AJAX: Submitting a form without refreshing the page - javascript

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.

Related

Jquery: Submit a form without refreshing

Im trying to submit a form like this way:
<form id="myForm" action="http://example.com/somefile" method="POST">
...
...
...
<input type="submit" id="sendForm" value="send">
</form>
the action link its a webservice developed by another developer, so, when i submit the form, the webservice replies me with an URL (http://www.example.com/thanks), what i wanna do is to avoid this webservice reply, and in place, change the url of the redirect, is this possible?
Ive tried too do it with:
<script>
$("#sendForm").click(function () {
if (form_check_validation()) {
$("#myForm").submit();
window.location.replace("http://stackoverflow.com");
} else {
return false;
// event.preventDefault();
}
});
</script>
But its not working.
Thanks
NOTE: The webservice is in another server, so im having issues with cross-domain origin.
https://api.jquery.com/event.preventdefault/ Google is your friend, bud...........
Assuming this service allows cross origin and you don't want / need to move to a different page, why not use ajax?
You can simply create and ajax call using $.ajax.
see http://api.jquery.com/jquery.ajax/
Example:
$.ajax({
url : "POST_URL",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
// Handle server response
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle error
}
});
You can do it with Ajax. I also recommend that you bind a submit event listener to the form so that the submission works correctly also when pressing Enter.
$("#myForm").submit(function (event) {
if (form_check_validation()) {
form_submit(this);
} else {
// ...
}
event.preventDefault();
});
function form_submit (form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize()
});
}

how to trigger an AJAX request before or after an onsubmit

I have this form that when submitted I need it to trigger my ajax request, but the thing is that it has an onsubmit function within it and does my ajax request is not being triggered. So, I am wondering if there is a chance for me to do this. Also, I cannot do anything to the onsubmit and I cannot edit/delete it so that is why I added my own different onclick function. Code below:
my own js with ajax:
$(document).on('click','#Notes_subpanel_save_button',function (){
var assigned_id = $("#assigned_user_id").val();
$.ajax({
method: "POST",
url: "index.php?entryPoint=getsupportticket",
data: {notification_update: "update", assigned_id: assigned_id, ticket_record: QueryString.record},
success: function (data) {
alert(data);
}
});
});
HTML of the button:
<input title="Save" class="button" onclick="var _form = document.getElementById('form_SubpanelQuickCreate_Notes'); disableOnUnloadEditView(); _form.action.value='Save';if(check_form('form_SubpanelQuickCreate_Notes'))return SUGAR.subpanelUtils.inlineSave(_form.id, 'Notes_subpanel_save_button');return false;" type="submit" name="Notes_subpanel_save_button" id="Notes_subpanel_save_button" value="Save">
Here you go:
beforeSend: function () {
// YOUR CODE
}
Hope it will help you.
use ajaxStart and ajaxStop
$(".button").ajaxStart(function(){
$(this).button("disable");
}).ajaxStop(function(){
$(this).button("enable");
});
Have you tried:
$('#Notes_subpanel_save_button'). on('click', function() {
// make ajax call
}) ;

Submit form with jQuery (json encoded, ajax, parse original url/method)

I found a lot of questions about submitting forms without json and submitting forms statically specifying the url and method in the javascript code.
But all I am really looking for is a way to make all my forms send an ajax request in the exact way the form specified it in the first place with the only difference being that I want the data to be json encoded.
For instance a form like this
<form role="form" action="api/login" method="POST">
<input name="email" value="my#email.com" type="text"/>
<input name="password" value="mypassword" type="text"/>
<button type="submit">Login</button>
</form>
should automatically generate an ajax request like this when submitted:
POST /api/login HTTP/1.1
Content-type: application/json
{
"email": "my#email.com",
"password": "mypassword"
}
without me having to specify the method or url in the javascript code again.
And I don't want to write new code for every form I write. I'd simply like to have one snippet that automatically applies the above mentioned to any form.
You try something like this
$(document).on('submit','form',function(e){
e.preventDefault();
$form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: getObject($form.serializeArray()),
success: function (response) {
//Success Handler
}
});
return false;
});
function getObject(data) {
var paramObj = {};
$.each(data, function(_, kv) {
if (paramObj.hasOwnProperty(kv.name)) {
paramObj[kv.name] = $.makeArray(paramObj[kv.name]);
paramObj[kv.name].push(kv.value);
}
else {
paramObj[kv.name] = kv.value;
}
});
return paramObj;
}
$(function() {
$('form').submit(function(){
$.post(
$(this).attr('method'),
$('form').serialize(),
function (data) {
proccessmyData(data);
}
);
return false;
});
});
you can write function for success call back with proccessmyData(data)

