Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript is not catching the correct list item from JQuery-AJAX [duplicate]

I have two functions main function which JQuery , and the other one in Javascript.

jQuery :

$(document).ready(function () {
  $('#ProvisionLink').click(function () {
    var queryTargetList = [ "Item1","Item2","Item3","Item4"]
    var data =  ["Data1","Data2","Data3","Data4" ]
    event.preventDefault();
    var i;

    for(i = 0; i < queryTargetList.length; ++i) {
          var dataItem = data[i];
          var QueryItems = queryTargetList[i];
          console.log("Before Launching the Javascript : " +QueryItems)
          $.ajax({
            url: '/operation',
            data: {DataType: dataItem,},
            type: 'POST',
            success: function (response){ getInventory(response,QueryItems) },
            error: function (error) {console.log(error);}
            });
    }

  });
});

Java script :

   function getInventory(data,queryTarget){
  console.log("In Get Inventory Function in javascript ... " +queryTarget)
  var queryTarget = "#"+queryTarget

  // get the query id
  const SelectBoxQuery = document.querySelector(queryTarget)
  console.log(SelectBoxQuery)
  // resetting the values to enter all the new one.
  SelectBoxQuery.options.length = 0; // reset the values

  // making a loop to reach each element item in the list
  for (var i = 0; i < data.length; ++i) {

    // add new element which is option to the targeted ID
    var SelectBoxQuery_Addition = document.createElement('option');

    // adding a text to that option
    SelectBoxQuery_Addition.text = data[i];

    // apply the adding .
    SelectBoxQuery.add(SelectBoxQuery_Addition)

  }}

The problem is, after i get response from python FLASK to Jquery function. in success part it should launch the javascript function with the same i of the queryTargetList.

for example if i pass data[1], i expect to have queryTargetList[1] also.

but in javascript console.log function. that does not happen. it printing the last item of the queryTargetList list.

Print:

Before Launching the Javascript : Item1
JQueryTests.js:11 Before Launching the Javascript : Item2
JQueryTests.js:11 Before Launching the Javascript : Item3
JQueryTests.js:11 Before Launching the Javascript : Item4
operationJavaScript.js:115 In Get Inventory Function in javascript ... Item4
In Get Inventory Function in javascript ... Item4
In Get Inventory Function in javascript ... Item4
In Get Inventory Function in javascript ... Item4

I do not know what am doing wrong :(

like image 945
Leivir Avatar asked Feb 03 '21 05:02

Leivir


Video Answer


3 Answers

Since the ajax call is an async operation, the loop variable i would have changed by the time the success method gets called. There is no guarantee that the i would have reached the end. You would need to wrap the variables, in a closure so that it success methods gets the correct item. Sample code not tested.

$(document).ready(function () {
$('#ProvisionLink').click(function () {
var queryTargetList = [ "Item1","Item2","Item3","Item4"]
var data =  ["Data1","Data2","Data3","Data4" ]
event.preventDefault();
var i;

for(i = 0; i < queryTargetList.length; ++i) {
      var dataItem = data[i];
      var QueryItems = queryTargetList[i];
      console.log("Before Launching the Javascript : " +QueryItems)
      (data,queryItem)=>{
         $.ajax({
           url: '/operation',
           data: {DataType: data,},
           type: 'POST',
           success: function (response){ getInventory(response,queryItem) },
           error: function (error) {console.log(error);}
        });
      })(dataItem,QueryItems);
}

});
 });
like image 84
gvmani Avatar answered Nov 15 '22 00:11

gvmani


set the async option to false:

 $.ajax({
            url: '/operation',
            data: {DataType: dataItem,},
            async: false,
            type: 'POST',
            success: function (response){ getInventory(response,QueryItems) },
            error: function (error) {console.log(error);}
            });

Another way: send queryTargetList[i] value to server and response get from server..

like image 26
MD. RAKIB HASAN Avatar answered Nov 14 '22 23:11

MD. RAKIB HASAN


You must consider the issue of synchronization and non-synchronization, because you did not set the async attribute, so the default will be true. The easiest way is to set the async attribute to false

Like my example below, for detailed usage, you can refer to here

  $.ajax({
    url: '/operation',
    data: {DataType: dataItem,},
    type: 'POST',
    async: false,
    success: function (response){ getInventory(response,QueryItems) },
    error: function (error) {console.log(error);}
  });
like image 20
Ian Avatar answered Nov 15 '22 00:11

Ian