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
Related
I'm hoping this is just a simple fix due to me being a little dumb somewhere along the line. I'm executing my ASP.NET MVC login using AJAX. There is a "success" handler which returns a "true" value to the calling function which, in turn, load the home page.
The issue is that the "success" handler is executing BEFORE any value is returned - which means that nothing happens because the value is not "SUCCESS". I can confirm this by looking at the request in Firebug, the value returned is SUCCESS but nothing happens. If I apply a breakpoint to the end of the function and then continue execution it works just fine.
I have no idea what the issue is, I'd be very grateful for help or an explanation to what I'm doing wrong.
Thanks!
My JS Function:
function LogIn(UserName, Password) {
var Cont = true;
var ErrorString = "";
if (UserName == null || UserName == "") {
Cont = false;
ErrorString += "Username is Required.";
}
if (Password == null || Password == "") {
Cont = false;
ErrorString += "Password is Required.";
}
var result = false;
if (Cont) {
var LogInUrl = "/AJAX/LogIn?UserName=" + UserName + "&Password=" + Password;
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
result = true;
}
}
})
}
return result;
}
UPDATE: The function that calls the LogIn function:
$('#FormLogin').submit(function (e) {
e.preventDefault();
var UserName = $("#TxtLoginUsername").val();
var Password = $("#TxtLoginPassword").val();
var IsLoggedIn = LogIn(UserName, Password);
if (IsLoggedIn) {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
})
As I said, the function does it's job and logs me in, but the "success" handler seems to execute before the value is returned.
Change your ajax call to something like this:
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
}
});
There is no point in returning result from LogIn, it'll always be false. You need to put the code handling the returned value in the callback.
Another alternative, if you don't like the idea of your LogIn function being so closely coupled to DOM manipulation is to return the promise from your ajax call. So at the end of LogIn, you'd do something like this:
return $.ajax({
url: LogInUrl,
type:"GET"
}
});
And then when you call it, you'd do something like this:
LogIn(UserName, Password).then(function(data) {
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
});
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.
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;
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');
});
I learn jQuery and don't understand this situation:
When running this code in debug mode all work well. But when running this code normal, calback function don't starts. Why?
In non debug mode I have -> "Start" -> "End 10"
Browser: Google Chrome.
var nrPost = 10;
$("#buttnX").click(function() {
alert("Start");
GoPosts();
End();
});
function End() {
alert('End ' + nrPost);
};
function GoPosts() {
$.ajaxSetup({async:false});
var url = "http://......";
var data = { ... };
$.post(url, data, Callback, 'json');
};
function Callback(response) {
if (response.error) {
return;
}
nrPost--;
if (nrPost > 0) [
GoPosts();
} else {
return;
}
};
You had an extra }; in your code. I changed it around a bit to use jQuery and put it up on jsfiddle.
http://jsfiddle.net/rH8RV/19/
It should alert: "Start" and then "End 10", that's correct based on how you wrote your code. Were you expecting anything else?
I don't know what you're planning to do with your recursive implementation, but if that's all, you could actually do this:
function startLoop(nrPost) {
// No need to put this in a loop
$.ajaxSetup({ async: false });
for (var i = 0; i < nrPost; i++) {
alert('Start ' + i);
var url = 'http://......';
var data = {};
$.post(url, data, function (response) {
if (response.error)
return;
alert('End ' + i);
}, 'json');
}
}
$('#buttnX').click(function () { startLoop(10) });
Hope that helps!
I imagine you are expecting the display to be:
"Start"
"End 0"
This is unlikely to work with your solution.
Your Ajax call $.post(url, data, Callback, 'json'); is asynchronous. This means that once the $.post method returns, the request is sent to the URL you have provided. However, Callback is not called until JQuery receives the answers. What happens immediately is that GoPosts terminates and the program continues. It comes back to line 5 of your code, inside the anonymous function in your click handler. At that point, End() is called and alerts "End 10".
You probably want to put your call to End in Callback instead:
function Callback(response)
{
if (response.error)
{
return;
}
nrPost--;
if(nrPost>0)
GoPosts();
else
{
End(); // You only want to end once you have made you nrPost calls to GoPost
return;
}
};