refrer function name in ajax, reverse callback on fail - javascript

I have no idea how I can achieve this.
I am using jQuery 1.9 for ajax call back.
I have a function, let's say:
function a (param){
//calling a function this will perform ajax
data = performAjax(param, url, etc);
// render response
renderResponse(data);
}
We are executing our ajax in perform ajax function.
Issue is when ajax fails then it perform ajaxError function.
I put a message in div that please refresh this again.
But how can I get function a and all the parameter of that in ajaxError function? So that I can put a link to refresh again.

Not sure if I understand correctly, but here it goes:
function performAjax() {
return $.ajax({
....
});
}
var lastFailedFunction;
function a (param){
var args = arguments;
//calling a function this will perform ajax
performAjax().then(function(data) { // on success
// render reponse
renderResponse(data);
}, function() { // on failure
lastFailedFunction = function() {
a.apply(a, args);
};
// now you can call lastFailedFunction() to try again
});
}
When the ajax-call fails, it will store the failed function call to lastFailedFunction. So somewhere else you might show this message:
<div>Function A failed, click here to try again</div>

Using error callback of ajax, you can get the error message
function a(param) {
var performAjax = $.ajax({
type: "",
url: "",
data: "",
success: function(msg){
//success msg
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//can access param of fun a and the error message
//append it to the body
$('body').append('<div>'+param+' error: '+errorThrown+'</div>');
}
});
}

Related

Return data from function to ajax javascript

I wanted to make a button when I clicked it called that ajax function to send data to a function then the function returns the data back to the ajax so that it can execute the success call which makes the button become disabled.
Here's the function notify()
public function notify()
{
$id = $this->user['id'];
$agent = AffiliateAgents::get($id);
if (empty($agent)) redirect('affiliate/sales/browse');
$_POST = array_map('trim', $_POST);
$agent = [
'commission_claim' => 1
];
AffiliateAgents::update($id, $agent);
$status = AffiliateAgents::get($id ,'commission_claim');
return $status;
}
Here's the ajax
$("#notify").click(function() {
$.ajax({
url: 'affiliate/sales/notify',
success: function() {
showNotification("success", "Berjaya!", "Anda berjaya membuat tuntutan komisyen");
}
});
})
just pass parameter into success function in this line:
...
success: function(yourData) {
...
As you wanted to disable the buttons after the success of Ajax.
You have to write the following code
in ajax part
success : function(data){
// disable button
if(data="success"){
$("#buttonId").attr("disabled","disabled");
} else{
alert("Status not success");
}
}
You can get the returned data (from PHP) like this:
//In the ajax...
success: function(data) {
console.log(data)
}
success Type: Function( Anything data, String textStatus, jqXHR jqXHR
) A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
http://api.jquery.com/jquery.ajax/

How do get data of ajax call beforeSend in same ajax Call?

is there way to get data prepared in ajax call before call to made.
var prevData = [];
$.ajax({
type : "GET",
data :{"dataId":dataId, "sortedOrder":Order},
url : "main-section/getData",
beforeSend: function( event, xhr, settings ) {
// Have to check data here.
if (xhr.data==prevData ){
prevData =xhr.data;
event.abort();
}
},
success : function(response) {
// some code.
},
error : function(xhr,ajaxOptions,thrownError) {
console.log("error occured : "+ thrownError)
}
});
i want to comapare data in beforesendmethod of ajax.In such a way that if there is multiple calls then abort calls in waiting.
I'm guessing it's a problem in the javascript event loop?
I would suggest refactoring your code to check the data and only send the ajax request if success occurs, outside of the ajax itself. Here is the sample pseudo-code
example = function(prevData, ajaxCall){
//check prevData here
if (success) {
ajaxCall();
}
}

Javascript redirect on Ajax success

I have a quiz type application. Each question has two answers with a value of 1 or 2. When the quiz is complete, if they have a score lower than 10, they get redirected to a page.
This is my code for this part.
while (n < numResults) {
increment = minScore + (interval * n);
if (totalScore <= increment) {
if(totalScore <= 10) {
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
})
.done(function( msg ) {
window.location.href("www.page2.html");
});
}
return;
} else {
n++;
}
}
I have a few things I am trying to solve. Firstly, before the redirect, some data (answers and url) is posted to PHP so I can process it. One thing I pass is the current window url. The reason I do this is because the
url has a format like
www.page1.com?a=1&b=2&c=3
In PHP, I parse this url and grab the values.
My first problem is that although the data is successfuly sent to PHP and handled, and returns a response of Success, the done function never seems to fire, therefore no redirect occurs (I put an alert in this function
to ensure it is not firing). In PHP, after I process the data, I do this
var_dump($response); //Outputs Success
return json_encode($response);
The second thing I am trying to work out is the redirect url (page2.html). Within this page, I have a button. This button has a standard link, and then I need to give it some params from the initial url.
So this pages button might be something like
www.externallink.com?a=1&c=2
How can I get the original URLs params into a button on the redirected url?
Thanks
USE below function insted of done:
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
success:function(data){
window.location.href("www.page2.html");
});
})
For your 1st part:
Try putting the error function of jQuery ajax call. Sometimes when the return type of result does not match with the expected datatype of ajax call, then result comes in the response of error.
error: function (data, status, e) {
}
For your 2nd part:
Attach click event for the button in the handler and read the current URL query string using window.location.search and then redirect using
window.location = newURL + "extra query params";
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function(data, textStatus, jqXHR) {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) {
alert( "complete" );
});
If you .done() callback never invoked, try to set debuggers or alerts inside .fail() or .complete() callback functions. Check if you have an error during ajax call and at all if the call has complete statement.
Here more information: http://api.jquery.com/jquery.ajax/

