How to handle ajax errors on response. - javascript

I have a single page order form. The user fills our the form, javascript validates everything and if it passes an ajax request will hit the server and charge the customer via Stripe when they click submit.
If the charge is successful, json is returned to the ajax request ({success:true}). The user is then redirected to an success page, or an error is displayed if something happened when charging the card.
I'm trying to handle a (rare) issue where the user's request hits the server, the user is successfully charged, but on response the user receives an error (most likely a timeout error on mobile/unstable connection). How can I prevent a user from being double charged? Below is my ajax request, but maybe I need to rethink my entire infrastructure?
$.ajax({ type : 'POST',
url : '/order',
data : $(':input').serialize(),
timeout : 30000,
dataType : 'json',
success : function (data) {
// redirect user to success page
window.location = '/completed';
},
error: function(xhr,status,error) {
// report the error to user.
} });

Try this..
$.ajaxSetup({
type : 'POST',
url : '/order',
data : $(':input').serialize(),
timeout : 30000,
dataType : 'json',
success : function (data) {
// redirect user to success page
window.location = '/completed';
},
error: function(xhr,status,error) {
if (xhr.status == 408) {//For Timeout
alert("Sorry, Request timeout.!");
window.location.href ="//specify a redirect url//";
}
else {
alert("An error occurred: " + status + "nError: " + error);
}
} });

Related

Dynamic / Changing variable in AJAX get Request

