I have tried to send serialized data via wordpress admin ajax, but i am getting output in below format instead of serialized format.


Jquery Ajax Code Below

            type: 'POST',
            dataType: 'json',
            url: ajax_reviewer_object.ajaxurl,
            data: { 
                'action': 'reviewer_action', //calls wp_ajax_nopriv_ajaxlogin
                'post_data': $('#approval_system').serialize()
            success: function(data){

PHP Function Below:

function reviewer_action_callback(){
    $ss = $_POST['post_data'];

add_action( 'init', 'reviewer_action' );
function reviewer_action() { 

    wp_localize_script( 'ajax-post-script', 'ajax_reviewer_object', array( 
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'load_msg' => plugins_url('lyca-draft-approval/assets/img/ajax-loader.gif')
    //add_action( 'wp_ajax_nopriv_ajax_post', 'ajax_post' );
    add_action( 'wp_ajax_reviewer_action', 'reviewer_action_callback' );
  • 2
    This is the correct format for .serialize() method. jQuery documentation – nmr Apr 11 at 12:00
  • What is the pre function? Is there a particular reason not to use JSON or the REST API? – Tom J Nowell Apr 11 at 12:13

Instead of relying on bespoke/custom serialising, and the ancient admin AJAX, consider using JSON and the REST API, e.g.:

add_action( 'rest_api_init', function () {
        register_rest_route( 'ramkumar/v1', '/test/', array(
                'methods' => 'POST',
                'callback' => 'ramkumar_rest_test'
        ) );
} );

function ramkumar_rest_test( $request ) {
    $reviewer_notes = $request['reviewer_notes'];
    $result = ....;
    return $result; // gets sent to the browser as JSON, so return an object/array/etc

Now we have yoursite.com/wp-json/ramkumar/v1/test and can poke it like this:

    url: "/wp-json/ramkumar/v1/test",
    data: { review_note: "hello I'm a reviewer" }
}).done(function( data ) {
    // json decode data and do stuff with it

This also has the benefit of being more debuggable, easier to use, etc. The REST API can accept multiple extra parameters telling it how to validate, sanitise, and authenticate the request. It will also tell you in plain english what you did wrong if you make a mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.