My ajax
response seems to be interpreted as text even though the ajax
request contains datatype: "json"
. My understanding is that header
line in the php script below should have no effect, and yet it fixes my problem.
Can anyone explain this behavior?
I am calling the following javascript function:
async function ajaxTest() {
$.ajax({
url: 'test_ajax_response.php',
type: 'POST',
datatype: "json",
data: {
'foo': 'bar'
},
success: function(response) {
console.log('first element of returned array: ' + response[0]);
console.log('length of returned array: ' + response.length);
}
});
}
Here is test_ajax_response.php
:
<?php
header("Content-Type: application/json", true);
$bar = $_POST['foo'];
$my_arr = array($bar);
echo json_encode($my_arr);
?>
The console output is
first element of returned array: bar
length of returned array: 1
If I comment the header
line the console output is
first element of returned array: [
length of returned array: 7
Same behavior in Chrome and Firefox.