Ajax after ajax request, submit form normal way

I have ajax request:
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
And php
.....
return $this->paypalController(params, etc...) // which should redirect to other page
.....
How should i make that ajax request if success, submit form normal way, because now if I redirect (at PHP) its only return response, but i need that this ajax request would handle php code as normal form submit (if success)
Dont suggest "window.location" please.
I would add a class to the form to test if your ajax has already occured. if it has just use the normal click funciton.
Something like:
$('form .submit').click(function(e) {
if (!$('form').hasClass('validated'))
{
e.preventDefault();
//Your code here
$.post(url, values, function(data) {
if (success)
{
$('form').addClass('validated');
$('form .submit').click();
}
});
}
}
Why don't you use a result variable that you update after a succesful AJAX request?
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
// avoid to execute the actual submit of the form if not succeded
var result = false;
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
async: false,
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
result = true;
}
}
});
return result;
});
</script>
I've had this issue before where I needed the form to submit to two places, one for tracking and another to the actual form action.
It only worked by submitting it programatically when you put the form.submit() behind a setTimeout. 500ms seems to have done the trick for me. I'm not sure why browsers have trouble submitting the form programatically when they are attempting to submit them traditionally, but this seems to sort it out.
setTimeout(function(){ $("#abc_from").submit(); }, 500);
One thing to keep in mind though once it submits, that's it for the page, it's gone. If you still want whatever processes are running on the page to run, you will need to set the target of the form to _blank so that it will submit in a new tab.

post multiple variables using jquery

I am trying to pass multiple variables from one php file to another via jquery but nothing is happening at all and i also can see that there is error in javascript code but i can not firgure out what is really wrong !
HTML Code :
<form id="edit" action="" method="POST">
<input type="text" name="name" value="wael">
<input type="text" name="phone" value="0103941454">
<input type="text" name="address" value="address">
<input type="submit" name="submit" value="Send">
</form>
<div style="display:none;" id="feedback"></div>
Jquery code :
$(document).ready(function(){
$('#edit').submit(function(){
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
};
});
});
});
PHP Code :
<?php
echo "Just testing functionality!":
?>
Please I need help to figure out what is wrong with this code.
In your JS code, you have to stop the form from being submitted, use e.preventDefault(), and there was a syntax error at the end of the success callback. Try this -
$(document).ready(function(){
$('#edit').submit(function(e){
e.preventDefault();
//^^^^^^^^^^^^^^^^^^^ Added this.
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
//^ There was a comma here. Remove it.
});
});
});
Now, with this, your code will execute without syntax errors, but your success callback will not called because, you have dataType:'json', so the return value from php will have to be valid json otherwise there will be a parsing error and your success callback will not be called.
To detect that, you need to use the error callback. This is a more complete AJAX call -
$(document).ready(function(){
$('#edit').submit(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
console.log("success");
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
},
error: function( jqXHR,textStatus,errorThrown ){
console.log(textStatus);
}
});
});
});
With your PHP code, which returns invalid JSON, the parsing error will be thrown.Try using json_encode() in your PHP if you want to return JSON data.For example, try this in your edit.php file -
<?php
header("Content-Type: application/json");
echo json_encode("Just testing functionality!");
?>
For posting form data it is good to use JQuery Form plugin which provide easy way to send data and receive response.
http://malsup.com/jquery/form/
Check this, and check examples where you will find easy and simple examples.
Also, using this plugin, you will have no need to fetch the form data in your jquery or use the jquery ajax function. The data will be directly posted to the form action by ajax when submitted.
Hope this will help.
add return false; to the end of your .submit() function to prevent the form from submitting
$('#edit').submit(function(){
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
});
return false; //here. otherwise the form will submit to its self not edit.php
});
try this code
$(document).ready(function(){
$('#edit').submit(function(event){
event.preventDefault();
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
});
});
});
I have made two changes here .
1. event.preventDefault();
for prevent the default action.
2. success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
instead of
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
};
apart from what Kamehameha and kanishka-panamaldeniya wrote down, you can achieve your goal in this way:
data: { name:wael ,phone:0103941454, address:address }
and
type:'post'
As said you need to call preventDeafult function on the event object; This function prevent the submit action to occur.
$('#edit').submit(function(event) {
event.preventDefault();
As a form of optimization you can also refer to $(this) inside your ajax call, instead to doing a new DOM traversing with $(#edit).serialize().
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$(this).serialize(), // <- modified here
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
});
and then yes, as #Kamehameha said, you need to return valid json from your edit.php, so
//edit.php
echo json_encode("Just testing functionality!");

Categories