Reputation: 12015
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.
Upvotes: 1
Views: 17337
Reputation: 3502
and If you do not have control over the PHP output then you can use another method to get the result. Another solution is using http://phpjs.org/ library. Here you can find many functions available in JS as available in php. Usage is also same as that of PHP. So I feel if you get the json_encode/json_decode from there and use that then it can solve your problem easily.
Remember you can compile your needed functions only. In your case, it is json_encode and json_decode. No need to download whole library. Url to compile your library: http://phpjs.org/packages/configure
Upvotes: 0
Reputation: 490153
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.
Upvotes: 8
Reputation: 91902
I presume that you mean a JSON response, like this:
{"msg":"Hello","html":"<b>Good bye<\/b>"}
This is actually a native JS object, so you can use it right away like this:
success: function(msg){
alert(msg.msg);
alert(msg.html);
}
You can also use the jQuery.each() function to loop over all properties of the JSON object if you need to:
jQuery.each(msg, function(key, val) {
alert(key + "=" + val);
});
Upvotes: 0
Reputation: 17275
My favorite solution for this is to encode array with PHP's function json_encode() so jquery will be happy to parse it.
Upvotes: 1