Catching an AJAX error from a post request (422) - ajax

I have the following Ajax but it needs to handle a 422 error being returned (which means Out of Stock). I've tried a few ways around but it error's and refuses to POST stating:
Failed to load resource: the server responded with a status of 422 ()
I'm unsure how to catch the 422 error and return something to the user displaying that it's out of stock.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id='+ request.variant_id + '&quantity='+request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res){
Shopify.moveAlong();
},
error: function(){
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length){
Shopify.moveAlong()
}
}
});
}
else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();

I've tried a few ways around but it error's and refuses to POST.
What I have understood is, you are seeing this error in Browser console. It cannot be prevented, but it does not mean that you request is not going through. The POST request is recieved by Shopify and a response with status 422 is sent, so that is treated as an error (Non 2xx response codes are treated as error).
To handle the error and display error message, adapt the code accordingly. Check updated code and code comments.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id=' + request.variant_id + '&quantity=' + request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res) {
Shopify.moveAlong();
},
error: function(jqXHR, textStatus, errorThrown) {
// Check status code
if (jqXHR.status === 422) {
// display error wherever you want to
console.log(jqXHR.responseText);
}
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length) {
Shopify.moveAlong()
}
}
});
} else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
AJAX Error Docs

Related

Ajax call always triggers fail handler even though success is returned by the server

