Good day guys, I'm using jQuery-form to submit a multipart form.
This is my PHP code:
foreach($addedData as $key => $value)
$result[$key] = $value;
echo json_encode($result);
Javascript:
function showResponse(responseText){
alert(responseText);
}
$('button').click(function(){
$("form").ajaxForm({
success: showResponse,
clearForm: true,
dataType: "json",
contentType: "application/json; charset=utf-8"
});
});
With this, the response was [object Object]. But when I removed these two lines:
dataType: "json",
contentType: "application/json; charset=utf-8"
The response became:
{"key1":"val1","key2":"va2","key3":"val3"}
My questions are: Do I really have to remove those two lines? And how can I get the values of the responseText
using Json?
If you specify dataType: 'json'
then your success
callback function will be passed the object the JSON represents, rather than a JSON string. jQuery implicitly handles converting the responseText to the object for you, so you don't have to do JSON.parse(responseText)
for yourself. If the response isn't valid JSON, the success
callback won't be executed; even if the AJAX request returned successfully.
To get the values out, just use responseText
like any other Javascript object; though you may want to give it a different name to make it clearer what it actually is.