JQuery Ajax function return - javascript

I've defined a file availability.php that return "yes" or "no", well i have a form that must check availability of a form before subscribe a user, and i do this using this ajax function, but the compare line seems not work ?
availability: function(element, value) {
$.ajax({
type: "GET",
url: "/tunnel/availability.php",
data: "username="+element,
dataType: "html",
success: function(data){
$("#response").html(data);
var $response = data;
if ($response == "yes")
alert("found");
}
});
}

Try this:
availability: function(element, value) {
$.ajax({
type: "GET",
url: "/tunnel/availability.php",
data: "username="+element,
success: function(data){
if (data == "yes"){
alert("found");
}
}
});
}

Why do you think it's not working? If you're expecting your function to check and return a value before a form is submitted, it is likely that the availability function is returning before the ajax check is performed, allowing your form to submit and nullifying the alert -- i.e., the page is already unloaded and the new request is being processed. If you want to use this to check availability before submitting a form you'll need to:
Return false from availability (or otherwise stop the form submission)
Do the form submission from the availability success function.
(maybe) Indicate that you're expecting a text response instead of html.
You can also simplify the check -- there's no need to put "data" in a variable before you check it. I'm also not sure why you are adding it to the page, but that could be reasonable. I'd also suggest a name change for the function (if you modify it to do this) and handling the form submission via AJAX -- if not, you can remove the handler and simply trigger a submit on the form.
submitIfAvailable: function(form, element, value) {
$.ajax({
type: "GET",
url: "/tunnel/availability.php",
data: "username="+element,
dataType: 'text', // I think it should work without this, but...
success: function(data){
if (data == "yes"){
$form = $(form);
$.post( $form.attr('action'), $form.serialize(), function(result) {
// process the result of form submission
});
}
}
});
return false;
}
I'm making some assumptions -- modify as appropriate if this doesn't fit in with how the availability function is used. The key thing to remember is that the function will return before the AJAX call completes and you can't use any return value from the function that comes from the AJAX call. This is true, at least, if you don't force the AJAX call to run synchronously by setting the option aSync to false.

You need to confirm what the availability page is actually returning.
Debug the callback using Firebug (or your favourite JS debugger) to see what sort of object is returned as data. You might find that your return value is wrapped, eg you might have to check data.value or something similar.

Related

How to handle API call error with jQuery AJAX?

I am making a weather app as a school project. I have an input through which the user is supposed to enter a name of a city to get the weather from an API. If the user misspells the name of the city I get an error in the console. I'd like to catch this when it happens and display some message to inform the user to correct the input. I searched other questions on StackOverflow and jQuery site as well, but didn't get my answer so that's why I'm here.
My code looks like this:
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (weatherData) {...//code}
I tried putting the ajax inside a try/catch block and added error: function().. beneath success, it still doesn't display an error message.
Why isn't this working? Is this easier to do in plain javascript?
Add an if statement to your success function to check if the list has elements in it. Otherwise you will get an error trying to get the name of an element that doesn't exist.
success: function (weatherData) {
if (weatherData.list.length > 0)
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((weatherData.list[0].name)));
}
From your comment it seems that you go and use this:
weatherData.list[0].name
your response as you mentioned is like this
"message":"like","cod":"200","count":0,"list":[]
You should check your response in order to see if you have any server errors.
My guess from what you have provided seems like you don't take into consideration neither the response code nor the number of items. You should change your ajax success handler to something like the following.
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (result) {
// Error handling
if (result.code != '200'){
alert('some kind of error');
return false;
}
// Checking the number of list items
if (result.list.length > 0){
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((result.list[0].name)));
}
}
});

Wait for Async ajax to complete before moving onto other code?

