So, I am doing a check when a user inputs an email to see if the email exists or not.
$('form.recover-form#check-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: {email: email},
success: function(response) {
if ( response == 'no' ) {
span.text('email does not exist');
} else if ( response == 'ok' ) {
form.submit();
}
}
});
});
The php code
if ( Input::isPost('email') ) {
$email = Input::post('email');
$check = $dbh->prepare(" SELECT * FROM users WHERE email = :email ");
$check->execute(array( 'email' => $email ));
echo ( $check->rowCount() == 1 ) ? 'ok' : 'no' ;
}
This way as soon as I submit the form it submits and the e.PreventDefault() inside the AJAX call is not working. If I put e.PreventDefault() before the AJAX call however, the form does not submit and the error appears if the email does not exists ( this is what I want to achieve ).
I can't understand where the problem is, hope you can help.
Thank you.
EIDT: This is the updated code
The problem is that you don't call preventDefault during the handling of the event. Instead, during the handling of the event, you start an ajax call (which is asynchronous), and then let the event continue. The ajax call completes later, which is too late to prevent the event's default — it's already happened.
Move the e.preventDefault() directly into the event handler, outside the ajax success handler.
$('.recover-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault(); // <=================== Here
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
// ============================ Not here, this would be too late
span.text('email does not exist');
}
}
});
});
In a comment, you've said:
Yes, it works for the validation, but I want to submit the form if ajax returns a positive response. I only do a check with AJAX, if it fails stop the submit, if it succeed continue the submit.
You can't hold up the original form submission waiting for the result of an asynchronous ajax call. What you do instead is cancel the original form submission, do the ajax, and then if the result is okay, re-submit the form using the submit method on the raw DOM form element. That method doesn't re-trigger submit event handlers.
Example: Live copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Delaying form submit during ajax</title>
</head>
<body>
<form action="http://www.google.com/search" method="GET">
<input type="text" name="q" value="kittens">
<input type="submit" value="Submit">
</form>
<script>
(function() {
$("form").submit(function(e) {
var rawFormElement = this; // Remember the DOM element for the form
// Stop form submission
display("Got form submit event, simulating ajax");
e.preventDefault();
// Simulate ajax check of data
setTimeout(function() {
// (This is the 'success' callback for the ajax)
display("Ajax call complete, pretending result is good and submitting");
// All okay, go ahead and submit the form
rawFormElement.submit(); // Doesn't trigger 'submit' handler
}, 1500);
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
</script>
</body>
</html>
You can't prevent the default action from a success handler of ajax request because of the asynchronous nature of it.
Instead by default prevent the form submission, then in the success handler if it is valid then call the submit again.
$('.recover-form').on('submit', function (e) {
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
//prevent the submit
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function (response) {
if (response == 0) {
span.text('email does not exist');
} else {
//submit if valie
form[0].submit()
}
}
});
});
First, you're options are incorrect. cache and async require boolean values, not strings.
async: false,
cache: false,
Secondly, instead of submitting the form after the ajax request you're instead triggering the event. Try this instead.
form.get(0).submit();
It returns the form node rather than a jquery object, allowing you to submit it directly rather than triggering an event (otherwise you would have an infinite loop.)
You don't really need async: false or cache: false in this case.
You need to do the following:
$('.recover-form').on('submit', function(e){
e.preventDefault();
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
span.text('email does not exist');
}
}
});
});
Notice how I've moved the e.preventDefault() to the beginning. This is because you were calling it when the ajax request responds which might happen 100s of milliseconds or even seconds after the form has been submitted
This happens because success function passed for jQuery.ajax() is executed assyncly, then it will be executed after event handler function is finish.
You should put the e.preventDefault() out of ajax function. and everything will work.
Better you can try something like this ,
<form name="myForm" onsubmit="return submitObj.validateAndSubmit();"> <!-- your form -->
<!-- your AJAX -->
var submitObj = {
validateAndSubmit : function()
{
var form = $('.recover-form'),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
return false;
}
else{
return true;
}
}
});
}
};
Related
This question already has answers here:
Sending multipart/formdata with jQuery.ajax
(13 answers)
Closed 6 years ago.
I would like to pass form data via jquery to a php page. Now I am little confused with image passing through jquery and how it will reach php page.
My code:
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var guestbookSendMessage = { //Fetch form data
'name' : $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file' :$("#fileInput")[0].files[0];
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'php/process.php', //Your form processing file url
data : guestbookSendMessage, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
You may use File API or FormData to send image data to your server with ajax. What to choose is up to you to decide but since FormData is easier to implement I will answer your question using FormData here.
First of all you need to create FormData container and append your data to it. Just amend your code
var guestbookSendMessage = { //Fetch form data
'name': $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file': $("#fileInput")[0].files[0];
};
with this
var guestbookSendMessage = new FormData();
guestbookSendMessage.append('name', $('input[name=name]').val());
guestbookSendMessage.append('msg', $('textarea[name=msg]').val());
guestbookSendMessage.append('file', $("#fileInput")[0].files[0]);
Now instead of this parameter in your $.ajax
dataType: 'json'
Add these two
processData: false,
contentType: false
This will allow your data to be interpreted correctly.
Now in your php/process.php script you'll get 'name' and 'msg' in your $_POST superglobal array and 'file' in $_FILES.
var fdata = new FormData();
var myform = $('#prfform'); // specify the form element
var idata = myform.serializeArray();
var document = $('input[type="file"]')[0].files[0];
fdata.append('document[]', document);
$.each(idata,function(key,input){
fdata.append(input.name,input.value);
});
$.ajax({
url:"process.php",
type: "POST",
data: fdata,
processData: false,
contentType: false,
beforeSend: function() {
//something before send
},
success:function(data) {
//something after response
}
});
<form name="prfform" id="prfform" method="post" enctype="multipart/form-data">
<!-- elements -->
</form>
Please try this code.
"enctype" is important in the form.
In ajax script, give "processData: false" and "contentType: false"
This might solve your issue.
I'm learning AJAX by reading some online tutorials, so please understand I am very new to AJAX and programming in general. I have managed to do the following with 3 selectboxes:
populates selectbox 2 based on selection from selectbox 1
populates selectbox 3 based on selection from selectbox 2
Everything is working perfectly
Here is my code:
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
Here is an Example
What I want to do
I would like to send the value of the 3 selectboxes to 3 php variables without the form reloading.
My Problem
When the user clicks submit:
The form reloads (which I dont want)
The selectbox values does not get send to my php variables
my code to get the values after submit is clicked is as follows:
if(isset($_POST['submit'])){
$a = $_POST['sport'];
$b = $_POST['tournament'];
:
}
However my code is flawed as I mentioned above.
If any one can help me to explain how to send my form data to the 3 php variables without the form reloading it will be greatly appreciated
If you don't want to submit your form when you click the button, you need to set that input as button and not submit. You can, also, attach the submit event handler to the form and prevent it to submit:
$("form").on("submit", function(e){
e.preventDefault(); //This is one option
return false; //This is another option (and return true if you want to submit it).
});
So, being said this, you could probably do something like:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'yoururl',
data: formData,
type: 'post', //Based on what you have in your backend side
success: function(data) {
//Whatever you want to do once the server returns a success response
}
});
});
In your backend:
if (isset($_POST["sport"])) {
//Do something with sport
}
if (isset($_POST["tournament"])) {
//Do something with torunament
}
echo "Successfull response!"; //You have to "write" something in your response and that is what the frontend is going to receive.
Hope this helps!
Try using the javascript function preventDefault().
See this SO question.
Use a <button>Submit</button> element instead of <input type="submit"/> since the submit automatically submits the form.
Edit: And you would have to use on.('click') instead of looking for submit event in your jQuery.
edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});
So, I have a form with one input text field(search_term) and a submit button.
What I'm trying to do is type in a keyword into the input text field, press Submit, the keyword gets sent to a php script that will json_encode it and send it back to the form page where an alert box should appear and show the keyword.
Instead I keep getting null shown in the alert box after pressing the submit.
PHP script works fine if I actually type it out in the url with keyword passed too:
localhost/filter.php?search_term=hey
JavaScript to submit the form and get the value back asynchroniously(without reloading the page):
$('#filter_form').on('submit', function(e){
var filtered_data = null;
e.preventDefault();
$.ajax({
type: 'GET',
dataType: 'json',
url: 'filter.php',
async: false,
success: function(json)
{
filtered_data = json;
}
});
alert(filtered_data);
});
filter.php:
$search_term = $_GET['search_term'];
echo json_encode($search_term);
You need to POST the value of the input to the processing page.
$('#filter_form').on('submit', function(e) {
e.preventDefault();
$inputValue = $('#search_term').val(); //if the id of the input is "search_term"
$.ajax({
type: 'POST',
data: {
'inputValue': $inputValue
},
url: 'filter.php',
success: function(json) {
alert(json);
}
});
});
filter.php should be changed to:
$search_term = $_POST['inputValue'];
echo json_encode($search_term);
i have the following javascript file named coupon.js -
jQuery(document).ready(function(){
jQuery('.appnitro').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return true;
});
});
sms.php -
<?php
//process form
$res = "message deliverd";
$arr = array( 'content' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
i am calling like this -
<form id="smsform" class="appnitro" method="post" action="sms.php">
...
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit"/>
</form>
<div id="content"></div>
Now i expected that after a successful form submission the div "content" would show the message without any page refresh.
But instead the page redirects to /sms.php and then outputs -
{"content":"message deliverd"}
Please tell where i am going wrong. My javascript is correct . No error shown by firebug. Or please tell some other method to acheive the reqd. functionality.
Even this coupon.js is not working-
jQuery(document).ready(function(e){
jQuery('.appnitro').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
e.preventDefault();
});
});
Not working even if i add return fasle at end. Please suggest some other method to acheive this functionality
The reason why the page is refreshing is because the submit event wasn't suppressed.
There are two ways to do this:
Accept an event object as a parameter to the event handler, then call preventDefault() on it.
return false from the event handler.
Answer to your revised question: You are accepting the e parameter in the wrong function, you should accept it in the submit handler, not the ready handler.
I believe you need to cancel the form submission in your jquery. From the jQuery documentation:
Now when the form is submitted, the
message is alerted. This happens prior
to the actual submission, so we can
cancel the submit action by calling
.preventDefault() on the event object
or by returning false from our
handler. We can trigger the event
manually when another element is
clicked:
So in your code:
//add 'e' or some other handler to the function call
jQuery(document).ready(function(e){
jQuery('.appnitro').submit( function() { $.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false
return false;
//or
e.preventDefault();
});
});