Jquery post occasionally not calling success or error function - javascript

My host is currently having server issues, making today the perfect day to test what happens when my ajax calls fail.
So I'm finding that when something does go wrong, neither my success or fail function in the following are being called: ( simplified for simplicity's sake ). Currently this will fail completely about one in every 10 times.
I'd like to know how to make sure I can catch all errors in ajax, for example when the server simply doesn't respond, as would be the case today.
myvar = jQuery.post(ajax_object.ajax_url, data, function( response ) {
console.log( 'success!' );
})
.fail(function() {
console.log( 'sad trombone' );
});

You can try these two ways.
$.ajax({
url: ajax_object.ajax_url,
type: 'POST',
async: false,
cache: false,
timeout: 30000,
data : data,
dataType: 'json', // use this if you want json response
error: function() {
return true;
},
success: function(data) {
console.log(data);
}
});
OR $.post(ajax_object.ajax_url, { data:data }, function(response){
console.log(response);
});
first you simply give an echo "hii"; exit; in the page ajax_object.ajax_url so you can test whether it is properly redirect to that page..

Related

Solution to fix ajax returning both success and error when it executes php corectly

I've got the below ajax code and it works fine. If I send a request the first time, it works fine. If I send the second time, It returns success and error (1 each).
$('#eproductForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: $('#eproductForm').attr('action'),
data: $('#eproductForm').serialize(),
cache: false,
async: false,
dataType: 'json',
success: function (response) {
$('#eproductModal').modal('hide');
$('#eproductForm')[0].reset();
save_success();
stockList();
},
error: function(response){
something_wrong();
}
});
return false;
});
Do you have a solution please? share. Thanks
Why are you returning false at the end!? I'm hoping
save_success();
stockList();
this two functions will take you to another place, the thing is when you are returning false maybe the submit aint working correctly so it falls down to the error. Try returning true in success/ false in error, maybe this will fix it. If this doesn't work, try making the Ajax request a promise as in
return new Promise ((resolve, reject) => {
$.ajax({
type: 'post',
url: $('#eproductForm').attr('action'),
data: $('#eproductForm').serialize(),
cache: false,
async: false,
dataType: 'json',
success: function (response) {
resolve(response)
},
error: function(response){
reject(err)
}
});
}).then((response) => {
$('#eproductModal').modal('hide');
$('#eproductForm')[0].reset();
save_success();
stockList();}).catch((err) => {something_wrong();})
this will help you understand how the request is passing through your function. Also, it helps to check your rquest in the chrome developer tools and see what status is returning, so you can deduce at what point is breaking

Calling function inside jQuery ajax success response works once but not twice

I have a page where I enter the names of cards and the card's details are presented via AJAX. I've removed a lot of code in this example that isn't relevant to the issue and I've tested this simplified code and it reproduces the same error.
The mysterious thing is that it works fine the first run through the testSelectedCardDetails function. It calls setNameCardIsFromField fine and does what it is meant to do. The second time through it dies with the console showing:
Uncaught TypeError: setNameCardIsFromField is not a function
What's up with that? I honestly don't know enough about how jQuery works to be able to nail the problem so I turn to the stackoverflow world begging for salvation from this madness. ;)
function testSelectedCardDetails(cardName) {
var cardTestInfoArray = [];
$.ajax({
url: 'includes/getCardAndSetDataViaAJAX.php',
type: 'POST',
cache: false,
async: false, // if set to true then the data doesn't get here fast enough to run commands in 'success'
dataType: 'json',
data: { callThis: "testSelectedCardDetails", thisCardName: cardName},
error: function(data){
console.log("AJAX failed to get card info.");
},
success: function(data) {
$.map(data, function (value) { cardTestInfoArray = value; });
cardPresentInfo['printings'] = cardTestInfoArray['printings'];
//automatically set setNameCardIsFrom field
setNameCardIsFromField(cardPresentInfo['printings']);
}
});
}
Here's the function being called:
function setNameCardIsFromField(setCode) {
$.ajax({
url: 'includes/getCardAndSetDataViaAJAX.php',
type: 'POST',
cache: false,
async: false, // if set to true then the data doesn't get here fast enough to run commands in 'success'
dataType: 'text',
data: { callThis: "setNameCardIsFromField", thisSetCode: setCode},
error: function(data){
console.log("AJAX failed to get card info.");
},
success: function(setName) {
//console.log(setName);
setNameCardIsFromField = document.querySelector('#setNameCardIsFrom');
setNameCardIsFromField.value = setName;
}
});
}
You overwrite the function:
setNameCardIsFromField = document.querySelector('#setNameCardIsFrom');
Assuming it's global (which is generally bad).
Unrelated, but meh on using async: false, better to do it right than to hack around it, e.g., callback, promise, whatever.

Ajax - All request are Done/Completed

I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.

How to pass parameters in GET requests with jQuery

How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];

Pass JavaScript function in ajax response

I'm trying to return a callback from an AJAX submitted form. The user submits a form, the server processes and returns the valid response, i.e. an error message and also a JavaScript function that could perform an action. I'm using Zepto.js faling back to jQuery depending on browser.
My ajax request is:
$.ajax({
success: function(data, status, xhr) {
data.callback();
},
url: form.attr('action'),
data: form.serialize(),
dataType: 'json'
});
On the server I want to return something like:
// PHP code
?>
{
return: false,
error: 'Sorry, we couldn’t find an account with that username or password.',
callback: function() {
console.log('this is the callback');
}
}
<?php
// more PHP code
When returned to the browser callback function should fire. I want the server to return the callback so I can use the same JavaScript code and have it respond accordingly to the server response.
Would I need to change the dataType to script? However I thought this was just for loading .js files, not blocks of code.
Any help appreciated.
The general feeling here is I am approaching this in the wrong way. So revised code:
$.ajax({
success: function(data, status, xhr) {
var callback = data['callback'];
callback();
},
url: form.attr('action'), // in this example it's badLogin
data: form.serialize(),
dataType: 'json'
});
// callback specified in PHP
badLogin: function() {
console.log('bad login');
}
And my PHP
if (!$valid) {
?>
{
"return": false,
"error": "Sorry, we couldn’t find an account with that username or password.",
"callback": "badLogin"
}
<?php
}
Thanks for pointing me in the right direction.
You can always return the code as a string and use eval() if you are absolutely sure that the string will always be correct and no code can be injected.

Categories

Resources