Submit without leaving page - javascript

My form
<form id="reservationForm" action="sendmail.php" method="post">
...
.
.
.
.
<input type="image" src="images/res-button.png" alt="Submit" class="submit" width="251" height="51px">
My javascript
$("#reservationForm").submit(function () {
e.preventDefault();
var $form = $(this);
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: $('#form').serialize(),
success: function(response) {
alert("Success");
$('#reservationForm').fadeOut("slow");
}
});
return false;
});
i don't want to run any validation because i have user 'required' in all types. i just want to send data to my php while staying at the same contact form. but this only load my php file and send the e-mail. looks like it dosen't run my javascript. please help

You haven't defined the event argument in the callback. Change this line as follows and it should work:
$("#reservationForm").submit(function (e) {
...
EDIT: BTW: The .submit event handler of jQuery short hand is deprecated. You should be using .on('submit', ...instead.

Related

on form submit using ajax and getting value from php function

I have a form calling submitting as follow
<form action="" method="post" id="member_form" onsubmit="return json_add('member','<?php echo ($admin->getnew_id()); ?>','0','slider_form');">
The problem I have is to get the $new_id before submitting the form from another function class.
this is not working
It keep running the funtion getnew_id() and generate the ID before it is saved
I need the process as follow.
Form Open
User complete form
onsubmit it need to do follow.
a. get new id = $new_d
b. then do
return json_add('member','','0','slider_form');">
I tried the following but dont work
$("form").submit(function(){
$.ajax({
url:"lastid.php",
type:'POST',
success:function(response) {
var $new_id = $.trim(response);
return json_add('member-add',$new_id,'0','slider_form');
alert("Submitted");
}
});
The problem seems to be in the third step.
What you should do is prevent the form from submitting and handle it in ajax.
you need onsubmit="return false" to prevent the form from submitting
Next, handle the submission in ajax
$("form#member_form").submit(function(){
$.ajax({
url: "lastid.php",
type: "POST",
data: { // this is where your form's datas are
"json": json_add('member-add',$new_id,'0','slider_form'),
"key": $("form#member_form").serialize()
},
success: function(response) {
var $new_id = $.trim(response);
alert("Submitted");
// alerting here makes more sense
}
// return json_add('member-add',$new_id,'0','slider_form');
// returning here do nothing!
});
You can read more about using ajax in jQuery here

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!");

Getting data from form.serializaArray()

i need help..why does my code not working?what is the proper way to get the data from a form.serialize? mines not working.. also am doing it right when passing it to php? also my php code looks awful and does not look like a good oop
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="" id="title_val"/>
post topic
</form>
<div id="test">
</div>
Javascript
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'get',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
Php
<?php
class test{
public function test2($val){
return $val;
}
}
$test = new test();
echo $test->test2($_POST['title_val']);
?>
OUTPUT
You're telling your ajax call to send the variables as GET variables, then trying to access them with the $_POST hyperglobal. Change GET to POST:
type:'post',
Also, it should be noted that you are binding your ajax call to the click on your submit button, so your form will still be posting. You should bind on the form's submit function instead and use preventDefault to prevent the form posting.
$('#frm').submit(function(e) {
e.preventDefault(); // stop form processing normally
$.ajax({
url: 'topic.php',
type: 'post',
data: $(this).serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});

submitting a form via AJAX

I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});

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.

Categories