I am making an ajax call on submit button click event to check field validations server side.
When I get a validation fail, ajax response gives the proper error message, returns false, and stops the form to submit to the action url. But when I get a response of 'success', the form is still not submitting to the action url script.
Is this the case when return statement executes before ajax response?
And also why is the form not getting submitted?
Here is the code:
<input type="submit" onclick="return validate();" name="submit" value="Proceed" />
<script type="text/javascript">
var flag=false;
function validate(){
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
success: function (result) {
if(result.toString() == "success" ){
flag=true;
}
else{
$('#error').css('display', 'block');
$('#error').css('color','red');
$('#error').text(result.toString());
flag=false;
}
}
});
return flag;
}
</script>
one Way is
use async : false
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
async : false,
success: function (result) {
And also why are you returning the value outside the ajax function , return the value inside ajax success if you are not using async : false
$.ajax({
type:"POST",
url:"../chk.php",
data:datastring,
cache: false,
success: function (result) {
if(result.toString() == "success" ){
flag=true;
}
else{
$('#error').css('display', 'block');
$('#error').css('color','red');
$('#error').text(result.toString());
flag=false;
}
}
return flag;
});
Ajax is asynchronous, so you should just pass a function to the function as an argument, and then execute it on success of the ajax call.
function my_callback() {
alert('done');
}
function validate(cb) {
$.ajax({
/* ... */
success: function() {
cb();
}
});
}
The function you pass to validate will be executed upon the success function call.
Related
I have a HTTP handler (ASHX) which I am calling from UI side using an AJAX function. The following is what needs to happen in this call:
When the section loads, it will display the status of the short code on the server in the shortcodestatus span. It will either say on or off:
<a class="btn btn-default" id="toggleshortcode">Short Code <span id="shortcodestatus"></span></a>
This is the function for getting the status of the short code and this works properly. I can manually change the status of the short code and the changes reflect properly on the div when I reload the page:
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
$("#shortcodestatus").empty();
if (output == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
});
};
This is the short code status code from the handler:
case "shortcodestatus":
{
output = ShortCodeStatus() ? "true" : "false";
}
break;
I want to be able to click on the toggleshortcode div to fire off this event through the handler. The functions for disabling and enabling the short code are working properly:
case "toggleshortcode":
{
if (ShortCodeStatus() == true)
{
DisableShortCode();
output = "false";
}
else
{
EnableShortCode();
output = "true";
}
}
break;
Here is the ajax call for the short code toggle:
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
ShortCodeStatus();
}
});
});
I'm hitting the URLs correctly and I'm getting the correct responses from each function. However the change to the short code does not seem to be happening.
For example, if the short code is off, the ShortCodeStatus function will return false and thus render the OFF button. When I click on the toggleshortcode button, the output is true (I want to turn on short code) which is correct but when the ShortCodeStatus function fires again in the success, it will still say false. The ajax functions seem correct but I can't figure out why the toggleshortcode on the handler is not firing properly.
Thank you so much for your time!
I'm seeing 2 cases that you can check.
First, in the ajax call for 'toggleshortcode', you are calling the function 'getShortCodeStatus()', and base on your example the correct name of the function is 'ShortCodeStatus()'.
Second, in the call to 'Handler.ashx?action=toggleshortcode', you are already returning the status (true or false), I suggest you make a javascript function named SetShortCodeStatus(status) , and use this inside of the success of both ajax request 'Handler.ashx?action=shortcodestatus' and 'Handler.ashx?action=toggleshortcode'.
function SetShortCodeStatus(status) {
$("#shortcodestatus").empty();
if (status == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
SetShortCodeStatus(output);
}
});
};
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
SetShortCodeStatus(output);
}
});
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return AJAX response Text?
How to return the response from an AJAX call from a function?
So I have a javascript function where I'm doing an AJAX call to see if the user is online or offline. It looks something like this.
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
return html;
}
});
}
I would like to assign the value from this function as a variable that I can then use.
Something like this.
var test = onlineStatus();
if (test == "true")
alert("online");
else
alert("offline");
Is this possible? I must be doing something wrong, but can't figure out how to achieve this result. Thanks
// Edit:
Thanks for your help everyone, sorry, didn't realize it may have been a duplicate question. I wasn't sure what to search for initially, so I didn't see anything related.
$.ajax is asynchronous so you can't return anything from onlineStatus, you need to pass it a callback function that can be called when the ajax call completes.
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
});
}
onlineStatus(function(test) {
if (test == "true")
alert("online");
else
alert("offline");
});
Since calls happen asynchronously, you'll have to pass a callback function into onlineStatus. Something like:
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
callback(html);
}
});
}
And then call it with:
onlineStatus(function (html)
{
// Do stuff with the status
});
You can simple use a deferred object.
function onlineStatus(){
var request = $.ajax({
url: "assets/ajax/online-offline.php",
cache: false
});
return request;
}
var test = onlineStatus();
test.done(function(html) {
if (html)
alert("online");
else
alert("offline");
});
$.ajax returns a jqXHR, so you can use .done:
jqXHR.done(function(data, textStatus, jqXHR) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated
AJAX is asynchronous, that's what the A stands for. You need pass a callback.
For example:
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
});
}
onlineStatus(function(data) {
if (data == "true") {
alert "online";
}
else {
alert "offline";
}
}
The $.ajax method is asynchronous so you need to handle its return values in the callback.
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
if (html == "true")
alert("online");
else
alert("offline");
}
});
}
you can do like this.......but it is not a good method because synchronous request by ajax makes your code slow.......
function onlineStatus(){
var data;
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
async:false,
success: function(html){
data = html;
}
});
return data;
}
or
if you only want to dispaly the alert box then...
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
if (html== "true")
alert("online");
else
alert("offline");
}
});
return data;
}
jQuery ajax call is an asynchronous call. You will have to wait to get the results before you can use them for showing the alert.
var isOnline = false;
checkOnlineStatus();
function checkOnlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
}
});
}
function callback(html){
isOnline = (html == "online");
showAlert();
}
function showAlert(){
if (isOnline == "true")
alert("online");
else
alert("offline");
}
I'm calling the JavaScript function onsubmit of form but form has submit before finished the submit function.If I use the alert in the onsubmit function it finish the function first then submit the form.I used the settimeout function in place of alert but it didn't work.How can I submit the form after the onsubmit has complete.
function chat1close(name){
var abc;
abc=window.frames[0].test();
$.ajax({
type:'GET',
url:'modules/closechat.php?abc='+abc+'&name='+name,
success:function(data){
}
});
document.getElementById("hello").innerHTML=" ";
alert("yes");
return true;
}
Add async: false to your ajax call. This will prevent it from executing the rest of the function until the call returns.
If chat1close is the function that is being executed on the form submit and you want the code to be executed synchronously then set the following option on the .ajax request:
async:false,
http://api.jquery.com/jQuery.ajax/
Easy way to do this:
var $form = jQuery("#the_form");
var should_submit = false;
$form.submit(function () {
if (should_submit)
return true;
$.post('some/async/thing', function () {
//This is an async callback that
//will set the should submit var to true and resubmit form.
should_submit = true;
$form.submit(); //will now submit normally because should_submit is true.
});
return false;
});
The form isn't sent before the function has finished, but you are making an asynchronous AJAX call in the function, and the form is sent before the AJAX response arrives and the success callback function is called.
The only way to do an AJAX call before the form is sent is to use a synchronous AJAX call, but that will freeze the browser while it's waiting for the response:
function chat1close(name){
var abc = window.frames[0].test();
$.ajax({
type: 'GET',
async: false,
url: 'modules/closechat.php?abc='+abc+'&name='+name,
success:function(data){
document.getElementById("hello").innerHTML=" ";
alert("yes");
}
});
return true;
}
However, you can stop the form from being sent, and instead send the form after the AJAX response has arrived:
function chat1close(name){
var abc = window.frames[0].test();
$.ajax({
type: 'GET',
async: false,
url: 'modules/closechat.php?abc='+abc+'&name='+name,
success:function(data){
document.getElementById("hello").innerHTML=" ";
alert("yes");
$('#IdOfTheForm')[0].submit();
}
});
return false;
}
I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jquery ajax call taking too long or something
for some reason this ajax call
$('#new_user').submit(function(e){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
}
}
});
});
is still submitting the form even after prints out my error and my return false....why is that
$.ajax is a function call which defines an AJAX callback then and the .submit function ends. Separately (asynchronously) the AJAX call is made and your success function then returns false to basically nothing since .submit has already finished.
What you really want to do is halt the form submission process, waiting for the AJAX call to finish, then decide if it should continue. This can be achieved by completely stopping the form submission the first time, then manually resubmitting it once you've got the AJAX callback. Of course the trick is how do you know it's valid? You could throw a value on the submit element.
Example:
$('#new_user').submit(function(e){
var submitElem = $(this);
// Check for previous success
if (submitElem.data('valid') !== true) {
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false) {
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
} else {
// If successful, record validity and submit (allowing to continue)
submitElem
.data('valid', true)
.submit();
}
}
});
return false;
} else {
// Fall through
return true;
}
});