my ajax keeps refreshing the whole page instead of the div - javascript

I have an ajax form and I want to reload the div instead of the whole page, but it isn't working.
This is my handling.js:
$(document).ready(function(){
$('#guideForm').submit(function(){
$.ajax({
type: 'POST',
url: '../includes/handling.php',
data: $(this).serialize()
})
.done(function(data){
$('#guide').load(document.URL + ' #guide');
})
return false;
});
});
this is my handling.php:
if ($_POST['guide']) {
$settings->addGuide($_POST['guide']);
}
EDIT:
Formcodes:
<div class="col-md-4">
<h2>test title</h2>
<p class="guids">This is a test text.</p>
<form method="post" id="guideForm">
<input name="guide" value="1" style="positon:absolute; display:none;">
<button class="btn btn-primary">Got it!</button>
</form>
</div>
Can someone help me to figure out what I'm doing wrong?

You should try e.preventDefault()
$('#guideForm').submit(function(e){
e.preventDefault(); // added this line and an argument 'e' to the function
$.ajax({
type: 'POST',
url: '../includes/handling.php',
data: $(this).serialize()
})
.done(function(data){
$('#guide').load(document.URL + ' #guide');
})
return false;
});

Use e.preventDefault();
$(document).ready(function(){
$('#guideForm').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../includes/handling.php',
data: $(this).serialize()
})
.done(function(data){
$('#guide').load(document.URL + ' #guide');
})
return false;
});
});

$('#guideForm').submit()
The above jquery statement would by default submit the fold which would essentially reload the code. If you do not want this to happen,
add the following
event.preventDefault();
This would prevent the submit of the form and execute the code in the function

I think there's an error in your js that's why it doesn't execute as expected, have you checked if you get any error? Maybe it's because you don't have a termination on your $.ajax function.. try adding ";" terminator.
$(document).ready(function(){
$('#guideForm').submit(function(){
$.ajax({
type: 'POST',
url: '../includes/handling.php',
data: $(this).serialize()
})
.done(function(data){
$('#guide').load(document.URL + ' #guide');
});
return false;
});
});

To stop the page from submitting you need to prevent the default behavior of the event i.e. to submit the form.
Your page keeps reloading because after your request DOM submits the form. And, as default behavior, Your form submits itself on the same page as you haven't specified a action param.
So, there are multiple ways of doing this.
i). Stop the JS event from propagating by using the method preventDefault() of event object.
Like this:
$(document).ready(function(){
$('#guideForm').submit(function(e){
e.preventDefault(); //stop default behaviour
$.ajax({
type: 'POST',
url: '../includes/handling.php',
data: $(this).serialize()
})
.done(function(data){
$('#guide').load(document.URL + ' #guide');
})
return false;
});
});
This is the most official way of doing this.
ii). You can change your submit button/input to a simple button and bind the ajax with onClick event.
Like this:
$(document).ready(function(){
$('#fakeSubmitButton').click(function(e){
$.ajax({
type: 'POST',
url: '../includes/handling.php',
data: $(this).serialize()
})
.done(function(data){
$('#guide').load(document.URL + ' #guide');
})
return false;
});
});
iii). You can define javascript:void(0) as your form's action attribute. This will automatically prevent form from submitting.
iv). By returning false from the event handler. Which you are currently doing. It is strange it is not working as jQuery doc itself says:
we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
Maybe the following post can help you:
jQuery - Form still submits with return false
Also check the answer of Chen-Tsu Lin in the above post. It is given a link for when you should not use return false.
Hope this helps.

Use e.preventDefault(); to stop the default behavior of submit.
$(document).ready(function(){
$('#guideForm').submit(function(e){
e.preventDefault(); //stop default behaviour
$.ajax({
type: 'POST',
url: '../includes/handling.php',
data: $(this).serialize()
})
.done(function(data){
$('#guide').load(document.URL + ' #guide');
})
return false;
});
});

Related

Cannot get $_POST('input') using jQuery .submit()

