Page refreshes on submit click with ajax - php

I have a small commenting system that I have modified and try implement into the site. It's in 'ajax'. When the jQuery with HTML is embedded into the page the commenting system works fine - i.e. when the user clicks on a submit button the code returns 'false', stops the page from refreshing and submits data. BUT when I implemented the code within my site and placed it in a seperate .js file the code for some reason doesn't work properly. I mean - the page after the onclick refreshes. Why is that so ? The code is not changed at all - when on its own, it works but not in the index.php site when implemented. I tried to change input type to 'button' and call a function from onclick - the page doesn't refresh but also doesn't insert the input..I'm running out of ideas as to why it is that so. Here's the code:
$(document).ready(function () {
$(".submit").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name=' + name + '&email=' + email + '&comment_area=' + comment_area;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if (name == '' || !emailReg.test(emailaddressVal) || comment == '') {
alert('Please enter valid data and type in message'); return false;
}
else {
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function (html) {
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
} return false;
});
});
//END
//COM LIST
//HTML / PHP
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#"
enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> &
nbsp;comment or <a href="index.php" id="cancel"
onmousedown="$('.slider').hide();$('#com_list').show();"><u>cancel</u></a>
</form>
</div>
//comments.php
if($_POST) {
$name=$_POST['name'];
$email=$_POST['email'];
$comment_area=$_POST['comment_area'];
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$insert = mysqli_query($connect,"INSERT INTO comments (name,email,comment,com_date)
VALUES ('$name','$email','$comment_area',curdate())");
}
////////////////
Thanks for any suggestions..

aha!
there is an error in your js:
in my console i'm getting "comment is not defined "
if(name=='' || !emailReg.test(emailaddressVal) || comment=='')
and earlier you have:
var comment_area = $("#comment_area").val(); //<--
change this to comment and it'll get past that at least.
EDIT: a little background. when firefox hits an error, sometimes it'll swallow it, and just stop running any javascript after that error, so your return false and or prevent default code isn't fire, so it's still going to post the form and refresh the page.

Change this line:
$(".submit").click(function () {
To this:
$("#comment_form").submit(function () {
The submit event gets triggered on the <form> element, not on the submit button.

Keep your damn code clean, so you can understand what you are cooking...
This will work for you:
$(document).ready(function(){
$("#comment_form").submit(function(e){
e.preventDefault(); // stop refresh
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name='+ name + '&email=' + email + '&comment_area=' + comment_area+'&submit_comment=true';
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(name=='' || !emailReg.test(emailaddressVal) || comment==''){
alert('Please enter valid data and type in message');
} else{
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function(html){
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
}
});
$('#cancel').click(function(e){
e.preventDefault();
$('.slider').hide();
$('#com_list').show();
});
});
Here is some more clean code...
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#" enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> comment or <u>cancel</u>
</form>
</div>
Here is some other clean and SECURE code
<?php
if(isset($_POST['submit_comment'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$comment_area = mysql_real_escape_string($_POST['comment_area']);
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$query = 'INSERT INTO comments (name,email,comment,com_date) '.
"VALUES ('$name','$email','$comment_area',CURDATE())";
$insert = mysqli_query($connect, $query);
}
?>

Related

jquery ajax contact form redirects to contact.php instead of catching php echo and executing sucess function

I have a contact form php+jquery+HTML.the form div is hidden in index.HTML,until contact button is presses.Jquery works,Ajax call posts needed data to php,which echoes a response.The problem is when php echoes,instead of remaining on same page without refreshing,browser redirects to contact.php,where the echo is showed correctly.I think the Ajax part won't catch the response from server,although syntax is the same in all tutorials.please assist.
html part:
HTML
<div id = 'contact_form'>
<div id = 'result'></div>
<form id="contactform" action="js/contact.php" method="POST" enctype="multipart/form-data">
<div class="row">
<input id="name" class="input" name="name" type="text" required = 'true' value="" size="30" placeholder='Nome'/>
</div>
<div class="row">
<input id="email" class="input" name="email" type="text" required = 'true' value="" size="30" placeholder = 'Email'/>
</div>
<div class="row">
<textarea id="message" class="input" name="message" rows="7" cols="50" required = 'true' placeholder = 'Messagio'></textarea>
</div>
<input id="submit_button" class = 'myButton' type="submit" value="Manda messagio" />
</form>
</div>
</div>
JS
$('#submit_btn').click(function(){
var user_name = $("input#name").val();
if (user_name == "") {
$("input#name").focus().addClass('active');
return false;
}
var user_email = $("input#email").val();
if (!$("input#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("input#email").focus().addClass('active');
return false;
}
var msg = $("textarea#message").val();
if (message == "") {
$("textarea#message").focus().addClass('active');
return false;
}
var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function(d) {
console.log(d);
}
});
return false;
});
PHP
<?php
$toEmail = "x#gmail.com";
$subject = "dal tuo sito ";
$mailHeaders = "From: " . $_POST["name"] . "<". $_POST["email"] .">\r\n";
if(mail($toEmail,$subject,$_POST["message"], $mailHeaders)) {
echo "Mail Sent";
} else {
echo "Problem in Sending Mail";
}
?>
If you want to keep the same button you can change your js.
$('#submit_btn').click(function(e){
e.preventDefault();
//YOUR CODE HERE
}
Because you used a submit type input, I recommend you change the submit input for a link like button. And also remove the action attr from the form:
HTML
Send
JS
<script>
$('#btn').on("click", function(){
//Your ajax here
//var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: {name: user_name, email: user_email, message: msg}
}).done(function(response){
console.log(response);
});
});
</script>

Php Form Submit without Refresh - Ajax not working

I am trying to get get my form to submit without having the page refreshing everytime
However, when I insert the ajax and place the php into a new file the form doesnt submit and I dont understand why?
Any advice would be appreicated!
PHP
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
//Post data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
//mail settings
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
$header = "From: $email";
if($_POST) {
if($name == '' || $email == '' || $phone == '' || $message == '') {
echo $feedback = "<font color='red'> *Please Fill in All Fields!";
}
else {
mail($to, $subject, $body, $header);
echo $feedback = "<font color='green'> *Message sent! You will receive a reply shortly!";
}
}
}
else{
echo $feedback = "<font color='red'> Missing Params";
}
?>
AJAX
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#submitBtn").click(function( event ) {
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>
HTML CODE HERE: http://www.codeply.com/go/e3jAo1WrPl
The .bind() function may be the way to go with this form, since it binds the action of clicking the button to the event handler.
It also may be beneficial to have the event.preventDefault() before your ajax call.
$(document).ready(function(){
$("#submitBtn").bind([boundElement],function( event ) {
event.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
return true;
});
});
I would recommend double-checking the syntax for the bound element in the .bind() parameters. It is single quote marks for referring to a named form element
Example HTML:
This might help you with your problem:
$(document).ready(function() {
$("#contact").submit(function(event) {
event.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
message = $('#message').val(),
occasion = $('#occasion').val(),
dataString = $(this).serialize();
$.ajax({
url: 'php.php',
type: 'post',
data: dataString,
})
.done( function( html ) {
$( '#feedback' ).html( html );
})
.fail( function( response ) {
console.log( response );
});
});
});
Firs of all, you have the form and the submit button, so when you press the button, the event 'submit' is triggered, so you prevent the event to be fired, then you do your coding, the variables, but I cannot understand why you declare all those, if you don't use them, but that's up to you.
Here is a suggestion with using a button in stead of a submit. I commented out the preventDefault, because it is unnecessary in this case -- we are not actually submitting the form. This gives us more control.
The request is submitted. In this case, it obviously fails. In your case, whether or not it fails is going to depend on what you have going on server side.
http://plnkr.co/edit/txuxaFUkgFq9SFDcqUdp
<form action="http://www.yahoo.com" id="contactForm" method="get" target="_blank">
<div class="innerForm">
<label for="name">Name:</label>
<input id="name" name="name" type="text" />
<label for="phone">Phone:</label>
<input id="phone" name="phone" type="text" />
<label for="email">Email:</label>
<input id="email" name="email" type="text" />
<label for="occasion">Occasion:</label>
<input id="occasion" type="text" name="occasion" />
<label id="messageLabel" for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button id="test">test</button>
<!--input type="submit" value="Submit" id="submitBtn" name="submit" onclick="return chk();"/ -->
</div>
<div id="feedback"></div>
</form>
$(document).ready(function(){
$("#test").click(function (event) {
//values
alert("test clicked");
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var message = document.getElementById('message').value;
var occasion = document.getElementById('occasion').value;
var dataString = $("#contactForm").serialize();
$.ajax({
type: "get",
url: "http://www.yahoo.com",
data: dataString,
success: function (html) {
alert("success");
//$('#feedback').html(html);
},
error: function(result){
alert("failure");
}
});
//event.preventDefault();
});
});

Insert records to mysql database with php using Ajax

How to do coding of this Code With Using Ajax.Please Help.
I am Bignner here and i have written this code it's working but i want to use with ajax this because don't want to reload the page...?
PHP File
//Code For Making Form And getting Data…..
<html>
<body>
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form action="Form_Data.php" method="post">
ID: <input type="text" name="ID"><br><br>
NAME: <input type="text" name="NAME"><br><br>
PASSWORD: <input type="text" name="PASSWORD"><br><br>
CREDITS: <input type="text" name="CREDITS"><br><br>
E_mail: <input type="text" name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" name="MODIFIED_ON"><br><br>
<input type="submit">
</form>
</body>
</html>
//code for taking data from form data.
<html>
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
mysql_close($conn);
?>
</html>
I have Tried Yet ... Is Blewo...
file for html and ajax
<html>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</HEAD>
<body>
<div id="status_text">
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form onsubmit="return false" method="post">
ID: <input type="text" id="ID" name="ID"><br><br>
NAME: <input type="text" id="NMAE" name="NAME"><br><br>
PASSWORD: <input type="text" id= "PASSWORD"name="PASSWORD"><br><br>
CREDITS: <input type="text" Id= "CREDITS"name="CREDITS"><br><br>
Email_ID: <input type="text" id="Email_ID"name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" id="CREATED_ON" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" id="MODIFIED_ON" name="MODIFIED_ON"><br><br>
<input type="submit" id="btn_submit" name="submit" value="Send">
</div>
<script>
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
//make the postdata
var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&REDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
});
$.ajax({
url : "Form_Data.php",
type: "POST",
data : postData,
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
</script>
</form>
</body>
</div>
</html>
code for query...
<html>
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
mysql_close($conn);
?>
</html>
I have Solved It ... How To Use Ajax and MYSQL...
PHP CODE
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
// $retval=mysql_query($query,$conn);
if ($query_run)
{
echo 'It is working';
}
mysql_close($conn);
?>
HTML FILE....
<html>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</HEAD>
<body>
<div id="status_text">
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
ID: <input type="text" id="ID" name="ID"><br><br>
NAME: <input type="text" id="NAME" name="NAME"><br><br>
PASSWORD: <input type="text" id= "PASSWORD"name="PASSWORD"><br><br>
CREDITS: <input type="text" Id= "CREDITS"name="CREDITS"><br><br>
Email_ID: <input type="text" id="EMAIL_ID"name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" id="CREATED_ON" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" id="MODIFIED_ON" name="MODIFIED_ON"><br><br>
<input type="submit" id="btn_submit" name="submit" value="Send"/>
</div>
<script>
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
} }
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
// make the postdata
// var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&CREDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
// alert(postData);
var myData={"ID":ID,"NAME":NAME,"PASSWORD":PASSWORD,"CREDITS":CREDITS,"EMAIL_ID":EMAIL_ID,"CREATED_ON":CREATED_ON,"MODIFIED_ON":MODIFIED_ON};
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "Form_Data.php",
type: "POST",
data : myData,
success: function(data,status,xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
});
</script>
</body>
</div>
</html>
change your script because your ajax was outside the click function
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
//make the postdata
var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&REDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "Form_Data.php",
type: "POST",
data : postData,
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
});
</script>
and change your php code to this
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
if(isset($_POST['NAME'])){
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
}
mysql_close($conn);
?>
In this code I'm just submitting your two input fields, the rest you can add by yourself. Try this:
<html>
<body>
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form action="Form_Data.php" method="post">
NAME: <input id="name" type="text" name="NAME"><br><br>
PASSWORD: <input id="password" type="text" name="PASSWORD"><br><br>
<input type="submit" id="submit">
</form>
</body>
</html>
$("#submit").click(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "your_php_path.php",
data: 'name=' + name+ '&password=' + password,
success: function(result) {
alert(result);
}
});
});

