0

I've been trying to send an array from PHP to javascript so I can display search results from a database. I have converted the array into JSON and now can't seem to retrieve it. I've never used AJAX but I have some people that work here that have and no one has been able to figure out the exact problem (granted not a lot of their time has been spent on it)

 $(document).ready( function() {
     var data = {};
     $.ajax({
         type: 'GET',
         url: '../wp-content/plugins/advantage-geo/get_data.php',
         data: "data",
         dataType: 'json',
         cache: false,
         success: function(result) {
            alert(result.d);
            console.log(result);
         },
         error: function(XMLHttpRequest, textStatus, errorThrown) { 
         alert("Status: " + textStatus); alert("Error: " + errorThrown); 
      }    
   });
});

That is the call from the JS file. (It closes with }); but it wasn't being taken into the code block so I removed it.)

The following is the PHP

<?php 

header("Content-type:json");

global $wpdb;

$sql = "SELECT * FROM wptest_geo_db";
$result = $wpdb->get_results($sql) or die(mysql_error());


echo json_encode($result);

print_r(json_decode($person_array));
print_r($person_array);

?>

The JSON is created properly and I can display that on the page from the php file. The AJAX call is throwing an 500 Internal Server Error and I don't know why.

dHantke
  • 27
  • 5

1 Answers1

1

My answer may not directly talk about the 500 Server Error but going through my answer might help you fix that.

AJAX call doesn't need you to send the HTTP request type as JSON so you just need to output the encoded JSON as string. AJAX will identify it as JSON data, you even don't need to tell jQuery AJAX that you're expecting JSON data, it'll identify.

<?php 
    // it's not required that the response HTTP request is of type JOSN
    // just ignore this
    //header("Content-type:json");

    global $wpdb;

    $sql = "SELECT * FROM wptest_geo_db";
    $result = $wpdb->get_results($sql) or die(mysql_error());

    echo json_encode($result);

    // you've echo-ed the encoded JSON just above
    // why would you print the arrays?
    // I assume it's for testing purpose
    //print_r(json_decode($person_array));
    //print_r($person_array);
?>

Now, onto WordPress AJAX. You're doing it totally incorrect. Please look at this document to see how to handle AJAX in WordPress https://codex.wordpress.org/AJAX_in_Plugins. Test and trial what's in the linked AJAX tutorial/document and come back here if you face any issues while trying so.

Junaid
  • 1,270
  • 3
  • 14
  • 33
  • 1
    As per documentation you should also include the *wp_die();* at the end of the example. – Musk Jul 20 '17 at 16:58
  • @Musk You're right, but that is part of when WP AJAX is implemented. Right now, this isn't even near WP AJAX – Junaid Jul 20 '17 at 18:08