I have 2 ajax functions in the same script and I want the result of the first one to be collect by the second one and send to the proper URL,
Here is my code :
<!DOCTYPE html>
<meta charset="utf-8"/>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url:"TEST_2.csv",
dataType:"text",
success:function(data)
{
var lines=data.split("n");
var result = [];
// NOTE: If your columns contain commas in their values, you'll need
// to deal with those before doing the next step
// (you might convert them to &&& or something, then covert them back later)
// jsfiddle showing the issue https://jsfiddle.net/
for(var i=0;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<currentline.length;j++){
obj=currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return result;
}
});
// Définition des paramètres et des entêtes de la requête avec l'identifiant de la liste dans l'URL
var listId = 261291
settings = {
"async": true,
"crossDomain": true,
"url": 'https://www.kizeoforms.com/rest/v3/lists/'+listId,
"method": 'PUT',
"headers": {
'content-type': 'application/json',
Authorization: '*****',
},
// Ajout des données dans le corps de la requête
processData: false,
data: result,
}
$.ajax(settings).done(function(response) {
console.log(response)
})
});
</script>
</html>
When I run the script on my browser I get this error in the console :
I don’t see how to pass the content of the “result” variable in the “data” of the “settings” variable which I then pass to my second ajax function,
I’m pretty new to ajax so I might be doing something totally wrong here,
Thank,
2
Answers
By defaults, Ajax is launched with async=true.
The second ajax call, can be alunched before the first have finished and result have not value.
For example, you can mark the first Ajax call to syncronous to wait for result is filled
I think you are building an array of json objects out of your csv file at your first block of code. Here’s a simpler yet effective way to do it:
Source answer is here: convert CSV lines into Javascript objects
Function to read the file:
Your first code would end up like this:
Then you can check if the object was correctly built and run the ajax PUT that follows: