Cant access variable inside jQuery $.post [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I went through many posts about this, but didnt find any solution working for me - cleaned up code:
$('#form-new').submit(function(e){
e.preventDefault();
$curForm = $(this);
$textbox = $( '.new-box' ,this);
window.tmp_input_ok = false;
var wasError = false;
if( $.trim($textbox.val()) == "" ){
wasError = true;
}
if( wasError ){
//possible message
} else{
var jqxhr = $.post(
$(this).attr('action'),
$(this).serialize(),
function(data, textStatus, jqXHR){
if( data=="200" ){
console.log('post OK'); //this shows in console!
window.tmp_input_ok = true;
} else{
console.log('not OK');
}
}
).fail(function() {
console.log('POST fail)');
});
}
//however, window.tmp_input_ok is false here so the textbox does not empty:
if(window.tmp_input_ok == true) $textbox.val('');
else console.log('input not ok :('); //and this is outputted to console
});
Originaly, there was just a var tmp_input_ok = false initialization and then working with the tmp_input_ok variable, but it wasnt working so I tried global window... does not work either... I am starting to be desperate.

Your if statement is executed before the call is finished.
$.post is an async call and the rest of the code continues while the post is processing
You are already using .fail(), you can add .always() if you want to execute your if statement always on completion or add it to your .success() if you only want to check it when the call succeeds, similar to this:
if (wasError) {
//possible message
} else {
var jqxhr = $.post($(this).attr('action'), $(this).serialize(), function (data, textStatus, jqXHR) {
if (data == "200") {
console.log('post OK'); //this shows in console!
window.tmp_input_ok = true;
} else {
console.log('not OK');
}
// either add it here if you only want to process it on success
if (window.tmp_input_ok == true) $textbox.val('');
else console.log('input not ok :(');
}).fail(function () {
console.log('POST fail)');
}).always(function(){ // or add it here if you always wan to execute on completion regardless of fail or success
if (window.tmp_input_ok == true) $textbox.val('');
else console.log('input not ok :(');
});
}

The reason your XHR request has an onSuccess callback is because the call is asynchronous.
Take for instance this simple bit of code:
$.get(
'/foo',
function(){
alert("data received");
}
)
alert ("End of script reached");
The success callback is set up to something that will be called when the request is successfully received, rather than when that line of code is read by the browser.
Often you'll see the "End of script reached" alert before the "data received" alert simply because a full XHR request will take over 100 milliseconds, while reading those few lines will take a fraction of that.
Code that depends on having a response for a state must be called by the callback. There's far too many ways to do this for me to go into detail.

Related

Let code wait untill AJAX request is done

I have the following code to check if a username already exists. It uses an AJAX-request to another page, this page returns either 1 (username exists) or 0 (username doesn't exist).
function checkUsername(username,callback){
$.ajax({
url: '/check_username.php',
type: 'post',
data: {username: username},
dataType: 'json',
success : function(data){
switch(data.response){
case 0:
callback(true);
break;
case 1:
callback(false);
break;
}
}
});
};
var error; // 'undefined' for now
checkUsername('abc',function(data){
if(data == false){
// username exists
error = true;
}else{
// username does not exist
error = false;
};
});
if(error == false){
alert('username does not exist');
}else{
alert('username exists');
};
Problem
The code checks if error = true (there is an error, ie. the username exists) or error = false, but the code keeps on running. It doesn't wait until the AJAX-request in checkUsername is done. So it's always "username exists" (because error = undefined, and if-else then goes to the else-statement).
Question
How can I make sure that the code waits until the AJAX-request (the checkUsername function) is completely done before going any further.
I have a "partial" solution: When I wrap the if-else-statement that checks error = true/false in a setTimeout, it works. The problem is: How many miliseconds? I want to have it as fast as possible. 500ms? What if the AJAX-response is not done then? 1000ms? Isn't that too long?
I think there is a better solution than doing this with a setTimeout. Anyone have an idea?
if(error == false){
alert('username does not exist');
}else{
alert('username exists');
};
Currently your above code
is on top of javascript, it is always being executed whether you call your ajax or not.so put it into other function and call it after calling checkUsername().
function checkUsername(username,callback){
$.ajax({
url: '/check_username.php',
type: 'post',
data: {username: username},
dataType: 'json',
success : function(data){
switch(data.response){
case 0:
callback(true);
break;
case 1:
callback(false);
break;
}
}
});
};
var error; // 'undefined' for now
checkUsername('abc',function(data){
if(data == false){
// username exists
error = true;
}else{
// username does not exist
error = false;
};
alertMsg();
});
function alertMsg(){
if(error == false){
alert('username does not exist');
}else{
alert('username exists');
}
}
try with async: false on ajax function
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
Set async to FALSE and it will not move until ajax request is completed.
function checkUsername(username,callback){
$.ajax({
url: '/check_username.php',
type: 'post',
data: {username: username},
dataType: 'json',
async : false,
success : function(data){
switch(data.response){
case 0:
callback(true);
break;
case 1:
callback(false);
break;
}
}
});
};
var error; // 'undefined' for now
checkUsername('abc',function(data){
if(data == false){
// username exists
error = true;
}else{
// username does not exist
error = false;
};
});
if(error == false){
alert('username does not exist');
}else{
alert('username exists');
};
I had the same problem couldn't find any way but this worked for me.
function sendAjax(){
var defObj = $.Deferred();
//my ajax code here
defObj.resolve(ajaxResponse);
return defObj.promise();
}
AJAX (and a lot of other functionality of JavaScript) works asynchonous, this means you do not wait for something to happen but rater tell JavaScript what to do when something happens. In your example you're trying to wait 'till the AJAX-Request finished but what you should do is tell JavaScript to execute your code when the request finished, this means, put the code in the callback.
Even though you have used callbacks for AJAX, the way you are checking
conditions is still asynchronous..
checkUsername('abc',function(data){
alermsg(data);
});
function alertmsg(data){
!data?alert('username does not exist'):alert('username exists');
}

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);
};
});

