Javascript: How to stop multiple jQuery ajax error handlers? - javascript

A team member put this into our project
$(function() {
$("body").bind("ajaxError", function(event, XMLHttpRequest, ajaxOptions, thrownError){
alert(thrownError);
});
}
However I want to supress one of my errors (as it would be noise and verification isn't needed)
function blah() {
...
errFunc = function(event, xhr, opts, errThrown) {
//what could I do here?
//event.stopImmediatePropagation()?
}
$.ajax({
url : '/unimportant_background_refresh',
type : 'GET',
data : { },
dataType : 'json',
success : updateBackgroundStuff,
error : errFunc, // Suppresses error message.
});
}
How can I stop the catch all error from happenning please? Can I just do something in the error function such as { event.StopPropogation(); } or must I work out some mechanism for having the catch all selectively ignore things please?

Global events can be disabled, for a particular Ajax request, by passing in the global option, like so:
$.ajax({
url: "test.html",
global: false,
// ...
});
Taken from: http://docs.jquery.com/Ajax_Events

I would just throw a boolean into your code that's defaulted to false. Set it to true the first time the error is thrown and make sure to check for true at the start of the error function.
Something like:
function blah() {
var errorHappened = false;
...
errFunc = function(event, xhr, opts, errThrown) {
if (errorHappened)
return;
errorHappened = true;
// handle the errror.
}
// the rest of your code
}

Related

Sending an error in grails and reading it in Javascript

Hi my question is how i would send an error from the grails side after a check, for example in a grails controller being called if i had (don't know if its correct):
if(something){ return error #}
else if(something){ return error #}
else{ return error#}
And then what i would need to do in a js function so that it can receive said errors and then act upon it. ie. Error 200 continues as normal, error 400 renders a new page etc, just need to get to the part of reading this error.
Simple stuff:
def delPhoto() {
Photos ph = Photos.get(params.id as Long)
if (ph) {
doSomething()
// return status 200
render status:response.SC_OK
return
}
//OtherWise return 404
render status:response.SC_NOT_FOUND
}
Now in your gsp java script
$.ajax({timeout:1000,cache:true,type: 'GET',url: "${g.createLink(controller: 'photos', action: 'delPhoto')}",
success: function(data) {
$("#uploads").html(data);
},
statusCode: {
417: function() {
$('#field').css({'color':'white'});
$('#field').html("${g.message(code:'default.false.error')}")
}
},
statusCode: {
404: function() {
$('#field').css({'color':'white'});
$('#field').html("${g.message(code:'default.false.error')}")
}
},
error: function (e) {
}
});
});
So your ajax call then defines for each error message or success what things to update on the page
instead of returning status you can directly set your response status in you controller action like this
response.status = 401
and render anything you want.
And access your response status in your ajax success handler like below
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
}
});

Impossible to create a new account on prestashop

I am currently developping a new website
When I am trying to create an account, I get an error like this :
Uncaught TypeError: Cannot read property 'hasError' of null.
And this is the code
function submitFunction()
{
$('#create_account_error').html('').hide();
//send the ajax request to the server
$.ajax({
type: 'POST',
url: baseUri,
async: true,
cache: false,
dataType : "json",
data: {
controller: 'authentication',
SubmitCreate: 1,
ajax: true,
email_create: $('#email_create').val(),
back: $('input[name=back]').val(),
token: token
},
success: function(jsonData)
{
if (jsonData.hasError())
{
var errors = '';
for(error in jsonData.errors)
//IE6 bug fix
if(error != 'indexOf')
errors += '<li>'+jsonData.errors[error]+'</li>';
$('#create_account_error').html('<ol>'+errors+'</ol>').show();
}
else
{
// adding a div to display a transition
$('#center_column').html('<div id="noSlide">'+$('#center_column').html()+'</div>');
$('#noSlide').fadeOut('slow', function(){
$('#noSlide').html(jsonData.page);
// update the state (when this file is called from AJAX you still need to update the state)
bindStateInputAndUpdate();
$(this).fadeIn('slow', function(){
document.location = '#account-creation';
});
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
It seems to be the jsonData, on the function, which is not working as well. Any idea or suggestions?
The success handler will be passed the data returned from the ajax request.
It will not have a function called hasError() because it is just a json object it will not have any functions.
The error handler should be fired if there is an http error i.e. if the ajax call returns an http 500.
I'm not familiar with prestashop, but looking over the prestashop documentation hasError is returned as a bool (not a function), so instead try (without the parenthesis).
if (jsonData.hasError)
You may also want to check if any data is returned first.
if (jsonData)

How to handle response of a POST request in jQuery

I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.

add global callback to $.ajaxSetup

I am use $.ajaxSetup to use a global authorization method, and global error handling in my site. I would like to pass a callback function into the global error method so I can call the function whenever I need to in the global error handler. Here is my $.ajaxSetup:
$.ajaxSetup({
global: false,
// type: "POST",
beforeSend: function (xhr) {
//The string needs to be turned into 'this.pasToken'
//if not us, don't include
if(app.cookieAuth)
xhr.setRequestHeader("Authorization", _this.pasToken);
},
statusCode: {
401: function(){
//Redirect to the login window if the user is unauthorized
window.location.href = app.loginUrl;
},
//This is where I need help
403: function(error, callback){
//Show an error message if permission isn't granted
callback(error);
alert(JSON.parse(error.responseText)['Message']);
}
}
});
Note the 403: status code. I am trying to pass in a callback function, but I don't know how to do it from the individual ajax calls. Anyone have an idea?
The easiest solution; define your own property for ajax options.
$.ajaxSetup({
statusCode: {
403: function(error, callback){
this.callback403(error);
}
}
});
$.ajax({
callback403: function () {}
});
Note, if you change the context option of the ajax request, this may not work.
I am not sure if this is what you are looking for:
$.ajax({
statusCode: {
404: function() {
alert("page not found");
}
}
});

Ember js: TypeError this.init is undefined

This is related to my previous question. The answer there seemed to solve the problem.
But I am literally doing the exact same thing from another route, and now I get an error. The application passes over the ajax function twice. The first time, I get a TypeError. If I reload the page, then the function executes correctly.
I know in the docs, it mentions having to create and object that is defined. Could somebody point me to an example of how extended controller needs to be created in order to execute a function when it is called.
I get an error: TypeError: this.init is undefined
Here is my route:
App.RegisterPickRoute = Em.Route.extend({
redirect: function() {
var registerTestController=this.controllerFor('registerTest')
var isRegistered=registerTestController.registerContacts();
if(!isRegistered)
this.transitionTo('registerTest');
else
alert('holla')
}
});
Here is my function in my controller:
registerContacts: function(){
var isRegistered=false;
var self=this
self.contactsToAdd=self.get('contactList').filterProperty('isSelected', true);
$.ajax({
type: 'POST',
cache: false,
url: contextPath + 'user/regTest',
data:{contactList:self.contactsToAdd},
success: function(data) {
isRegistered=true;
},
error: function(jqXHR, textStatus, errorThrown) {
isRegistered=false;
},
async: false
});
return isRegistered
}
I have a syntax error. The value passed to the data attribute of the ajax call needs to be self.contactsToAdd.toArray()

Categories