This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm wanting to use AJAX to determine whether or not a form's values are acceptable to me (this is not form validation). The AJAX result will determine if the form is submitted or not.
Below, you'll see that I perform an AJAX call when the form is submitted and depending what is returned (either blank which is acceptable, or an error message which is not acceptable), I'd like to return true; or return false; the $("form").submit.
I suspect my trouble to be in the AJAX's success:. Please help me get the result out of the AJAX call so that I can do something like if (result == "") { return true; } else { return false; }.
WORKING:
$("form").submit(function(e) {
e.preventDefault();
var form = this;
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "")
form.submit();
else
alert(result);
}).fail(function() {
alert('ERROR');
});
});
ORIGINAL:
$("form").submit(function() {
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
success: function(result) {
alert(result);
},
error: function(result) {
alert(result); //This works as expected (blank if acceptable and error msg if not acceptable)
}
});
/*
if (result == "")
return true;
else
return false;
*/
return false; //this is here for debugging, just to stop the form submission
});
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("form").submit(function(e) {
e.preventDefault();
var self = this,
tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "") self.submit();
}).fail(function() {
alert('error');
});
});
use e.preventDefault(); to prevent the form from submitting, and then use this.submit() (isn't calling the jQuery .submit() trigger function, but rather the native <form> .submit() function) to submit the form.
$("form").submit(function(e) {
e.preventDefault();
var tray = $('select[name=tray_id]').val();
var form = this;
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
complete : function(result){callback(result, form)}
});
});
var callback = function(result, form){
if(!result)
form.submit();
};
Related
I am using ajax validation in URL field, I getting correct message (after a check from database), but still form is submitting
I want if I getting an invalid message then the form should not submit, how can I do this ?
<script>
$(document).ready(function(){
$("#Url").blur(function() {
var element = $(this).val();
$.ajax
({
url: "<?php echo site_url('Welcome/check_user_status'); ?>",
type: 'POST',
data: "url="+element,
success: function(data){
alert(data);
$('#emailInfo').html(data);
if(jQuery.trim(data) === "Emailvalid")
{
alert("Emailvalid");
}
else
{
alert("Email Invalid");
}
console.log(data);
}
});
});
// return false;
});
</script>
<form name="myForm" id="myForm">
<script>
$(document).ready(function(){
$("#Url").blur(function() {
var element = $(this).val();
$.ajax
({
url: "<?php echo site_url('Welcome/check_user_status'); ?>",
type: 'POST',
data: "url="+element,
success: function(data){
alert(data);
$('#emailInfo').html(data);
if(jQuery.trim(data) === "Emailvalid")
{
alert("Emailvalid");
}
else
{
alert("Email Invalid");
$("form").submit(function(e){
e.preventDefault();
});
}
console.log(data);
}
});
});
// return false;
});
</script>
Your tests are placed in the success callback, which is fired after the $.ajax() call has successfully POSTed data and received a response. No matter what you put in there, it is only ever going to happen after the form has been submitted.
If you are trying to do validation before your POST, you need to add that separately. Depending on what kind of validation you need, you could write your own simple tests, or use a plugin - jQuery Validation is a great option.
add this in your footer file
<script>
var burl="<?php echo base_url('') ?>";
var surl="<?php echo site_url('') ?>";
</script>
and then use this surl on ajax url...
like this
<script>
$(document).ready(function(){
$("#Url").blur(function(e) { // add e
e.preventDefault();// prevent other events
var element = $(this).val();
$.ajax
({
url: surl+"Welcome/check_user_status",
type: 'POST',
data: {"url":element}, // check the change
success: function(data){
if($.trim(data) === "Emailvalid"){ // instead of jQuery use $
alert("Emailvalid");
$('#emailInfo').html(data); // put here
}else{ // remove the space between if and else
alert("Email Invalid");
return false; // add here
}
console.log(data);
}
});
});
});
</script>
Hi i have problem with form redirection to its action target, validation ajax interrupt the form redirection here is my code , all i just submit the post to form action location also redirect on that location.
$("form").submit(function(e){
jQuery.ajax({
type : "post",
url : "validate.php",
dataType : "json",
data : {email : 'example#domain.com'},
success: function(response) {
if(response.status == '1'){
//Email is valid want to continue form submit and redirect , but it is not
}else{
e.preventDefault();
//return false
}
}
});
})
You may need to create a separated function to submit your form as a callback of the validation ajax process and pass the serialized data to it, something like :
function submitForm(serializedData) {
jQuery.ajax({
ur: "{your form action processing file}",
type: "POST",
data: serializedData,
success: function (data, textStatus, xhr) {
console.log("form submitted "+xhr.status) // 201 if everything OK
// optionally reload the page
window.location.reload(true);
}
});
}
jQuery(document).ready(function ($) {
// validate form
$("#myForm").on("submit", function (event) {
// prevent form from being submitted
event.preventDefault();
// collect your form data to be submitted :
var serializedData = $("#myForm").serializeArray();
$.ajax({
url : "validate.php",
type: "POST",
cache: false,
dataType : "json",
data : {email : 'example#domain.com'},
success: function (response) {
if(response.status == '1'){
// email is valid so submit the form
submitForm(serializedData);
} // you don't need an else statement since we already used event.preventDefault() before the ajax call
},
error: function () {
console.log("ajax validation error");
}
})
}); // on submit
}); // ready
Notice we assigned a selector (#myForm) to the form we are processing.
Im trying to use if else statement in success ajax function, but the value always false and data inserted
I use jQuery v1.7.1, here my code
// Contact Submiting form
function Contact_form(form, options){
$.ajax({
url: 'contact.php',
data: $('#contactform').serialize(),
success: function(data){
if(data.check == '1'){ // if Ajax respone data.check =1 or Complete
$('.notifications').slideDown(function(){
setTimeout("$('.notifications').slideUp();",7000);
}); // Show notifications box
$('#contactform').get(0).reset(); // reset form
}
else if(data.check == '0'){
$('#preloader').fadeOut(400,function(){ $(this).remove(); });
alert("No complete");
return false;
}
},
cache: false,type: 'POST',dataType: 'json'
});
}
if else is bad in success function use
function Contact_form(form, options){
$.ajax({
url: 'contact.php',
data: $('#contactform').serialize(),
success: function(data){
$('.notifications').slideDown(function(){
setTimeout("$('.notifications').slideUp();",7000);
}); // Show notifications box
$('#contactform').get(0).reset(); // reset form
unloading(); // remove loading
},
error: function(data){
$('#preloader').fadeOut(400,function(){ $(this).remove(); });
alert("No complete");
return false;
},
cache: false,type: 'POST',dataType: 'json'
});
}
Can you try to use data.result in logic statement
I'm currently working on a multi-step query form which can be found at: http://jsfiddle.net/xSkgH/47/.
I'm trying to submit the variables via jQuery AJAX (process.php will handle the processing) and refresh the div last-step with the div in the process.php called result. How can I achieve this?
I've so far managed to accomplish this using the jQuery form plugin by malsup (http://jquery.malsup.com/form/) and now need to using the jQuery AJAX method to accomplish it as part of a strict specification.
This is the code I had been using (with the jQuery form plugin):
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#result',
beforeSubmit: showRequest,
success: showResponse
};
// bind to the form's submit event
$('#task5_booking').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
// alert('About to submit: \n\n' + queryString);
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}
Many thanks!
Use jQuery.ajax to handle the last step:
http://api.jquery.com/jQuery.ajax/
else if (whichStep == 'last-step') {
$.ajax( {
url:'urltophp.php',
data: {}, // your data
dataType: 'json', //your datatype
type: 'POST', //or GET
success: function(r) {
//your callback here...
}
});
}
Edit:
$('#task5_booking').submit(function(e) {
$(e).preventDefault(); //prevent the default form submit()
var formData = $(this).serialize(); //serialize the form fields data...
$.ajax( {
url:'urltophp.php',
data: formData, // your data
dataType: 'json', //your datatype
type: 'POST', //or GET
success: showResponse
});
//$(this).ajaxSubmit(options);
//return false;
//});
});
Change this:
function showResponse(responseText, statusText, xhr, $form) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}
To this:
function showResponse(responseText) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}
use http://api.jquery.com/load/ .
it's like using .ajax, only easier and fits your requirements.
$('#last-step').load(url, data, function(){}) sends a post request, and fills the html content of 'last-step' with whatever the url printed out into the response html.
The title almost says it all. I have a jquery code i've written, im not good at it but this is what i achieved:
$("#myForm").submit(function(){
//alert($(this).serialize());
$.post("submit.php", $(this).serialize(), function(data){
if(data == success) {
$("#add_vote").fadeOut("fast");
$("#verification_sent").fadeIn("fast");
$("#wrong").fadeOut("fast");
} else {
$("#wrong").fadeIn("fast");
}
});
return false;
});
The form gets submitted well but the fadeIn and fadeOut's I have does not work. Do anyone know why?
Verify what submit.php returns, and what is in data.
if(data == success) {
This looks suspicious, did you meant if (data == "success") { ? (success is a variable, probably undefined; "success" is a string.)
What is success in:
if(data == success) {
Maybe you mean:
if(data == "success") {
Or else you maybe have misunderstood the $.post function?
$.post("submit.php", $(this).serialize(), function(data){
Lets break it up:
"submit.php" // the url (OK)
$(this).serialize() // The data (OK)
function(data){ // The callback on success
And its only a helper function for the $.ajax method, Witch also have a error callback:
var ajaxObj = $.ajax({
type: 'POST',
url: "submit.php",
data: $(this).serialize()
});
ajaxObj.success(function(){
// Success
});
ajaxObj.error(function(){
// Error
});