I am triggering multiple AJAX requests in a loop. They run in parallel and it is not clear which one will respond first.
If the response is successful, I can identify the request by analyzing the response.
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
success: function (results) {
if (results.status == 'success'){
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log(error);
}
});
}
However, once in a while, the request fails and an error is triggered.
For a proper error handling, I would like to know to which of the (previously triggered) requests the error belongs.
Is there a clean method how a specific AJAX request can be identified?
I would recommend to pass in a identifier via context to the AJAX call which you can use inside the success or error methods:
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
// data inside "context" will be available as part of "this" in the success/error case.
context: {
"kk": kk
},
success: function (results) {
if (results.status == 'success'){
console.log("Element " + this.kk + " finished successfully.");
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log("Element " + this.kk + "failed.");
console.log(error);
}
});
}
More information regarding context can be found in the jQuery documentation.
Regarding your comment about checking how many calls failed / succeeded: here is a JsFiddle demonstrating how to keep track of the call statistics.
Related
Some reason I can return data fine from a POST in Chrome. The data returned looks like this when using Chrome:
{"email":"account#bytestand.com","customer_id":20413,"credit_amount":50.0,"currency_symbol":"$"}
But then when the same POST is completed on FireFox I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Somehow the data isn't being handled the same and I don't know why.
Here is the code that generates the ajax request
function getCustomerAndCredit() {
console.log("getCustomerAndCredit");
$(function() {
$("form[action='" + shopAddress + "/account/login']").submit(function(event){
console.log("this is past the submit event in Firefox");
var custEmail = $("form[action='" + shopAddress + "/account/login'] input[type=email]").val();
var pass = $("form[action='" + shopAddress + "/account/login'] input[type=password]").val();
sessionStorage.setItem('custEmail', custEmail);
sessionStorage.setItem('pass', pass);
sessionStorage.setItem('loggedIn', true);
debugger;
$.ajax({
url: "/apps/proxy/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "js",
complete: function(data) {
debugger;
if(noCustomerInDB(data)){
if(data.responseJSON == undefined){
sessionStorage.setItem('customer_id', JSON.parse(data.responseText).customer_id);
sessionStorage.setItem('creditAmount', JSON.parse(data.responseText).credit_amount);
sessionStorage.setItem('currency', JSON.parse(data.responseText).currency_symbol);
}
else {
sessionStorage.setItem('customer_id', data.responseJSON.customer_id);
sessionStorage.setItem('creditAmount', data.responseJSON.credit_amount);
sessionStorage.setItem('currency', data.responseJSON.currency_symbol);
}
}
// console.log("What is the credit_amount here in getCustomerAndCredit " + sessionStorage.getItem('creditAmount'));
},
});
});
});
}
And then this is where the data is going:
function noCustomerInDB(data){
console.log("this is the todd variable " + data);
console.log("stringify data " + JSON.stringify(data));
console.log("what about just data?? " + JSON.parse(data));
console.log("this is the response down here in the no customer function" + data.responseText);
if(data.responseText == ""){
return false;
}
else{
if (JSON.parse(data.responseText).customer_id == "no_customer"){
sessionStorage.setItem('creditAmount', "null");
return false;
}
else{
return true;
}
}
}
I did some more digging and now its looking like the ajax isn't being called on FireFox. Because the data returned from the POST looks like this:
{"readyState":0,"status":0,"statusText":"error"}
This cannot be - dataType: "js"
Use dataType: "json" instead. Also make sure that "/apps/proxy/return_customer" has the proper header configured to deploy JSON:
"Content-Type: application/json"
So I'm trying to pass a variable Boolean "state" (true/false) to a server from an HTML file.
<script>
$("#aaa").click(function () {
$(this).hide('slow');
$("#bam").html(shay + " arrived ").hide().show(700);
childName = true;
counter++;
if (counter > 12) {
$("#bam").html("All have arrived").hide().show(700);
}
});
</script>
I have multiple instances of this function for each kid arriving to school. The name of the kid's variable equals to true upon clicking his name. What I'd like to do is send these variables' Boolean state to a server, so I'll be able to remotely know what's each kid's "state". Is there a way to do it with jQuery's Post method? If not, what is the most simple way? Thanks!
Yes you can do
<script>
$("#aaa").click(function () {
$(this).hide('slow');
$("#bam").html(shay + " arrived ").hide().show(700);
childName = true;
$.post("url",
{
childStatus: childName,
},
function(status){ // return from server
});
counter++;
if (counter > 12) {
$("#bam").html("All have arrived").hide().show(700);
}
});
</script>
You can post any thing to server with jquery post method like bellow example:
$("#aaa").click(function () {
$(this).hide('slow');
$("#bam").html(shay + " arrived ").hide().show(700);
childName = true;
counter++;
$.post("destination.asp", {childStatus: childName}, function(result){
// do any thing
});
if (counter > 12) {
$("#bam").html("All have arrived").hide().show(700);
}
});
You can have an id for each child. And add an event listener which sends data to server. For example,
HTML:
<button id="id_001" class="childBtn">Arrived</div>
<button id="id_002" class="childBtn">Arrived</div>
<button id="id_003" class="childBtn">Arrived</div>
jQuery:
$(".childBtn").click(function(){
$.post('http://yourserver.com/api', { childId : $(this).attr('id')},
function(data, status) {
//alert("Data: " + data + "\nStatus: " + status);
}
});
I hope that helps :)
Yes, please check out the documentation for .ajax(): official documentation
Could look something like this:
$.ajax({
type: 'POST',
url: 'your-endpoint-url', // the endpoint for the call
data: childName,
success: function(response){
console.log('AJAX success: ' + response);
// maybe do something else here ...
},
error: function(error, status, xhr){
console.log('AJAX error: ' + error);
console.log('STATUS: ' + status + ', XHR: ' + xhr);
}
});
Side note: you say you have multiple instances of this function; then why assign the click function to a DOM element ('#aaa'), rather than doing this through a (e.g.) class selector (give your schookid-rows a css class '.schoolkid' and assign the click function via the class selector)
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
I have a website where I rely on a lot of custom API call. My API return always an XML.
Currently, at the start of each and every $.get or $.post I call, I have this snippet :
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
However, I feel this code to be much redundant on one of my page, it's used 15 times.
I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here
Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?
I assume that you have something like this in many places in your code
$.ajax({
method: "GET",
url: "someurl.html",
dataType: "xml",
success : function() {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
// ...
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
});
you could create a generic custom ajax function tha you can re-use
function baseAjaxCall(option, sCb) {
var ajaxOptions = {
method: option.method || "GET",
url: option.url,
dataType: option.dataType || "xml",
success : function(data) {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
else {
sCb(root);
}
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
};
//you can check for optional settings
if(option.contentType !== undefined){
ajaxOptions.contentType = option.contentType;
}
$.ajax(ajaxOptions);
}
everywhere in your code you can re-use the baseAjaxCall function
baseAjaxCall({ url: "someurl.html" }, function(root){
// no need to chek for errors here!
});
Hope it's helps!
I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}