I want to pass an array to my Ajax request so I can update multiple elements with the same query. Here is what I do:
My Ajax call:
$("body").on("focusout", "input", function () {
var id = ($(this).attr("id"));
var container = '#' + id + "_ck";
var data_type = ($(this).attr("data-type"));
var text = document.getElementById(id).value;
$.ajax({
url: 'ajax-php.php',
type: 'post',
data: { 'action': 'input_ck', 'id': id, 'text': text, 'data_type': data_type },
success: function (data, status) {
$(container).html(data); <-------------------------------- PHP RESPONSE
},
error: function (xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
});
Now I know that I can return an array so that the data contain my array in JSON.
Let's say that PHP returns this:
$arr($var1,$var2);
echo json_encode($arr);
Could I do something like this back in my jQuery Ajax script?
foreach(data as value){
i=0;
$(container[i]).html(data[i]);
i++;
}
I would also make an array out of containers. I'm not sure about the syntax here but would it be possible?
Yes of course you can, but you need to tweak around ajax properties to meet the expectation output of response like following :
$.ajax({
url: 'ajax-php.php',
type: 'post',
dataType : 'json', //<----- add here
data: { 'action': 'input_ck', 'id': id, 'text': text, 'data_type': data_type },
success: function (data, status) {
// $(container).html(data); <-------------------------------- PHP RESPONSE
// Add here
//i=0;
// you can either use $.each or forEach or native for loops here
$.each(data, function(i,e){ //< i = index, e = element
// i'm not sure with this selector
// you need to show what kind of container element did you have
$(container[i]).html(data[i]);// or easier if using e.property_name
//i++;
}
},
error: function (xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
PHP
$json = array('vals' => array($var1, $var2));
header('Content-Type: application/json');
echo json_encode($json)
Jquery
if(data.vals){
$.each(data.vals, function(key, value) {
$(container[key]).html(value);
});
}
Untested
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With