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();
});
});
Related
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;
}
}
});
}
};
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;
});
Javascript part...
It stops at the $("#deletar").click...
$(document).ready(function() {
$("#deletar").click(function() { // it fails here !!
var sendu = $("#ids").val();
$.ajax({
type : "POST",
url : "deletar.php",
data : "ids=" + sendu,
success : function(msg, string, jqXHR) {
$("#result").html(msg);
}
});
});
});
This is the php file... is a echo to other ajax post, and retrieves a list of a mysql db
.$row2['amigos']."
</td>
<td><inp ``ut type='submit' name='deletar' id='deletar' value='deletar'
OnClick='return confirm(\"Tem certeza que quer deletar esta linha?\");'>
<input type='hidden' name='ids' id='ids' value='".$row2['id']."'>
</td>
</tr>
";
enter code here
Your ajax is being called from a submit button click. You haven't done anything to prevent the default behaviour of the submit button, therefore after your ajax call, the browser will submit the form using a traditional request.
In your click event, you can return false to prevent the form submitting:
$("#deletar").click(function(){ //it fails here !!
var sendu = $("#ids").val();
$.ajax({
type:"POST",
url:"deletar.php",
data: "ids="+sendu,
success: function(msg,string,jqXHR){
$("#result").html(msg);
}
});
return false; // <--- stop the form submitting
});
You can also use e.preventDefault to achieve the same result.
I think you need to stop the form submitting after the submit button has been clicked:
$(document).ready(function () {
$("#deletar").click(function (event) {//it fails here !!
event.preventDefault(); // one of these
event.stopPropagation(); // lines should do the trick
var sendu = $("#ids").val();
$.ajax({
type : "POST",
url : "deletar.php",
data : "ids=" + sendu,
success : function (msg, string, jqXHR) {
$("#result").html(msg);
}
});
});
});
i want to submit all form's infomation with an onclick event function (i don't want to use a conventional submit ). How can i use the post or ajax method?
here is my code
$("#login_form").bind("click", function() {
var qtyVal = document.getElementsByName('id[]').length;
$.ajax({
type : "post",
cache : false,
url : "abcd.php?ref=xyz",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
You should not use from this keyword here. You click on a button to send the form data,so this will return you the button element. You should not use from 'click' event for your form too. You can do like the following code:
function send(){
$.ajax({
type : "post",
cache : false,
url : "abcd.php?ref=xyz",
data : $('#frm').serializeArray(),
success: function(data) {
alert(data);
}
});
return false;}
<form id="frm"><input type="button" id="submit" onclick="send()" /></form>
Are you looking for .submit() ?
If login_form is really a form (i.e. <form id="login_form">), you can do:
$("#login_form").submit();
to submit your form the conventional way without AJAX call.
Currently my AJAX is working like this:
index.php
<a href='one.php' class='ajax'>One</a>
<div id="workspace">workspace</div>
one.php
$arr = array ( "workspace" => "One" );
echo json_encode( $arr );
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
jQuery('#' + id).html(snippets[id]);
}
});
});
});
Above code is working perfectly. When I click link 'One' then one.php is executed and String "One" is loaded into workspace DIV.
Question:
Now I want to submit a form with AJAX. For example I have a form in index.php like this.
<form id='myForm' action='one.php' method='post'>
<input type='text' name='myText'>
<input type='submit' name='myButton' value='Submit'>
</form>
When I submit the form then one.php should print the textbox value in workspace DIV.
$arr = array ( "workspace" => $_POST['myText'] );
echo json_encode( $arr );
How to code js to submit the form with AJAX/JSON.
Thanks
Here is my complete solution:
jQuery('#myForm').live('submit',function(event) {
$.ajax({
url: 'one.php',
type: 'POST',
dataType: 'json',
data: $('#myForm').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
Submitting the form is easy:
$j('#myForm').submit();
However that will post back the entire page.
A post via an Ajax call is easy too:
$j.ajax({
type: 'POST',
url: 'one.php',
data: {
myText: $j('#myText').val(),
myButton: $j('#myButton').val()
},
success: function(response, textStatus, XMLHttpRequest) {
$j('div.ajax').html(response);
}
});
If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:
$j('div.ajax').load('one.php', data);
Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.
However it should be a fairly simple loop.
Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as
$('#myForm').ajaxSubmit();
You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.
You can submit the form with jQuery's $.ajax method like this:
$.ajax({
url: 'one.php',
type: 'POST',
data: $('#myForm').serialize(),
success:function(data){
alert(data);
}
});