To avoid a lot of ajax calls I am trying to send three variables through one Ajax response, but I am having trouble with how to process the data when it's been received on client. Below I will explain. If it is not recommended sending multiple variables with one response then please tell me why.
The server sends the response including three variables. one is just an array, two and three is mysql RowDataPacket objects. It looks like this:
let oneJSON = JSON.stringify(one);
let twoJSON = JSON.stringify(two);
let threeJSON = JSON.stringify(three);
response.write(oneJSON);
response.write(twoJSON);
response.write(threeJSON);
response.end();
The client code:
$.ajax({
type: "POST",
url: "http://localhost:3000/getthis",
data: {
"date": date,
},
success: function(data) {
alert(data);
/* not working:
let allvariables = JSON.parse(data);
alert(allvariables);
*/
}
});
On the client, I receive one JSON file that looks like this:
["cat1","cat2","cat3",null][{"strength":"10","temp":"10","category":"cat1"}][{"difficulty":"medium","category":"cat1"}]
Above code is created through alert(data);. As you can see every variable has "[ ]" around them.
So the data is received, but I don't know how to get the variables back again? I have tried to start with parsing it:
let allvariables = JSON.parse(data); alert(allvariables);
but this don't seem to work as no alert is created.
Any idea how I can retrieve the variables from the received JSON file?