Reputation: 265
I am creating a wordpress plugin that consist a form with Ajax Functionality.
I am able to see the json array as below in console tab while debugging.
Note: Error Function in Ajax Call displays below result:
Object {readyState: 4, responseText: "[{"id":"1","school_name":"Apollo Beach Elementary …lo Beach","rating":"A","type":"Elementary"}]Array", status: 200, statusText: "OK"}
Here is the Ajax Code
function ajaxformschool() {
jQuery.ajax({
url: ajaxschoolajax.ajaxurl,
data: {'action':'ajaxschool_process'},
dataType: 'json',
type: "POST",
success: function(data) {
alert(data[0]);
},
error:function(exception){console.log(exception);}
});
}
Html link where the function is called
echo '<a onclick="ajaxformschool();" style="cursor: pointer"><b>Search</b></a>';
Ajax Action Function
function ajaxschool_process() {
global $wpdb;
$data = $wpdb->get_results ("SELECT * FROM schools;");
echo json_encode($data);
die($data);
}
Upvotes: 1
Views: 801
Reputation: 6994
Try it....
Ajax Code
function ajaxformschool() {
jQuery.ajax({
url: ajaxschoolajax.ajaxurl,
data: {'action':'ajaxschool_process'},
dataType: 'json',
type: "POST",
success: function(data) {
var result=eval(data);
alert(result.id);
},
error:function(exception){console.log(exception);}
});
Ajax Action Function
function ajaxschool_process() {
global $wpdb;
$data = $wpdb->get_results ("SELECT * FROM schools");
echo json_encode($data);
die();
Upvotes: 1
Reputation: 299
Don't pass any parameter with die()
function ajaxschool_process() {
global $wpdb;
$data = $wpdb->get_results ("SELECT * FROM schools;");
echo json_encode($data);
die();
}
Upvotes: 1
Reputation: 418
Do not pass $data
in die()
function :
$data = $wpdb->get_results ("SELECT * FROM schools;");
echo json_encode($data);
die();
die() tries to print the value passed in parameter, then prints "Array", so jQuery can't parse the JSON data since it's not a valid JSON.
Upvotes: 1