How to get api data using jquery ajax?

10,752

Please check below code

<select name="city" id="city">
    <option value="">Select City</option>
    <option value="delhi">delhi</option>
    <option value="ghaziabad">ghaziabad</option>
    <option value="noida">noida</option>
    <option value="meerut">meerut</option>
</select> 

Ajax Called

<script>
    $(document).ready(function(){
        $("#city").change(function(){
            name = $(this).val();
            /*For PHP called is for Cross-Origin Request Blocked*/
            $.ajax({
               type:"GET",
               dataType: "json",
               data:{name: name},
               url:"test.php",
               success:function(data)
               {
                   alert('Get Success');
                   console.log(data);
               }
            });
        });
    });
</script>

PHP file code for Cross-Origin Request Blocked -

<?php 
$name_city = rawurlencode($_GET['name']);
$url = "http://postalpincode.in/api/postoffice/".$name_city;
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,"$url");
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_HEADER, false);
$postoffice_data = curl_exec($curl_handle);
curl_close($curl_handle); 
$postoffice_data = json_decode($postoffice_data);
echo json_encode($postoffice_data);
exit;
?>
Share:
10,752
Rudra
Author by

Rudra

Updated on June 24, 2022

Comments

  • Rudra
    Rudra almost 2 years

    In this code I have a normal dropdown where I have some city name. Now, What I actually want when I change any city then through jquery I want to get json data in my alert box which is not working yet. I don't know why? So, How can I do this?

    $(document).ready(function() {
      $("#city").change(function() {
        name = $(this).val();
        console.log(name);
        $.ajax({
          type: "POST",
          dataType: "json",
          data: {
            "name": name
          },
          url: "http://postalpincode.in/api/postoffice/" + name,
          success: function(data) {
            console.log(data);
          }
        });
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select name="city" id="city">
      <option value="">Select City</option>
      <option value="delhi">delhi</option>
      <option value="ghaziabad">ghaziabad</option>
      <option value="noida">noida</option>
      <option value="meerut">meerut</option>
    </select>