Make jQuery ajax POST inside a loop

I have a bunch of data inside a loop that I would like to send POST to the server through jQuery.

My code is similar to the following:

var patients = [] // contains an array of patient objects I want to POST to server

var post = function(theUrl, theData, callback){
    $.ajax({
        type: "POST",
        url: theUrl,
        data: theData,
        success: callback,
        contentType: "application/json"
    });
}

var createdPatient = function(patient){
    //patient was created
}

$('#saveAll').click(function(event) {
    for (var i = 0;i < patients.length;i++) {
        var json = JSON.stringify(patients[i]);
        post("/openmrs/ws/rest/v1/patient", json, createdPatient);
    }
});

When I run the code, only the last patient was saved on the server. How can I fix this erroneous result?

+4
source share
1 answer

Using the promise returned jQuery.ajax(), you can write something more similar (see comments for details):

var patients = [...] // contains an array of patient objects to be POSTed to the server

$('#saveAll').click(function(event) {
    // first, map the `patients` array to an array of jqXHR promises as returned by $.ajax().
    var promises = patients.map(function(patient) {
        return $.ajax({
            type: 'POST',
            url: '/openmrs/ws/rest/v1/patient',
            data: patient, // jQuery.jax will handle js plain objects here. You may need to stringify here if patient is not a plain object.
            contentType: "application/json"
        }).then(function(data, textStatus, jqXHR) {
            return textStatus; // report successes in the form of the "textStatus" message (or anything you like).
        }, function(jqXHR, textStatus, errorThrown) {
            return $.when(textStatus || errorThrown); // report error on the success path, otherwise `$.when()` will bail out at the first error.
        });
    });
    // Now aggregate the `promises` array with `$.when()`
    $.when.apply(null, promises).then(function(results) {
        console.log(results);
    }, function(error) {
        // due to error handling above, you should never get here.
        console.log(error);
    });
});

See jQuery.ajax () and jQuery.when () for more details.

0
source

Source: https://habr.com/ru/post/1678658/


All Articles