Prototype validation not working correctly

I use Prototype.js to validate a form. For one of the fields, I have the prototype script ajax a request to a file. The file is a simple PHP file and will return '1' if the value is OK and '0' if the value is not OK. I have the script as below, which should work perfectly. The prototype validation is supposed to show a validation error message when a field does not pass validation, and not display / remove the message once the field passes validation. But in this case, even when the ajax file returns '1', the validation will display the error message anyway. Anyone able to help would be greatly appreciated!
['validate-number3', numessage3, function(v) {
new Ajax.Request('test.php?nr='+v, {
method:'get',
onSuccess: function(transport) {
var response = transport.responseText;
if(response == '1'){return true;}else{return false};
}
});
}],
the return value from Ajax.Request is the Ajax.Request object and returns as soon as the request is setup - the onsuccess callback is called after the request has been completed - so checking the results of Ajax.Request is not useful for what you want to accomplish.
The reason that this doesn't work as you expect, this is an asynchronous call which means it will start the call and then return control to the script while it is processing and then run the callbacks when it is completed.
Try it this way
new Ajax.Request('test.php?nr='+v, {
method:'get',
onSuccess: handleResponse
});
function handleResponse( transport ){
var response = transport.responseText;
if(response == '1'){
//everything is OK
}else{
//value is not OK
};
}
I was able to solve my question!
Thanks to this teriffic page: http://inchoo.net/ecommerce/magento/magento-frontend/magento-form-field-ajax-validation/ it was no problem. This is what I ended up with:
var ok = false;
new Ajax.Request('test.php?nr='+v, {
method:'get',
asynchronous: false,
onSuccess: function(transport) {
var response = transport.responseText;
if(response == '1'){ok = true;}else{ok = false;};
},
onComplete: function() {
if ($('advice-validate-number-pay_bank_no')) {
$('advice-validate-number-pay_bank_no').remove();
}
}
});
return ok;

Issues with handling http errors with jQuery AJAX webservice calls