I know this has been asked, probably, a million times, but for the life of me I cannot get anything to work.
I have a UI wizard control that on the "changed" event validates the model. If the model is not valid, it doe not allow the user to move forward in the wizard. I have tired using the $.when().done() feature in jquery, but my code still passes through before making sure the model is valid. The reason for calling an async ajax request is I do not want the UI to lock up so I can show some sort of progress indicator. I had set the async property to false, but my UI indicator would never show up. Here is an example of what my code is doing:
//the change event that is called when the user clicks 'next' on the wizard:
wizard.on('change', function (e, data) {
var isValid = $.validate({
"Model": [The_UI_MODEL],
"Url": [URL_To_Server_Validation],
"Async": true, //tells ajax request to send as async
});
//Tells the wizard not to move 'next' if the request comes back as not valid
if (data.direction === 'next' && !isValid) {
e.preventDefault();
}
}
//I am using the $.extend method for JQuery to create a function that will validate any model in my system.
validate: function(options) {
//Clear any previous validation errors
$.clearValidations();
var data = $.postJson(options);
//the result is getting returned before the $.postJson(options) finishes
return data.Success;
}
//I created my own method that extends the $.ajax method so I could do other things before /after a request:
postJson: function(options){
...other code for my application
//This is where I want the ajax request to happen and once done return the data coming back
//This is what I have tried, but it is not doing what I thought.
$.when(function(){
return $.ajax({
url: options.Url,
type: 'POST',
cache: false,
async: options.Async,
timeout: options.Timeout,
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(options.Model),
error: function(xhr, status, error) {
...do stuff if ajax errors out
},
success: function (data) {
},
});
}).done(function(response){
//looks like i get back the responseText of the request. which is fine, but other posts i have read stated i should be getting back the request itself
...other UI stuff
return response;
})
}
KarelG is absolutely right. You need to refactor your code and do your valdiation check within the success callback of the ajax request.
Something like this...
wizard.on('change', function (e, data) {
$.ajax({
url: [URL_To_Server_Validation],
type: 'POST',
cache: false,
async: true,
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {"Model": [The_UI_MODEL]},
success: function (response) {
//Tells the wizard not to move 'next' if the request comes back as not valid
if(!response & data.direction === 'next')
{
e.preventDefault();
}
}
});
});
It looks like you're trying to write asynchronous code as if it were synchronous. An asynchronous call such as your $.validate() will return immediately without a result and continue on to the rest of your code. Anything you want to happen when the validate call finishes must be done in a callback function passed to it.
You can use jQuery promises (when, then, done, etc.) or another library such as async.js to help manage the control flow.
Also, this isn't particularly useful now since there's little to no browser support for it yet, but the yield operator plus a library such as Task.js will eventually let us write asynchronous code as if it were synchronous.

Post form to web2py function using ajax

The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});

why does the data property in an jquery ajax call override my return false?

i have the following block of code:
$("#contact_container form, #contact_details form").live(
"submit",
function(event) {
$.ajax({
type: this.method,
url: this.action,
data: this.serialize(),
success: function(data) {
data = $(data).find("#content");
$("#contact_details").html(data);
},
});
return false;
}
;
when i leave out the data: this.serialize(), it behaves properly and displays the response within the #contact_details div. however, when i leave it in, it submits the form, causing the page to navigate away. why does the presence of the data attribute negates the return false? (probably due to a bug that i can't spot...)
also, is the syntax to my find statement correct? it comes back as "undefined" even though i use a debugger to check the ajax response and that id does exists.
thanks,
steve
I think that this.serialize() fails because this points to the form element and not a jQuery object.
This probably causes a script error and therefore the return statement is never reached.
Try changing it into:
data: $(this).serialize()

Is it possible to make JqGrid send a JSON QueryString to server?

Is it possible to tell jqGrid to send all search options in JSON format ? Hence I won't have to reformat it on the backend side.
There is no direct function like that mentioned in the documentation, so you will probably have realize that manually in the beforeSubmit method of the jqGrid. I would spontaneously use jQuerys serializeArray method for the form and a JSON Serializer. Then you will have to submit the serialized Form via Ajax. Just make sure, that you return success : false, so that jqGrid doesn't submit the form.
beforeSubmit : function(postdata, formid) {
var formarray = $('#' + formid).serializeArray();
var httpbody = JSON.stringify(formarray);
// Send accordingly via AJAX
$.ajax(...);
// This looks kind of weird, but we don't want jqgrid to continue cause it was sent already
return { success : false, message : "Successffully saved" };
}
Doesn't seem like the nicest sollution though but the beforeSubmit Event is probably the only place to dig into it.
I don't know how helpful this will be, but I found that I can return true here as long as I set my editurl to '#' ....
beforeSubmit : function(postdata, formid) {
if (isValid) {
$.ajax({
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
url: "/RateIQ/Main.aspx/Accessorial/AccessorialDetailSave",
data: JSON.stringify(postdata),
dataType: "json"
});
}
return [isValid, ""];
}
and I've experienced no side effects so far...

Categories