how to find which method is causing the error during parallel ajax call

I am using $.when to make parallel ajax call to webapi controller and it works perfectly fine. The structure is given below,
$.when(GetDataFromMethodA(),GetDataFromMethodB(),GetDataFromMethodC())
.done(function (responseFromMethodA,responseFromMethodB, responseFromMethodC) {
if (responseFromMethodA != null) {
//do some action
}
if (responseFromMethodB != null) {
//do some action
}
if (responseFromMethodC != null) {
//do some action
}
}).fail(function (xhr, textStatus, errorThrown) {
//which method raised the exception?
});
Methods:
function GetDataFromMethodA() {
var Request = {};
Request.Code = name.find(':selected').val();
return $.ajax({
url: 'api/Data/GetCurrentView',
type: 'POST',
dataType: 'json',
data: Request
});
}
similarly, I have method B and C.
QUESTION:
There are situations where any one of the method fails and based on the failing method, I need to display appropriate message to the user. When anyone of the method fails, the exception is caught in the 'fail' section. But, how to find which method raised the exception?
If you use always instead of done, you can inspect whether the request succeeded with isResolved() or isRejected(), for instance:
$.when(GetDataFromMethodA(),GetDataFromMethodB(),GetDataFromMethodC())
.always(function (responseFromMethodA,responseFromMethodB, responseFromMethodC) {
if(responseFromMethodA.isRejected()) {
console.log('A did not work!');
}
if(responseFromMethodB.isRejected()) {
console.log('B did not work!');
}
// ...etc.
});

How to get default error of ajax call

Ok, what I am trying to do is alerting ajax errors according to its error codes and I have lots of ajax calls on website so I am using global ajax error handler function.
But what I want is if some ajax call already have default errors then show there not global.
$(document).ready(function(){
$(document).ajaxError(e,xhr,opt){
if(xhr.error){
//Don't do anything
} else {
alert('You have an error');
}
}
}
First Function :
$.ajax({
type:"post",
url:"page.php",
data:"name=mohit&lastname=bumb",
error:function(){
alert('error');
}
});
Second Function :
$.ajax({
type:"post",
url:"page.php",
data:"name=mohit&lastname=bumb",
});
So in 2nd case it should show You have an error and in first case just error
Yes you can, but you have to override jQuery default $.ajax methods. Check the following code that I used in one of my projects. Make sure you load the script just after jQuery.
My scenario was -
The web site had a lot of ajax partial views which had to check whether user is logged in or not. So I had to override jquery calls to check for it.
I also had to show a loader when any ajax call was made.
One more thing, some js are loaded by ajax, so I added a check whether the url is a .js file or normal url.
I have taken out the sensitive codes that were confidential for my project. The rest is here. This might help you.
$(document).ready(function () {
var oldjQuery = [];
oldjQuery["ajax"] = $.ajax;
oldjQuery["load"] = $.load;
var newOptions = [];
//override ajax
jQuery.ajax = function (options) {
newOptions["ajax"] = $.extend({}, options);
//override the success callback
newOptions["ajax"].success = function (data, textStatus, jqXhr) {
try {
if (options.url.indexOf('.js') <= -1) {
//this is a normal success call, do nothing
}
}
catch (err) {
//... my other codes, incase any error occurred
}
if (typeof options.success != 'undefined') {
//the ajax call has a success method specified, so call it
options.success(data, textStatus, jqXhr);
}
};
//override the error callback
newOptions["ajax"].error = function (jqXhr, textStatus, errorThrown) {
try {
if (options.url.indexOf('.js') <= -1) {
//this is a normal success call, do nothing
}
}catch (y) {
//... my other codes, incase any error occurred
}
//the ajax call has an error method specified, so call it
if (typeof options.error != 'undefined') {
options.error(jqXhr, textStatus, errorThrown);
}
};
return oldjQuery["ajax"](newOptions["ajax"]);
};
//override load function
jQuery.load = function (url, data, completeCallback, ignore) {
newOptions["load"].completeCallback = function (d, textStatus, jqXhr) {
try {
if (url.indexOf('.js') <= -1) {
//codes
}
} catch (err) {
try {
//codes
}catch (err2) {
}
}
if (typeof completeCallback != 'undefined') {
//call the default completed callback
completeCallback(d, textStatus, jqXhr);
}
};
return oldjQuery["load"](url, data, newOptions["load"].completeCallback);
};
});

Categories