jquery ajax loaded form submit sets serialized data into url

Im making some web appication which loads pages without refresching te page. This all works great but now i have a form on one of these pages. I want to submit the form without the page to refresh. But when i submit the form after i loaded it with ajax the url in the browser will change from
localhost/documents/projects/test/
to
localhost.documents/projects/test/?form_type=register&Username=&first_name=&surname_prefix=&surname=&surname=&email=
When i just put the form html in my index.php and submit it there it works fine.
I hope someone can tell me what im doing wrong and how to fix it.
part of index.php
<div class="message"></div>
<div id="content">
<div id="page">
<div class="form_container">
<form id="form">
<input type="hidden" name="form_type" value="register" />
<input class="type_text" type="text" name="username" maxlength="20" placeholder="username" />
<input class="type_text" type="text" name="first_name" maxlength="50" placeholder="First Name" />
<input class="type_text" type="text" name="surname_prefix" maxlength="20" placeholder="Surname Prefix" />
<input class="type_text" type="text" name="surname" maxlength="50" placeholder="Surname" />
<label class="label" for="birth_date">dd-mm-jjjj</label>
<input id="birth_date" class="type_text" type="text" name="birth_date" maxlength="10" placeholder="Birth Date" />
<input class="type_text" type="text" name="email" placeholder="Email Address" />
<input class="type_submit" type="submit" value="Register" />
</form>
</div>
</div>
pageHandler.js
$(document).ready(function() {
var request;
//page handler
//pageRequest('home');
$('.click').click(function(event) {
var temp = $(this).attr('id');
var pages = ['home','register'];
if($.inArray(temp, pages) !== -1) {
pageRequest(temp);
//$('.message').html(temp);
}
event.preventDefault();
});
function pageRequest(temp) {
var page = $('#page');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
type: "POST",
url: "core/posts.php",
data: 'temp=' + temp
});
request.done(function(data) {
page.fadeOut(function() {
page.html('');
page.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
page.fadeOut(function() {
page.html('');
page.html(textStatus).fadeIn();
});
});
}
//form handler
$('#page').delegate( "#form", "submit", function(event) {
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
formRequest(serializedData);
event.preventDefault();
});
function formRequest(values) {
var message = $('.message');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
url: "core/posts.php",
type: "POST",
data: values
});
request.done(function(data) {
message.fadeOut(function() {
message.html('');
message.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
message.fadeOut(function() {
message.html('');
message.html(textStatus).fadeIn();
});
});
}
});
posts.php
If(isset($_POST['temp'])) {
$temp = $_POST['temp'];
$url = '../content/templates/'.$temp.'.html';
if(file_exists($url)) {
$html = file_get_contents($url);
echo $html;
}
else {
echo 'Sorry, couldn\'t find the page.';
}
}
//form handler
if(isset($_POST['form_type'])) {
require_once('../admin/config/database.functions.php');
$function = new myDBFunctions();
switch($_POST['form_type']) {
case 'register' :
$username = $_POST['username'];
$firstname = $_POST['first_name'];
$surnamep = $_POST['surname_prefix'];
$surname = $_POST['surname'];
$birthdate = $_POST['birth_date'];
$email = $_POST['email'];
echo 'Thanks for your registration';
break;
case 'login' :
echo 'login';
break;
case 'password_recovery' :
echo 'password recovery';
break;
}
}
I have found the problem but not why it occured. I had a $_POST['username'] in my posts.php file while the the name of the html input field was Username. I have changed this and now the url in the browser doesn't change anymore. I'm happy I've found the problem but i still dont get why the data send by ajax would appair in the url.
"I want to submit the form without the page to refresh"
There are a few ways to do this, I think the easiest is to intercept and stop the form from actually submitting like a regular HTML form and instead make an ajax call with the data in the form fields.
To do this, you will need to intercept the submit event of the form, get the values of all the inputs in the form and make an ajax call with the data to the server:
<form id="myForm">
....
</form>
<script>
$('#form').on("submit", function(event) {
// stop the form from submitting
event.preventDefault();
// get data in the inputs of the form
var data = {};
var $inputs = $('#form').children("input, select, textarea");
inputs.each(function($element){
data[$element.attr('name')] = $element.val();
});
// submit data to the backend
request = $.ajax({
type: "POST",
url: "",
data: data
});
});
</scipt>

Send single input with ajax/jquery/php

I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');

Categories