WordPress plugin development – AJAX JSON data is sending correctly but PHP response is always 0, why?

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:

Read More
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…

Related posts

Leave a Reply

3 comments

  1. Because ANYTHING... isn’t correct json format. Try echo json_encode(array('msg' => 'test')); This causes that JQuery have a parsing error (not error from receive)

  2. Change the line in javascript from

    var data =  JSON.stringify({ action: 'process_json', value_name: 'value'  });//generic sample
    

    to

    var data =  { action: 'process_json', value_name: 'value'  };
    

    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}, to data: data,

    🙂 I miss that last time.

  3. OK, I got it using the following code:

    In main PHP plugin file:

    echo "<script src='URL PATH TO/ajax_file.js' type='text/javascript'></script>";
    
    add_action( 'wp_ajax_foobar', 'foobar_handler' );
    add_action( 'wp_ajax_nopriv_foobar', 'foobar_handler' );
    function foobar_handler() {
        // Handle request then generate response
        echo "ANYTHING..."; // do stuff here
        die(); // avoids extra 0 at the end of the response
    }
    

    In ajax_file.js: (referred to above in script tag)

    jQuery(document).ready(function($) {
    
       $('#id_to_submit_button').click( function() {
          var data = {
             action : 'foobar',
             Whatever : '1234',
          }
          ;
          // ajaxurl only needed for front - facing public pages, comment out for back end pages
          var ajaxurl = 'http://SITE_URL/wp-admin/admin-ajax.php';
          jQuery.post(ajaxurl, data, function(response) {
             alert('Got this from the server: ' + response);
          }
          );
       }
       );
    }
    );
    

    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…