Why data is being submitted twice through ajax? - php

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);
});

Related

Ajax Validation intrupt the form submit on form submit event

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.

Old values coming in POST from Jquery Modal Box

So I am messing with very stupid issue,There is normal HTML form which I am opening in Modal Box for updating the values.When I change the values of any Text Box and click on button for Ajax Call, there is Old values coming in POST instead of changed value.
For example if there is Value 5 and i changed it to 10 and fire Ajax but in POST data there is still 5.I am using on for getting current values.
Here is part of my HTML code :
<form action="" id="UpdateBind_data">
<input type="text" id="weightage" name="weightage" value="<?php echo $mapping_data->weightage; ?>">
<button type="button" class="btn btn-primary UpdateBind">Update</button>
</form>
Jquery :
$("body").on("click", ".UpdateBind", function() {
var Datastring = $("#UpdateBind_data").serialize();// Retrive the old values not the changed ones.
$.ajax({
type: "POST",
url: updatedbindlink,
data: Datastring,
datatype: "json",
cache: false,
success: function(response) {
if(response.res)
{
alert("Mapping data successfully Inserted");
}
else
{
//error
}
return false;
}
});
});
Thanks in advance.
Maybe it because your forms submits before executing the JQuery bind? Try this:
$("body").on("click", ".UpdateBind", function(e) {
e.preventDefault();
var Datastring = $("#UpdateBind_data").serialize();// Retrive the old values not the changed ones.
$.ajax({
type: "POST",
url: updatedbindlink,
data: Datastring,
datatype: "json",
cache: false,
success: function(response) {
if(response.res)
{
alert("Mapping data successfully Inserted");
}
else
{
//error
}
return false;
}
});
});

Ajax POST form data is send as GET request

I am creating a chat system. I am sending a form data through ajax method in jquery. My first problem is ajax method is not sending data to proccess.php and page goes to redirect to its self.
<div id="chatOutput"></div>
<form id="myform">
<textarea id="chatInput" name="chatInput"></textarea>
<input type="submit" id="send" name="send" value="send" />
</form>
and script is :
$('#send').click(function () {
$('#myform').submit();
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function () {
alert("Submitted!"); // for testing
}
});
return false;
});
but script is not working and page goes to refresh and i see the variables and its values in the address bar like get method.
if this problem goes to solve, process.php will create a chat.txt and append data from #chatInput into it. and then will append chat.txt 's data to #chatOutput.
After appending data, div#chatOutput 's size goes to change. I want to fixed/specified width and height of this div. After the fixing size, how to scroll to bottom to see the last chatting?
The problem is here:
$('#myform').submit();
The simulates the "Submit" button click event
You can just do :
$('#myform').submit(function() {
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function() {
alert("Submitted!"); // for testing
}
});
return false;
});
You used $('#myform').submit(); which just submits the form in the normal way and thus ignoring the ajax etc after that.
Also, put this code either after the form itself or within $(function(){ ... });
EDIT
You had a syntax error. Make sure u have e.preventDefault(); as the first thing in your event click function. Then the default action will be prevented even when an error occurs later on.
$('#send').click( function(e) {
e.preventDefault(); //disable default action
$('#myform').submit();
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function() {
alert("Submitted!"); // for testing
}
});
});
return false; //return something
});
Remove the line:
$('#myform').submit();
It is submitting the form before your ajax call is made.

Why is my page refreshed when I submit a post by Ajax?

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();
}
});
});

Trouble with jQuery form submit

I am at a loss here with some simple jQuery. I have the following code in a separate file:
$(document).ready(function(){
//$("#trackit").click(function() {
$.ajax({
type: "POST",
url: 'include/trackit.php',
data: "trackingNum=123456",
success: function(data) {
alert(data);
}
});
//});
});
That works just fine, on page load it returns the expected data to the alert window.
But, if I remove the comments from this line:
$("#trackit").click(function() {
to capture the form's submit button, I get no return data.
Here is the abbreviated form info:
<form action="<?php htmlentities($_SERVER['PHP_SELF']);?>" name="tForm" id="tForm" method="post">
<button type="submit" class="buttonTracking" id="trackit" name="trackit">Track It!</button>
</form>
Am I just overlooking some simple error here?
Correct working code would be this:
$(document).ready(function(){
$("#trackit").click(function() {
$.ajax({
type: "POST",
url: 'include/trackit.php',
data: "trackingNum=123456",
success: function(data) {
alert(data);
}
});
return false; // to cancel form submission and subsequent page refresh
});
});
I'd say it's because the #trackit button is also a submit button. The click action is executing your javascript AND submitting the form. You need to change the code to:
$(document).ready(function(){
$("#trackit").click(function() {
$.ajax({
type: "POST",
url: 'include/trackit.php',
data: "trackingNum=123456",
success: function(data) {
alert(data);
}
});
return false;
});
});

Categories