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

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

Related

Multiple jQuery AJAX calls conflicts?

I am trying to create a simple shopping cart using AJAX and PHP.
Everything works as it should BUT 1 thing doesn't work all the time and it seems that it fails to execute. (it works 3 times out of 5).
to explain this issue please take a look at the code bellow:
jQuery(document).ready(function() {
//////////////////////LETS RUN OUR ADD TO CART FEATURE USING AJAX //////////////
$(function(){
$('.form1').on('submit', function(e){
$( "#preloader" ).fadeIn( 850 );
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: $(this).attr('action'),
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$( "#preloader" ).fadeOut( 850 );
}
});
});
});
//////////////////////LETS RUN LOAD THE cart-header.php ON PAGE LOAD USING AJAX //////////////
$(document).ready(function () {
function load1() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data2) {
$('#headerCart').html($(data2));
//setTimeout(load2, 500);
}
});
}
load1();
});
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS RUN OUR DELETE FROM CART FEATURE USING AJAX //////////////
$(document).on('submit', '.delForm', function(dleItem){
// prevent native form submission here
dleItem.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS GET THE QUANTITY OF CURRENT ITEMS ADDED IN THE CART USING AJAX/////////////
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart.php",
//url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data) {
$('.item_count').html($(data).find('#total').text());
//$('#headerCart').html($(data));
setTimeout(load, 1000);
}
});
}
load();
});
I have commented the code so you can see the parts of the code and what they do.
the issue is this part:
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
As I mentioned above, this code works fine but it only works when it wants to as if it has mind of its own!
could someone please advise on this issue?
Thanks in advance.

Why data is being submitted twice through ajax?

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

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.

Form validation with jQuery and php

I have a form which I'm validating using jQuery and php. So basically if the php echoes "input must be filled" the jQuery should put a red border around that input, but the thing works only after submitting the form two times.
I explain: if I submit with input unfilled the php file echoes "input must be filled", but only if I press again the submit button - the input goes red.
$("form#maj_email").submit(function(){
var _data = $(this).serialize()
$.ajax({
type: 'POST',
url: 'validation_profil.php?var=maj_email',
beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localhost/www3/images/ajax_loader.gif')"})
$("div#error_maj_email").hide()
if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
$("form#maj_email input:[name=email]").css({border:"1px solid red"})
}
},
data:_data,
cache: false,
success: function(html){
$('div#error_maj_email').html(html)
$("div#ajax_icon_maj_email").css({background:"url('none')"})
$("div#error_maj_email").fadeIn()
}
})
})
It looks like the form is being submitted via the form instead of your ajax call. You need to prevent this behavior for this to work:
$("form#maj_email").submit(function(e){
var _data= $(this).serialize();
$.ajax({
type: 'POST',
url: 'validation_profil.php?var=maj_email',
beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localhost/www3/images/ajax_loader.gif')"})
$("div#error_maj_email").hide()
if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
$("form#maj_email input:[name=email]").css({border:"1px solid red"})
}
},
data:_data,
cache: false,
success: function(html){
$('div#error_maj_email').html(html)
$("div#ajax_icon_maj_email").css({background:"url('none')"})
$("div#error_maj_email").fadeIn()
}
});
e.preventDefault();
return false;
})

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