I have two arrays. Both are getting from two different $.each() functions.
var firstArray = ['item1', 'item2', 'item3', 'item4']; // **Dynamic Values
var counter = 0;
$.each(function(i, v){
//some code....
secondArray[counter] = $(this).val();
//secondArray have these values ['value1', 'value2', 'value3', 'value4']
counter++;
if(counter >= 4){
$.ajax({
type: 'POST',
url: customURL,
data: ?????
});
}
});
Actually i want the result like the 'item1' will get the 'value1', 'item2' to 'value2' and so on. In past when i used static values like -
$.ajax({
type: 'POST',
url: customURL,
data: {
'item1' : value[0],
'item2' : value[1],
'item2' : value[2],
'item3' : value[3],
}
});
i got the results using these static values but how could i use dynamic values instead of 'item1', 'item2' and so on. Remember the 'firstArray' values are dynamic means they can be changed. I am using only jQuery and HTML.
you only can send one data set with one request. so perhaps it's an option for you to merge your set before
Just sample code
let firstArray = [1, 2, 3, 4];
let secondArray = ['a', 'b', 'c'];
let dataSet = {
first: firstarray,
second: secondArray
};
$.ajax({
url: customUrl,
method: 'POST',
accepts: 'application/json',
dataType: 'json',
data: dataSet
})
.done((res, status, xhr) => {
// whatever you need to do
})
.fail((xhr, status, state) => {
// whatever you need to do
});
after that you have to handle the two arrays at backend
try this code
var firstArray = ['item1', 'item2', 'item3', 'item4']; // **Dynamic Values
var secondArray = ['value1', 'value2', 'value3', 'value4'];
var ajaxData = {}; // initial declaration with empty object
$.each(firstArray , function(i, v){
ajaxData[firstArray[i]] = secondArray[i];
});
$.ajax({
type: 'POST',
url: customURL,
data: ajaxData,
}).done(function(result){
//do something after success
});
Check out this fiddle for your ease: https://jsfiddle.net/syamsoul/zuncrx8q/4