The following JavaScript always triggers the fail handler even though the return value is success from the server side:
$.ajax(payload)
.done(function(data, statusText, jqxhr) {
document.getElementById('myModal').innerHTML = "<p>Record Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.fail(function(jqxhr, statusText, errorThrown) {
document.getElementById('myModal').innerHTML = "<p>Record Not Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.always(function () {
// Re-enable the inputs
$inputs.prop("disabled", false);
});
Returned JSON string:
[{"result":"success","row":11}]
Any thoughts?
Good news. I was able to crack it. The solution was as follows:
Set up a call back function in the payload
Have a dummy action in the newly created call back function
Prefixed the call back function name in the server side while creating the jasonp response
Client side:
function handleJSONPResponse(data, status, request) {
console.log('response', data);
}
// Fire off the request to /form.php
var payload = {
crossDomain: true,
url: "https://script.google.com/macros/s/XXXXXXXXXXXXXXXXX/exec",
method: "POST",
dataType: "jsonp",
data: serializedData,
jsonpCallback: 'handleJSONPResponse'
};
Server Side (e is the payload sent from client):
return ContentService
.createTextOutput(e.parameters.callback + '(' + JSON.stringify({"result":"success", "row": nextRow})+ ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
It was wonderful solving the problem. Thank you very much for your kind inputs and encouragement. Much appreciated.

XMLHttpRequest 400 Bad request during AJAX call on second request

I have some weird issue in which during AJAX call in MVC with POST method it will return 400 BAD Request randomly after second / third call on server but in local system it works properly.
I have pass same parameter during each call but randomly it will return 400 error on server.
Below is my AJAX call code:
function RunSimulation() {
ShowProgress();
var url = GetDomainURL() + "/Project/RunSimulation";
var data = $("form").serialize();
var random = Math.random();
alert('multipart/form-data;charset=UTF-8; boundary='+random);
$.ajax({
url: url,
type: 'POST',
data: data,
async: false,
cache: false,
contentType: 'multipart/form-data;charset=UTF-8; boundary='+random,
// timeout: 60000 * 10,
success: function (data) {
alert('sucess');
HideProgress();
},
error: function (jqXHR, textStatus, errorThrown) {
HideProgress();
}
});
}
I have stuck in this issue in last 2 days so please help me if anyone have any idea on this.
Below is my request body
__RequestVerificationToken=n96WSaViL9XKPZZArj0aqnGTxMGts5P5OJxO9-PdgcJUjoB3HKcK3_LPHa4I3IbDDModNpFl6RLxDSrr7eYOmIBOzQS99NSUyF6V9Zl-wtMVRaVPU_KomFXie58t8EjEhNhCHGxcM-9V-bZHC0_8twzFxaEkef6lwOtbhGfIx7E1&TabIndex=5&SubmitIndex=0&Mode=&ProjectHeader.ProjectHeaderId=79&SiteInformation.CalculateAnnualPercentage=False&SiteInformation.IsOSRSizing=True&ProjectHeader.SiteCount=2&hdnUserType=2&hdnUserOSR=True&ProjectHeader.ProjectHeaderId=79&ProjectHeader.Region=1&ProjectHeader.Country=Canada&ProjectHeader.State=AB&ProjectHeader.ProjectName=Test+Project&ProjectHeader.City=&ProjectHeader.ProjectNumber=79&ProjectHeader.DominantLand=2&ProjectHeader.OtherState=&ProjectHeader.ProjectDate=09%2F09%2F2015&ProjectHeader.ProjectDesignBy=vaibhavi+pandya&ProjectHeader.Notes=&ProjectHeader.FirstName=vaibhavi&ProjectHeader.LastName=pandya&ProjectHeader.Email=vpandya%40conteches.com&ProjectHeader.PhoneNumber=878-787-8787&ProjectHeader.Company=ei&ProjectHeader.EORFirstName=&ProjectHeader.EORLastName=&ProjectHeader.EOREmail=&ProjectHeader.EORPhoneNumber=&ProjectHeader.EORCompany=&SiteInformation.RainFallStationName=EDMONTON&SiteInformation.RainFallStation=1&SiteInformation.RainFallStationName=EDMONTON&SiteInformation.RainFallStationState=Alberta&ManageRainFallStation.RainFallStationFilter.State=Alberta&ProjectHeader.Country=Canada&ManageRainFallStation.RainFallStationFilter.SelectedCountry=&ManageRainFallStation.RainFallStationFilter.Location=&SiteInformation.PeakRainfallIntesityCkecked=false&SiteInformation.PeakRainfallIntesityCkeckedValue=0.00&StationState=&SiteInformation.ProjectHeaderId=79&SiteInformation.SiteId=127&SiteInformation.SiteName=Site+1+&SiteInformation.SiteArea=5&SiteInformation.Imperviousness=60.0&SiteInformation.TSSRemoval=80.0&SiteInformation.peakConvey=&SiteInformation.RunOff=&SiteInformation.WQF=&SiteInformation.IsOilPara=False&SiteInformation.OilParaValue=&SiteInformation.Width=447.00&SiteInformation.Slope=2&SiteInformation.ImperviousD=0.518&SiteInformation.PerviousD=5.08&SiteInformation.ImperviousM=0.015&SiteInformation.PerviousM=0.25&SiteInformation.MaxI=61.98&SiteInformation.MinI=10.16&SiteInformation.DecayRate=0.00055&SiteInformation.RegenerationRate=0.01&SiteInformation.DailyEvap=2.54&SiteInformation.Flow=0&SiteInformation.Freq=12&SiteInformation.FilterationWinterMonthsChecked=false&SiteInformation.WinterStartMonth=&SiteInformation.WinterEndMonth=&SiteInformation.InletInvertElev=&SiteInformation.PipeDiameter=&SiteInformation.OutletInvertElev=&SiteInformation.PipeMaterial=&SiteInformation.RimElev=&SiteInformation.IsMultipleInlets=False&SiteInformation.WaterLevelElev=&SiteInformation.IsGrateInlet=False&SiteAttenuationManage.ManageSiteAttenuationList%5B0%5D.Flow=0.00000&SiteAttenuationManage.ManageSiteAttenuationList%5B0%5D.Storage=0.00000&SiteAttenuationManage.ManageSiteAttenuationList%5B0%5D.IsDeleted=False&SiteInformation.UpstreamFlowDiversionValue=0.00000&SiteInformation.ParticleDistribution=5&SiteInformation.IsRainfallOSRAuthorized=False&SiteInformation.IsUserOSRAuthorized=False&SiteInformation.NoNullIsOSRSizing=True&SiteInformation.NoNullIsOSRSizing=true&SiteInformation.NoNullIsOSRSizing=false&SiteInformation.IsFlocc=true&SiteInformation.IsFlocc=false&SiteInformation.Flocc=20&ManageTSSFunction.ManageTSSFunctionList%5B0%5D.Name=Build+Up%2F+Wash-off&ManageTSSFunction.TSSRblValue=1&ManageTSSFunction.ManageTSSFunctionList%5B1%5D.Name=Event+Mean+Concentration+(EMC)&ManageTSSFunction.ManageTSSFunctionList%5B2%5D.Name=Power+Wash-off&ManageTSSFunction.ManageTSSFunctionList%5B3%5D.Name=Power+Wash-off+(Winter+Only)&SiteInformation.BuilUpPower=0.40&SiteInformation.ExpoWashOff=0.20&SiteInformation.TargetEvent=125.00&SiteInformation.AvailabilityA=0.05&SiteInformation.AvailabilityB=0.04&SiteInformation.AvailabilityC=1.10&SiteInformation.PSAvailability=400.00&SiteInformation.PowerWashOffFactor=0.08&SiteInformation.PowerWashExp=1.15&SiteInformation.PWWinterStartMonth=1&SiteInformation.PWWinterEndMonth=1&SiteInformation.EMC=444.00&SiteInformation.WinterSand=&SiteInformation.SandingStartMonth=&SiteInformation.SandingEndMonth=&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.ParticleDiameter=0.00&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.Percentage=0.00&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.SpecialGravity=0.00&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.IsDeleted=False&SiteInformation.CalculateAnnualPercentage=false&SiteInformation.RecommendedModel=OSR+4000%0D%0A&SiteInformation.SiteId=127
This was hinted at in comments, but why are you setting Content-Type to use multipart/form-data? You are not sending multipart/form-data, you are sending application/x-www-form-urlencoded data. There is no "multipart" attachment, so no boundary is required.
Try removing altogether the contentType line in your ajax call; the Content-Type will default to application/x-www-form-urlencoded, which is what is needed.
Also, better use async: true otherwise your page will be unresponsive while it blocks waiting for a response to the ajax request - unless that's what you want.
I am not sure that this is the cause of the 400 bad request errors, but at least this removes one possibility.
I have use below code as per your suggestions during AJAX Call
function RunSimulation() {
ShowProgress();
var url = GetDomainURL() + "/Project/RunSimulation";
var data = $("form").serialize();
var random = Math.random();
$.ajax({
url: url,
type: 'POST',
data: data,
async: true,
cache: false,
// timeout: 60000 * 10,
success: function (data) {
alert('sucess');
HideProgress();
},
error: function (jqXHR, textStatus, errorThrown) {
HideProgress();
}
});
}
But still get error as shown below
Bad Request Error

While converting from jquery to angularjs why am I getting this error?

Jquery Code
$.ajax({
url: '/ad_creation/get_campaign_objective/'+id,
dataType: 'text',
success: function(response) {
var campaign_objective = 'Error. Please refresh and try again.';
if (response == 'WEBSITE_CONVERSIONS')
campaign_objective = response;
if (response == 'WEBSITE_CLICKS')
campaign_objective = response;
$('select[name=campaign_objective]').val(response).hide();
$('#existing-campaign-objective').html(campaign_objective).show();
$('#campaign-objective-select').show();
if (campaign_objective == 'WEBSITE_CONVERSIONS'){
// Show pixel block again.
$('#select-pixel').show();
}
hideAjaxLoader('existing-campaign-loader');
},
error: function(xhr, ajaxOptions, thrownError) {
console.log('Invalid response', thrownError, xhr, ajaxOptions);
hideAjaxLoader('existing-campaign-loader');
}
});
Angularjs code
$http({
method:'get',
dataType:'text',
url:'/ad_creation/get_campaign_objective/'+Number(id)
})
.success(function(data){
console.log(data);
})
I get the error Unexpected token w. I have also tried not casting the id to number but still get the error.
Check the content-type of the response headers.
If it is 'application/json' angular tries to parse the response.
The error might be because of it.

CORS is driving me crazy - intermittent issues

It seems like I've tried everything and I finally just switched to using the CORS npm module:
var cors = require('cors');
And my one route I want to use CORS on:
app.post('/hangouts', cors(), hangoutsController.hangouts); // user CORS
I'm implementing a custom app in Google Hangouts, but need to post to my server, and the Hangout is run from a Google server. I put the AJAX call on a loop so that it will keep trying - this post going through is crucial to my app.
Here's the relevant AJAX call in the Hangout app:
var shouldpostHangoutId = true;
/* Post the Hangout ID to server */
var postHangoutId = function(hangoutId) {
var startData = gapi.hangout.getStartData();
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
crossDomain: true,
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
success: function( response ) {
console.log( "postHangoutId -- success" ); // server response
console.log( response ); // server response
shouldpostHangoutId = false;
},
error: function(xhr, textStatus, error){
console.log( "postHangoutId -- error" ); // server response
console.log(xhr.statusText);
console.log(textStatus);
console.log("error = " + error);
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
}
});
};
What's driving me crazy is that sometimes it goes through on the first go, sometimes it takes 5 times. And the whole process is super slow. Here's the log I get when it doesn't come through:
XMLHttpRequest cannot load https://www.foo.bar/hangouts. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'https://ts6d5n5om59gt6cin9c39faccjf890k5-a-hangout-
opensocial.googleusercontent.com' is therefore not allowed access.
I'm using Node + Express ~4 on Heroku.
I think the problem had something to do with pre-flight requests. I changed the AJAX call to the following:
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
error: function( error ){
// Log any error.
console.log( "ERROR:", error );
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
},
complete: function(){
console.log( "postHangoutId -- success" ); // server response
shouldpostHangoutId = false;
}
});
And it goes right through, first time without delay.