I have a page on a project I'm developing that is attempting to make an ajax request with a specific value assigned by the button's (there are multiple) id tag. This works; the value is successfully passed and an ajax call is triggered on every click.
When I try to make the call again to the same page with a different button the variables are reassigned however the GET request that is sent remains unchanged.
How do I pass a NEW variable (in this case id) passed into the GET request?
function someAJAX(target) {
var trigger = [target.attr('id')];
console.log[trigger];
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: target.attr("class"),
tableCall: true,
sort: trigger,
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
$(document).ready(function () {
$(".sort").on( "click", function (e) {
//e.stopPropagation();
//e.preventDefault();
target = $(this);
//console.log(target.attr("class"));
console.log(target.attr("id"));
/* ADD CHILDREN TO ELEMENT*/
if (target.hasClass('asc')) {
target.removeClass('asc')
} else {
target.addClass('asc')
}
/* MANAGE CLASS ADD/REMOVE FOR TARGET AND SIBLINGS */
if (target.hasClass('btn-primary')) {
} else {
target.addClass('btn-primary')
}
someAJAX(target);
target.siblings().removeClass('btn-primary');
})
});
Try to call your ajax like this someAJAX.bind(target)();
Then in function become
function someAJAX() {
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: this.attr("class"),
tableCall: true,
sort: this.attr('id'),
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
trigger doesn't seem to be defined anywhere. That's the only data that would be changing between your requests as the other ones are statically coded.
You just need to make sure trigger is defined and changes between the two requests.
Thanks for the input on this problem. I got down to the bottom of my problem. My requests were being handled correctly but dumping the tables was creating syntax errors preventing the appending of new information to my page.
Thanks for the quick replies!
It wall works now.

Ajax return error to call error ajax error call

I have an ajax function which updates my database.. The function works perfectly well and after updating the the database I call the successAlert() function I have created.. however now I want to call the error function in case of error however on testing purposely to break code I still get the successAlert().
Ajax / Javascript:
var share = "test"
var custid = "test"
$.ajax({
url: "assets/ajax/customer-rec.php",
type: "POST",
data: {UpdateAccount: "yes",custid: custid,share: share},
success: function(result){
successAlert()
},
error: function(result){
errorAlert()
}
});
PHP to update Database
if (isset($_POST['UpdateAccount'])){
$custid = $_POST['custid'];
$share = $_POST['share'];
$query="UPDATE `users` SET `share_ord`='$share' WHERE id= $custid";
$stmt = mysql_query($query);
if($stmt === false){
return false
}
}
return false is not an error. If you want to send the error use headers like
header('X-PHP-Response-Code: 404', true, 404);
you can call the same errorAlert() function in success also so that
$.ajax({
url: "assets/ajax/customer-rec.php",
type: "POST",
data: {UpdateAccount: "yes",custid: custid,share: share},
success: function(result){
if(result === false){
errorAlert()
} else {
successAlert()
}
},
error: function(result){
errorAlert()
}
});
To get error you need to return the status code '404' from the php function which is serving your request.
The error callback is fired when the server returns a HTTP status code that indicates an error, as such you should send one, ex HTTP 500
if($stmt === false){
header('HTTP/1.1 500 Server error');
}
See here a list of HTTP status codes
.ajax() will call on success method because, once your request is processed successfully by the server then it reruns HTTP_OK to the client and if .ajax not received HTTP_OK, then it will call error. According to your code, it will call success, because url is exists and server will send HTTP_OK to the browser.
If you want to generate error: then give wrong url or disconnect internet or simply change
In PHP:
if($stmt === false){
//If you want really generate some http error.
header('X-PHP-Response-Code: 500', true, 500);
exit(0);
//or else continue as per code
// return false;
}
In your JS:
$.ajax({
url: "assets/ajax/customer-rec.php",
type: "POST",
data: {UpdateAccount: "yes",custid: custid,share: share},
success: function(result){
if(!result){
showErrorAlert()
} else {
showSuccessAlert()
}
},
error: function(result){
showErrorAlert()
}
});

Error When Ajax sending two Request to Wicket Server

I am posting data to the wicket server via ajax when user click.to make the state ,retrieve the data when page loading ,via ajax GET, if only one request is sending then its working fine ,but in second request following error has thrown.
org.apache.wicket.core.request.mapper.StalePageException
How can I send the data to the server via ajax and later load the panel
with the submitted data when user load it.
Code :Java Script
Sending data to the server
function submitdata() {
$.ajax({
url : $('#mark').attr('json:callback.url1'),
type : 'post',
cache : false,
data : ko.toJSON(familyModel),
ntentType : 'application/json',
dataType : 'json',
complete : function() {
} ,
error: function(xhr, status, error){
console.log(xhr);
alert(status);
alert(error);
}
});}
}
Page Load
$(document).ready(function() {
$.ajax({
url : $('#mark').attr('json:callback.url'),
type : 'GET',
cache : false,
contentType : 'application/json',
success: function (data) {
console.log(data);
var parsed = JSON.parse(data);
// ko.mapping.fromJS(data, familyModel);
/ ko.applyBindings(familyModel);
// familyModel=new FamilyModel();
ko.applyBindings(familyModel);
},
error: function(xhr, status, error){
console.log(xhr);
alert(status);
alert(error);
}
});
}
public class AbstractJSONBehavior extends AbstractAjaxBehavior {
public void onRequest() {
RequestCycle requestCycle = RequestCycle.get();
readRequestData(requestCycle);
sendResponse(requestCycle);
}
You are using plain jQuery APIs and Wicket believes that the requests are non-Ajax, so it increments the Page#renderCount counter to prevent using page with stale information.
If you use Wicket.Ajax.post({...}) then Wicket will figure this out automatically.
So you can either use Wicket.Ajax.post() or pass either the request parameters or headers from https://github.com/apache/wicket/blob/master/wicket-request/src/main/java/org/apache/wicket/request/http/WebRequest.java#L40-L48 with value true to the jQuery#ajax().

AJAX request not working on remote host

I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:
function send() {
console.log("preparing");
var beacon = {
beaconID: $("#beaconID").val(),
name:$("#beaconName").val(),
campaignID:$("#campaignID").val(),
clientID:$("#clientID").val()
}
console.log("payload:");
console.log(beacon);
$.ajax({
type: 'POST',
url: '../beaconAPI/index.php/createBeacon',
data: JSON.stringify(beacon),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
console.log("done:");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
From the comments you posted
10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "
A status code of zero means one of two things:
You are running off file protocol
The page refreshed as Ajax call is made
Since you said this is on production, sounds like it is a case of #2.
So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.
onclick="send(); return false"
onsubmit="send(); return false"
$("#foo").on("click", function(e) {
send();
e.preventDefault();
});

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.
My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
How do I access the message in my javascript callback? The callback would look like:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
I do not see message i threw in the exception anywhere at all in the data that was returned from the server.
You should use the error callback on the client. The success callback is triggered only when the request succeeds:
$.ajax({
url: '/home/index',
type: 'DELETE',
data: { id: 1 },
success: function (result) {
alert('success'); // result will always be true here
},
error: function (jqXHR, textStatus, errorThrown) {
var statusCode = jqXHR.status; // will equal to 404
alert(statusCode);
}
});
Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.
I just answered this in my question What is the point of HttpException in ASP.NET MVC, but you can actually get that string if you use the HttpStatusCodeResult like this:
In your controller:
return new HttpStatusCodeResult(500,"Something bad happened")
And you can access "Something bad happened" using, say, jQuery $.ajax() like this:
$.ajax: {
url: "#Url.Action("RequestsAdminAjax", "Admin")",
type: "POST",
data: function(data) { return JSON.stringify(data); },
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus,errorThrown) {
debugger;
toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
}
},
and errorThrown will contain "Something bad happened".
HTH.

Categories

Resources