jsonajaxpost.post

How to use ajax post request response data to make another ajax post request?


I need to make two ajax post request to an api url.The first request returns some data as json (password,session,sessionId,itemId).

could any one show me how i can grab password,session,sessionId,itemId values and use it to make another ajax post request to the same api url ?

My current code only gets api response but how to use value of password,session,sessionId,itemId in the second post request ?

I tried to reference the api data like this data.keys.password, data.keys.session ,data.items.seasonId , data.items.itemId and I get error data.keys and data.items are undefined!

Could anyone tell me what i am doing wrong ?

(Note:Currently i put the data in second post request hardcoded for demo purpose)

ajax post request call:

function callAjax() {


        $.post("https://api-somewebsite.com/process.aspx",
        {
          name: "galaxy",
          itemNum: "123456789"
        },
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
            // now i want to use api response data to make another ajax post call
             $.post("https://api-somewebsite.com/process.aspx",
             {
               password: "2342432423ledf",
               session: "23isaofdfjosidfiedfdd=="
               seasonId: "12345",
              itemId:    "334455"
             },
            function(data,status){
            alert("Data: " + data + "\nStatus: " + status);


             });

        });


};

<br>
<button onclick="callAjax()">callAjax</button> 

api response(for first ajax post request) that i want to reference its items:

{
     "keys": {
         "password": "2342432423ledf",
         "session": "23isaofdfjosidfiedfdd=="
     },
     "items": {
         "seasonID": 12345,
         "itemID": 334455,
}

}

Solution

  • We resolved the issue in chat.

    The first request doesn't have the Content-Type header set to JSON, so the response isn't getting parsed. Setting dataType to json (the last argument to $.post) correctly sets the header and the response will be parsed as JSON. This means that data is an object, whose properties can be accessed, rather than a string.