0

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?

1 Answer 1

1

Maybe so:

let patternVariable = { one: one,
                        two: two,
                        three: three };
let varriableJSON = JSON.stringify(patternVariable); 
response.write(varriableJSON);
response.end();
Sign up to request clarification or add additional context in comments.

2 Comments

This worked on the array, but on the objects I just get [object Object],[object Object], what i did was parsing as variable patternVariable, then: two = patternVariable.two; alert(two); Any idea what to do?
heh, [object Object] => alert(two.strength), alert(two.temp), alert(two.category) etc... or you can convert variable with object in string type, so => alert("${two.strength} ${two.category} ${two.temp}") and etc... alert don't work with object. You should learn theory by js))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.