1

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 : enter image description here

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,

JS1
  • 631
  • 2
  • 7
  • 23
  • Hello JS1, welcome to the community! why are you making an ajax call to read the csv file? Also, to be sure that the second one only executes once the first one is done, maybe you could run it at the .done() callback? – María Antignolo Feb 07 '20 at 08:19
  • I posted you a way to get the result object generated and test it before being sent to the url. Tell me if I understood you all right so I update it if not :-) BOL! – María Antignolo Feb 07 '20 at 08:43

2 Answers2

0

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:

function loadFile(filePath) {
  var result = {};
  var items = null;
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("GET", filePath, false);
  xmlhttp.send();
  if (xmlhttp.status==200) {
    items = xmlhttp.responseText;
  }
  result.items = items;
  return result;
}

Your first code would end up like this:

    var csvString = loadFile("./TEST_2.csv");
    var arr = csvString.split('\n');     

    var items = {};
    var headers = arr[0].split(',');
    for(var i = 1; i < arr.length; i++) {
      var data = arr[i].split(',');
      var obj = {};
      for(var j = 0; j < data.length; j++) {
         obj[headers[j].trim()] = data[j].trim();
      }
      items.push(obj);
    }

    var result = {}
    result.items = items;
    console.log(JSON.stringify(result));

Then you can check if the object was correctly built and run the ajax PUT that follows:

if (Array.isArray(result) && result.length) {
  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: '*****',
                  },
                processData: false,
                data: result,
               }

   $.ajax(settings).done(function(response) {
     console.log(response)
   });

}

María Antignolo
  • 388
  • 4
  • 17
  • Thanks for the answer, but it doesn't work with me it tell "require" is undefined – JS1 Feb 07 '20 at 09:19
  • updated it. can you check if works for you? i cant test it at the moment but i think it will put you on the right path. i think the issues with the initial code are 1) not checking if result exists before using it, 2)result was declared inside an independent ajax call. – María Antignolo Feb 07 '20 at 10:03
  • Thanks for the help, I tried to use directly the bufferString that you used in fiddle so I don't need to use require to see if there are other problems and there is still another error, "jsonObj is not defined" – JS1 Feb 07 '20 at 10:04
  • try replacing jsonObj with result here at the settings, i fixed the line at the asnwer:data: result, – María Antignolo Feb 07 '20 at 10:08
  • Thanks, there is another error, I guess it's not that bad but I have "Cannot read property 'split' of null" of this line "var arr = csvString.split('\n'); " – JS1 Feb 07 '20 at 10:38
  • "xmlhttp.open("GET", filePath, false);" there is also a warning at this one – JS1 Feb 07 '20 at 10:39
  • Not finding the file. Please check that the path to your file is correct – María Antignolo Feb 07 '20 at 10:40
  • Hello JS1, did you check if your file was found there? – María Antignolo Feb 09 '20 at 09:12
  • Hello mantingablue, sorry for not answering earlier, I found what it was, I should've put "if (xmlhttp.status==200 || xmlhttp.status==0)" instead of if "(xmlhttp.status==200)" because my file is in local and the request status is 0 by default – JS1 Feb 10 '20 at 09:32
  • So now I have the object in result but it's not in the right format to be integrated in the webservice database by the PUT, I have this in result : ["label;label","test1;test4","test2;test5","test3;test6",""] but the webservice is waiting for something like : '{\r\n "items": [\r\n "label|label", "test1|test4", "test2|test5", "test3|test6" \r\n ]\r\n}' so I get a 400 bad request in the console – JS1 Feb 10 '20 at 09:39
  • I think you don't menction at your question that you need the objects to be grouped inside a parent "items". Ill check on it as soon as i have a while – María Antignolo Feb 10 '20 at 12:55
  • updated! hope its good to go now and your question finally answered :-D – María Antignolo Feb 10 '20 at 13:10
  • Done ;);;;;;;;;;;;;;;;;; – JS1 Feb 11 '20 at 09:48
  • If you are getting bored, I'm now trying to do the opposite : https://stackoverflow.com/questions/60171456/generate-a-csv-file-from-a-json-object – JS1 Feb 11 '20 at 14:46
  • I checked on the go but trying to help when you cant do it perfect enough for other audience is hard here. I think the link at your question's comments along with this one here (https://stackoverflow.com/questions/13405129/javascript-create-and-save-file) may help. – María Antignolo Feb 11 '20 at 15:30
-1

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

gamusino
  • 1
  • 2