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.
Related
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();
};
what is wrong with this ajax request? the page is still reloading without giving any popups. if i remove everything after the "event.preventDefault();" it will stop page reload so i figure it must something with how i'm using the ajax method. This is for a php-self validating form
<script type="text/javascript">
//attach submit event handler to the form
$('#rsgform1').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
//Clear result div
$("#rsgresult").html('');
//get values from from
var values = $(this).serialize();
// do an ajax request
$.ajax({
url: "contact.php",
type: "post",
data: values,
success: function(){
alert("success");
$("#rsgresult").html('Submitted successfully');
},
error:function(){
alert("failure");
$("#rsgresult").html('There is error while submit');
}
});
</script>
You forgot to close the ajax call...
<script type="text/javascript">
//attach submit event handler to the form
$('#rsgform1').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
//Clear result div
$("#rsgresult").html('');
//get values from from
var values = $(this).serialize();
// do an ajax request
$.ajax({
url: "contact.php",
type: "post",
data: values,
success: function(){
alert("success");
$("#rsgresult").html('Submitted successfully');
},
error:function(){
alert("failure");
$("#rsgresult").html('There is error while submit');
}
});
});
</script>
Try return false at the end of the callback function.
And don't forget to balance your braces as others have mentioned.
your script has a missing pair of closing brackets }) at the end
$('#rsgform1').submit(function (event) {
//prevent the form from submitting by default
event.preventDefault();
//Clear result div
$("#rsgresult").html('');
//get values from from
var values = $(this).serialize();
// do an ajax request
$.ajax({
url: "contact.php",
type: "post",
data: values,
success: function () {
alert("success");
$("#rsgresult").html('Submitted successfully');
},
error: function () {
alert("failure");
$("#rsgresult").html('There is error while submit');
}
});
});// <-- missing this closing pair
You have an error in your JS. When an error occurs, the page refreshes.
<script type="text/javascript">
$('#rsgform1').submit(function(event) {
event.preventDefault();
$("#rsgresult").html('');
var values = $(this).serialize();
$.ajax({
url: "contact.php",
type: "post",
data: values,
success: function() {
alert("success");
$("#rsgresult").html('Submitted successfully');
},
error:function() {
alert("failure");
$("#rsgresult").html('There is error while submit');
}
}); // Missing
});
</script>
I am using codeiniter framework. I want to Submit form data in database throught ajax coll and after success submiting form process I want to refresh specific div through other ajax request.
But When I press Enter Key for submit form then data is being submitted twice. I want submit data by ajax once time with on enter key press.
My code like-
$('#form1').submit(function () {
var id = $('#id').val();
var comment_text = $('#comment_text').val();
$.ajax({
data: {'id' :id,'comment_text':comment_text},
type: "POST",
url: "first_req.php",
dataType : "json"
success: function(data){
if(data.status =="Success")
{
$.ajax({
data: {'id':id},
type: 'GET',
url: 'sencond_req.php',
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
$('#com_display').html(data);
}
});
}
}
});
return false;
});
HTML-
<div id="com_display"></div>
<form id="form1" name="form1">
<input type='hidden' id='id' name='id' />
<input type='text' id='comment_text' name='comment_text' />
</form>
When I type hi in comment box and press enter button then data two times will be submitted in database.
Please give me any solution to solve it.
Even though you are submitting the data using ajax request, you are not stopping the default action of the form submit.
You can call the event.preventDefault() to do this.
$('#form1').submit(function (e) {
//prevent the default form submission
e.preventDefault();
var id = $('#id').val();
var comment_text = $('#comment_text').val();
$.ajax({
data: {
'id': id,
'comment_text': comment_text
},
type: "POST",
url: "first_req.php",
dataType: "json"
success: function (data) {
if (data.status == "Success") {
$.ajax({
data: {
'id': id
},
type: 'GET',
url: 'sencond_req.php',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
$('#com_display').html(data);
}
});
}
}
});
});
or return false from the event handler if you want to prevent the default and action and stop the bubbling of the submit event
Possible duplicate of this, this and this
In the Documentation READ HERE
(Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.)
In other words, when you click enter you will trigger default submit of the form, and also your jquery will submit the form.
Solution:
Prevent default behavior by adding e.preventDefault();. Read -> jQuery AJAX Form Submit Example
$('#form1').submit(function (e) {
e.preventDefault();
//the rest of code.
remove default behavior
$('form').submit(function(){
$(this).find(':submit').attr('disabled','disabled');
});
3. Only submit the form thru jquery when it actually submits (no resubmitting)
$(document).on("submit", "form.form1", function(event){
alert(1);
});
I am trying to create a post using Ajax and jQuery.
But it isn't working. It just refreshes the current page.
HTML :
<form name="update_text_post" action="" id="update_text_post" method="post">
<textarea name="textbox" class="textbox" maxlength="600"></textarea>
<input type="submit" name="submit" value="Update" class="update_post_submit">
</form>
jQuery :
$('#update_text_post').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
return false
});
The e.preventDefault(); is not working aswell.. it actually is not even performing the MYSQL query . Seems like it is not even sending the form or targeting the post_ajax2.php file.
You need to use .preventDefault() to stop the default form submit behavior with page reload.
$(function() {
$('#update_text_post').submit(function(e) {
e.preventDefault(); // e.preventDefault() for prevent form submisson with page reload
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
// 1. you missed $ here, so it will not be a dom ready callback.
// your case is just define a function, and without executing it.
$(function () {
$('#update_text_post').submit(function (e) {
// 2. you need to prevent the default submit event.
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
You have to stop the default behavior of the submit button (form posting).Otherwise the form will be submitted again and you will see the page loading again ( you won't notice the change ajax brought to your page- some partial page updates ). You can use the preventDefault function to do this.
$(function(){
$('#update_text_post').submit(function(e) {
e.preventDefault(); // prevent the default submit behaviour
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
Add return false.
$('#update_text_post').submit(function(e) {
$.ajax({
...
})
return false;
});
Clicking on a submit button does just that - it submits the form. If you want to replace the form submission with an AJAX POST request, you'll need to stop the form from also being submitted (and the page therefore reloading), by preventing the default behaviour of that event.
You can do this by calling return false; at the end of the callback function bound to the submit event handler, or by passing a reference to the event to the callback function and calling e.preventDefault() (where e refers to the event).
The key difference between the two methods is that return false, in a jQuery callback function, will also prevent the event from bubbling. In this case, that's not really a big deal.
You have to call e.preventDefault(); in your function to prevent the form submit.
$('#update_text_post').submit(function(e) {
// prevent form submit
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
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.