I'm developing an jQuery application in where I've a requirement to capture HTTP errors as and when it occurs. Below is my snippet.
// Function to validate URL
function validateURL(url)
{
var pattern = new RegExp();
pattern.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
if (!pattern.test(url))
{
return false;
}
return true;
}
// Generic error handler for handling the webservice requests.
function initWebService(wstype, wsurl,jsonData)
{
// If the method parameter is not either "GET" or "POST" display an error message to the developer.
var msgValidateArgument;
var wsCallStatus;
var callbackData;
if ((arguments[0] != 'GET') && (arguments[0] != 'POST'))
{
//alert("Invalid");
//alert("You must provide a valid http method in your webservice call.");
msgValidateArgument = "You must provide a valid http method in your webservice call.";
return msgValidateArgument;
}
// Making sure whether the developer is passing the required number of parameters.
if(arguments.length < 3)
{
//alert("Some required arguments seems to be missing. Please check your webservice invocation.");
msgValidateArgument = "Some required arguments seems to be missing. Please check your webservice invocation.";
return msgValidateArgument;
}
if (!validateURL(arguments[1]))
{
msgValidateArgument = "You must provide a valid URL in your webservice call.";
return msgValidateArgument;
}
if(arguments[2] != ''){
var response=jQuery.parseJSON(arguments[2]);
if(typeof response =='object'){
//It is JSON
alert(response.toSource());
}
else{
msgValidateArgument = "The JSON data being passed is not in valid JSON format.";
return msgValidateArgument;
}
}
// Making the AJAX call with the parameters being passed. The error handler handles some of the possble http error codes as of now.
$.ajax({
type: arguments[0],
url: arguments[1],
data: arguments[2],
dataType: 'json',
async:false,
statusCode:{
404: function(){
alert('Page not found');
},
500: function(){
alert('Page not found');
},
504: function(){
alert('Unknown host');
}
},
success: function(data){
//alert('Data being returned from server: ' +data.toSource());
//alert('Data being returned from server: ' +data.toSource());
//alert(data);
callbackData = data;
}
});
return callbackData;
}
But, when I programatically change the webservice url to hold a wrong value, and upon calling the html page, I'm able to see an error message in the firebug console, but my snippet doesn't seem to be catching the error at all.
For e.g, While calling the GEONames API, I'm encountering an stating "407 Authorization required" in firebug's console.but even if I handle that status code in my error block, it is not firing.. What could be the reason?.
Don't we have any comprehensive solution for handling these HTTP errors effectively?.
I think there are a few problems with your code ... firstly how is handleError called ? because you call a method called handleError but pass nothing ... im assuming your using .ajax()
You should do it like this :
$.ajax({
statusCode: {
404: function() {
alert('page not found');
},
500: function() {
alert('server error');
}
},
success : {
alert('it working');
},
complete : {
alert('im complete');
});

cant access var outside jquery

var = msg
$.get('json-signup-erros.php',{},function(data){msg=data},'json');
function focushint()
{
alert (msg) // this works
}
$("input").focus(focus);
alert(msg) //this doesnot work
can anyone tall me way??
You are making an AJAX request which is asynchronous.
msg will contain the value only after the request has been made.
You should put the code that uses msg into the Ajax request's success callback (the function(data)).
(There is the theoretical possibility to make the request synchronous using async: false but that is not good practice and should be used only if it's unavoidable.)
I agree with Pekka - you need to consider something like this:
var = msg;
$.get('json-signup-erros.php',{}, function(data, response)
{
if(response == "success")
{
msg = data;
alert(msg);
}
else
{
alert("Whoops something went wrong, please try again.");
}
},'json');
function focushint()
{
alert (msg); // this works
}
$("input").focus(focushint);
NB. I put a "success" check in the $.get... I see this all the time - you should not assume that your Ajax Http Request is going to return a 200 response! i.e. if no data get's returned due to an error (404, 500, 401) you can't alert it and you may want to warn the user that something went wrong by adding an else clause.
var = msg;
$.get('json-signup-erros.php',{}, function(data, response)
{
if(response == "success")
{
msg = data;
alert(msg);
}
else
{
alert("Whoops something went wrong, please try again.");
}
},'json');
function focushint()
{
alert (msg); // this works
}
$("input").focus(focushint);
alert(msg); // this is still does not work
If you want to access the msg outside a jQuery function like focushin that will be in the same scope

Categories