I must be missing something simple here. Firebug shows data being sent exactly as it should in NET tab (NET tab-> Post -> Parameters). PHP function will not even echo simple text.
The PHP:
add_action('wp_ajax_nopriv_process_json', 'process_json_received');
add_action('wp_ajax_process_json', 'process_json_received');
function process_json_received(){
echo "ANYTHING...";
exit;
}
The JS/Jquery (sending correctly)
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
$.ajax({ url: 'http://localhost:12345/site_name/wp-admin/admin-ajax.php',
data: {data: data},
type: 'post',
dataType: 'json',
success: function (response) {
alert("Got this from the server: " + response);
console.log( response );
$('body').append(response); // <-- Append the ajax response to the page body
},
complete: function(XMLHttpRequest, text_status) {
},
error: function (response) {
alert("Error getting php file");
}
});
Again, it doesn’t matter what is in the PHP function, the response is always 0. It could be an “enqueue_scripts” thing but ajax request is sending exactly as it should. NET tab in Firebug shows perfect json data so the problem has to be with the PHP function (or correct access to it). Maybe WordPress is somehow blocking it??? Has to be something simple – I’m hoping a fresh set of eyes will help. Thanks in advance…
Because
ANYTHING...
isn’t correct json format. Tryecho json_encode(array('msg' => 'test'));
This causes that JQuery have a parsing error (not error from receive)Change the line in javascript from
to
WordPress expect POST Data so it can read $_POST[‘action], you should never Stringify it, but use core javascript object only.
Read more about it : http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
EDIT:
Also change
data: {data: data},
todata: data,
🙂 I miss that last time.
OK, I got it using the following code:
In main PHP plugin file:
In ajax_file.js: (referred to above in script tag)
As soon as I included the script in this way it worked, it would not when placed in a PHP function as many sources suggest. I tried soooo many other ways that should have worked. I went step by step on the WordPress codex pages (many times) and several other tutorials. Enqueueing scripts, registering scripts, following all recommended practices. I still don’t understand why this way works for me and all the other “correct” ways didn’t. Could be something in my local server environment. Big thanks to those who answered and tried to help. God knows I have gotten the quick answer on StackOverflow enough times, I hope this saves someone the long hours I spent testing and troubleshooting…