There are some correct answers here, but there is one trigger that decides how you should handle the returned data.
When you use an ajax request and use the JSON data format, you can process the data in two ways.
- treat your data as JSON when returning
- configure your ajax call for JSON by adding dataType
See the following examples:
data line:
{"color1":"green","color2":"red","color3":"blue"}
ajax call without dataType:
$.ajax({
method: "post",
url: "ajax.php",
data: data,
success: function (response) {
var data = JSON.parse(response);
console.log(data.color1);
}
});
ajax call with dataType:
$.ajax({
method: "post",
url: "ajax.php",
dataType: "json",
data: data,
success: function (response) {
console.log(response.color1);
}
});
, , JSON.parse(), JSON. , .