0

I am trying to send data using ajax and getting response

This is my ajax code

jQuery( document ).ready(function() {
    jQuery( "#district" ).change(function() {
        var lvType = jQuery(this).val();

        if(lvType == '')
        {
            alert('Please Enter District First');
            return false;
        }
jQuery.ajax({
        url: '../wp-content/plugins/sevaapkedwar/menu-pages/search.php?q='+lvType,
        type: 'get',
        dataType: 'text/html',
        success:function(data)
        {
        alert('ajax call finished successfully');
        },
        error: function (err) {
                console.log(err);
            } 
     });
});});

and my search.php code is

global $wpdb;
$q = $_GET['q'];
$get_m = "select * from `sevaapkedwar_area` where `district_name` = '$q'";
$get_st_l = $wpdb->get_results($get_m);
//print_r($get_st_l);
$json = array();
    foreach($get_st_l as $get_st_l){
      $json[] = array(
        'id' => $get_st_l->id, 
       'area' => $get_st_l->area_name 
      );
    }
    echo json_encode($json);

When I am running this code then in console the status of query is 200 OK with data [{"id":"8","area":"City1"}]

But I am unable to alert the message ajax call finished successfully

What I am missing

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rohitashv Singhal
  • 4,517
  • 13
  • 57
  • 105

1 Answers1

0

in ajax code, change dataType to json. dataType: The type of data that you're expecting back from the server. some of the possible values are - xml, json, script, or HTML. Reference: https://api.jquery.com/jquery.ajax/

dataType: 'json',

In the PHP code add header before the last echo statement.

header('Content-Type: application/json');
echo json_encode($json);

Reference: Returning JSON from a PHP Script

Now your code should work in the correct way. You can check/clone my working git repo for the ajax demo.

Pavan Yogi
  • 180
  • 2
  • 7