php - Why is it that sometimes I have to JSON.parse() my AJAX response? -
i have non-uniformity how client-side jquery handles json ajax responses via server-side php.
here 2 example ajax calls have:
function checkorders() { $.ajax({ type: "post" , url:"/service/index.php" , data: { q: "checkorders" } , complete: function(result) { // note here json.parse() clause var x = json.parse(result.responsetext); if (x['unhandled_status']>0) { noty({ text: '<center>there <b>'+x['unhandled_status']+'</b> unhandled orders.', type: "information", layout: "topright", modal: false , timeout: 5000 } }); } } , xhrfields: { withcredentials: true } }); } note in above example have json.parse() responsetext php page in order deal object. somehow sees overall php response object, , have pull responsetext object , json.parse() it, in order use it.
now here ajax call have, whereby returned response, can use directly json response - meaning, somehow php page not return full "object" returns json , ajax call somehow knows json , not need json.parse() it:
function getunfiledorders() { $.ajax({ type: "post" , url:"/service/index.php" , data: { querytype: "getunfiledorders" } , success: function(result) { if (result['total_records'] >0) { noty({ text: result['response'], type: "error", modal: false, dismissqueue: true, layout: "topright", theme: 'defaulttheme' }); } } , xhrfields: { withcredentials: true } }); } in case, not need json.parse() responsetext in order treat response json object.
both php response scripts this:
header('content-type:application/json'); $array = array("total_records"=>3,"response"=>"success"); echo json_encode($array); can clue me in on non-uniformity?
edit:
i realized had 2 different callbacks in each of above ajax calls. 1 on complete , other on success.
when switched them both success returned response ajax request handled uniformly.
so guess question is:
- why there non-uniformity between these 2 callbacks?
- which better use?
i thoroughly reviewed docs on $.ajax() covered here.
anyway, simplicity complete , success have different variables loaded in function.
complete returns this:
complete
type: function( jqxhr jqxhr, string textstatus )
success returns this:
success
type: function( data, string textstatus, jqxhr jqxhr )
when have complete, first parameter returned object why have use:
complete: function(data) { var x = json.parse(data.responsetext); } as having fetch responsetext in object returned - , has string value (not formatted json).
the success function returns, first variable, whatever passed through php. in case json_encoded string. returns , can play around returned no further manipulation.
ta-dah!
in addition, note .success() gets called if server response 200, .complete() called regardless of status code
Comments
Post a Comment