I was trying to upload a form using jQuery's submit() and success in redirect the page to uploadAll.php, but when I was trying to get the input array using $_POST['inputname'] I can not obtain the value.
I was trying to use serialize() but I get confused in where I should put my PHP page reference.
<form id="regForm" action="uploadAll.php" method="post" enctype="multipart/form-data">
//some inputs and a hidden input here
</form>
document.getElementById("regForm").submit(function() {
var inputValues = $(this).serialize();
$.ajax({
url: "uploadAll.php",
type: "POST",
data: inputValues
}).done(function(data) {
alert(data);
});
});
return false;
Can I just submit without using serialize()? It seems my serialize does not work. Any help is appreciated
trust me, your code is wrong..
try use this code instead:
$("#regForm").on('submit', function(e) {
e.preventDefault();
var inputValues = $(this).serialize();
$.ajax({
url: "uploadAll.php",
type: "POST",
data: inputValues
}).done(function(data) {
alert(data);
});
});

Form submitting to wrong function when changing class dynamically

I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo

AJAX: Submitting a form without refreshing the page

I have a form similar to the following:
<form method="post" action="mail.php" id="myForm">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit">
</form>
I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.
I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):
$.post('mail.php', $('#myForm').serialize());
If possible, I would like to get help implementing this using AJAX,
Many thanks in advance
You need to prevent the default action (the actual submit).
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
You haven't provided your full code, but it sounds like the problem is because you are performing the $.post() on submit of the form, but not stopping the default behaviour. Try this:
$('#myForm').submit(function(e) {
e.preventDefault();
$.post('mail.php', $('#myForm').serialize());
});
/**
* it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
* for explanation why, try googling event delegation.
*/
//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
/*
* do ajax logic -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
* $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
* i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
*/
//example using post method
$.post('mail.php', $("#myForm").serialize(), function(response){
alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
})
//example using ajax method
$.ajax({
url:'mail.php',
type:'POST',
data: $("#myForm").serialize(),
dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
success: function(response){
alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
},
error: function(response){
//as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
alert("something went wrong");
}
})
//preventing the default behavior when the form is submit by
return false;
//or
event.preventDefault();
})
try this:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:
var form = document.getElementById('myForm');
var params = {
method: 'post',
body: new FormData(form),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
};
form.addEventListener('submit', function (e) {
window.fetch('mail.php', params).then(function (response) {
console.log(response.text());
});
e.preventDefault();
});
try this..
<form method="post" action="mail.php" id="myForm" onsubmit="return false;">
OR
add
e.preventDefault(); in your click function
$(#yourselector).click(function(e){
$.post('mail.php', $(this).serialize());
e.preventDefault();
})
You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.
By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).
If don't want this default action use preventDefault() method.
If you are using other than submit, no need to prevent default.
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'save.asmx/saveData',
dataType: 'json',
contentType:"application/json;charset=utf-8",
data: $('form').serialize(),
async:false,
success: function() {
alert("success");
}
error: function(request,error) {
console.log("error");
}
Take a look at the JQuery Post documentation. It should help you out.

.ajax() refreshes the page after ENTER is hit

I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>
This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.
Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});
Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.

Jquery help repeated ajax call

When I submit my form, a repeated ajax call is made it never stop.
Here is my Jquery for the ajax call on form submit:
$('form#formgo').submit(function(e) {
e.preventDefault();
$('#comparecontent').empty().html(
'<p style="text-align:center;">' +
'<img src="../images/ajax.gif" /></p>');
var form = $(this).closest('form');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(msg){
$('#comparecontent').html(msg);
}
});
return false;
});
In your ajax call, try specifying a timeout for the request:
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
timeout: 3000, // time in milliseconds
success:function(msg){
$('#comparecontent').html(msg);
}
});
see the .ajax() documentation for more info on available params http://api.jquery.com/jQuery.ajax/
It seems that something is triggering submit.
Try event.stopPropagation()
$('form#formgo').submit(function(e) {
e.preventDefault();
e.stopPropagation();
...
Also check if an onchange event is bound to elements with id comparecontent.

Categories