406 Error when returning JSON object – Unexpected content

A few colleagues and I have a problem whereby the response from an ajax call returns some unexpected content. Rather than getting a simple JSON object back with various properties, the value of result.responseText is the HTML markup of a generic 406 status error page, saying the MIME type is not accepted by the browser.
The call is made like so:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.promotion_banner .loader').hide();
$('.promotion_banner').html(result);
},
error: function (result) {
var obj = result.responseText;
if (obj.isRedirect) {
document.location = obj.redirectUrl;
}
else {
$('.promotion_banner .loader').hide();
$(".error-wrapper").removeClass("hidden");
var generic_error = document.getElementById('generic_error').value;
$(".error-wrapper p").html(generic_error);
}
},
beforeSend: function() {
$('.promotion_banner .loader').show();
}
});
The controller response to the call is like so:
Response.StatusCode = (int)HttpStatusCode.NotAcceptable; // 406
return Json(new { errorMessage = LocalErrorMessages.Website_Promotions_FreeFiver_General_Problem, isRedirect = false } );
We would expect result.responseText to contain key values for errorMessage and isRedirect, but they’re not there.
It’s worth pointing out that this code is multi-tenanted, shared by the current application and another one, where it works absolutely fine.
We’ve tried:
- Configuring IIS to show detailed error responses rather than a custom page for more detail – gives us nothing extra towards solving the problem.
- Allowing all response content types to the call
- Changing the culture of our site (which is currently es-ES)
- Various web.config tweaks
Has anyone ever had this problem?
Simplify your request. Maybe something like:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: 'GET',
data: {foo:'bar', one:'two'},
dataType: 'json',
success: function (result) {
console.dir(result);
},
error: function (xhr) {
console.dir(xhr)
}
});
And post the response from the server. This kind of error seems a request problem rather than server configuration issue

Resources