PHP: how to extract ajax array response

17,309

Solution 1

You should echo that $response with json_encode().

You should probably set dataType: 'json' too inside the object literal you send to $.ajax().

Then you can access it natively with JavaScript using the dot operator inside your success callback...

function(msg) {
    alert(msg.html);
}

BTW, this line...

$response = array(['msg'] => 'Hello', 'html' => '<b>Good bye</b>');

... isn't valid PHP. Remove the brackets from the first key.

Solution 2

My favorite solution for this is to encode array with PHP's function json_encode() so jquery will be happy to parse it.

Share:
17,309
gautamlakum
Author by

gautamlakum

I help startups and enterprises go ahead with their digital products. Product Designer. Design Sprint Facilitator.

Updated on June 04, 2022

Comments

  • gautamlakum
    gautamlakum almost 2 years

    I am getting ajax response in array format from php url. How to extract array response values in jQuery? FYI:

    PHP array is:

    $response = array('msg' => 'Hello', 'html' => '<b>Good bye</b>');
    

    I am getting $response array in my ajax response. i.e.

    var promo = "promo=45fdf4684sfd";
    $.ajax({
        type: "POST",
        url: baseJsUrl + "/users/calc_discount",
        data: promo,
        success: function (msg) { // I am getting $response here as ajax response.
            //alert(msg);
    
            // Here I want to check whether response is in array format or not. if it is in array format, I want to extract msg here and want to use response array values.
        }
    });
    

    Let me know answer pls. Thanks.

  • Emil Vikström
    Emil Vikström over 13 years
    PHPJS's json_encode and _decode only works on JS objects, not on PHP equivalents.
  • Satya Prakash
    Satya Prakash over 13 years
    Yes, Emil. You are right. I have not tested every function there but according to the way they are doing that json_encode/decode should work the same way as PHP counterpart is working. I have used few functions from there and that was working in correct way. Thanks for pointing the error.
  • Hexodus
    Hexodus about 10 years
    Does your example really work? I have to parse the response first to got a result like this: var obj = jQuery.parseJSON(msg); alert(obj.html);
  • user3167101
    user3167101 about 10 years
    @Hexodus Depends on what jQuery function you're using to read it. If you tell it the response type is json, it will automatically parse it (which you should be doing).