Submit a Form without Reloading - php

I got this simple form page that will submit the last name and first name of a user
<?php
include 'dbconnect.php';
if (isset($_POST['lname']) && isset($_POST['fname'])){
$ln = $_POST['lname'];
$fn = $_POST['fname'];
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
$result = mysql_query($sql);
}
?>
<!DOCTYPE html>
<html>
<head>
<script >var frm = $('#nameFrm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</head>
<body>
<form id = "nameFrm" name = "frmName" method = "POST" >
Last Name : <input type = "text" name = "lname"><br />
First Name: <input type = "text" name = "fname"><br />
<input type = "submit" value = "submit" name= "subbtn" >
</form>
</body>
my script does not work that script is suppose to avoid the page from reloading and i am pretty sure that it is reloading everytime the page is submitted
also when i seperate the php code
if (isset($_POST['lname']) && isset($_POST['fname'])){
$ln = $_POST['lname'];
$fn = $_POST['fname'];
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
$result = mysql_query($sql);
}
it still redirects it to the new php file

What to do is create a new file called requests.php / or whatever
in this file have a switch statement..
requests.php
<?php
if(isset($_POST['action']) && ($_POST['action']!='')){
$action = $_POST['action'];
switch($action){
case "submitForm" :
include 'dbconnect.php';
if ( (isset($_POST['lname'])) && (isset($_POST['fname'])) ){
$ln = mysql_real_escape_string($_POST['lname']);
$fn = mysql_real_escape_string($_POST['fname']);
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
mysql_query($sql);
echo "New values updated: ".$fn." ".$ln;
}
break;
}
}
?>
Then copy this crude html..
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadImg = jQuery('#loadingImage');
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&fname='+fname+'&lname='+lname,
url: 'requests.php',
beforeSend: function(){
loadImg.show();
},
complete: function(){
loadImg.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
</head>
<body>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
Last Name : <input type="text" id="lname" name="lname"><br />
First Name: <input type="text" id="fname" name="fname"><br />
<input type = "submit" value = "submit" name= "subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
<img src="http://craigmaslowski.com/images/activity-indicator.gif" />
</div>
<div id="results"></div>
</body>
What its doing is when you click the submit button, the jquery will fire,
it will grab the 2 values from fname & lname (these have been given an id)
the 2 values will then be added to the jquery.ajax URL, this url will be the form action url, which for this is requests.php
in requests.php the 2 post values are passed over and processed, the output will be sent back to the original page, were the data will be passed to the div#results, to show the output....
Also I've added a few other things, like a loading image, for both the beforeSend call and Complete,
**ALSO,
please be-aware that you should really think about moving from using the mysql_query syntax to mysqli_query.. have a look at MackieeE's comment!
**
Have a play around with it.. hopefully its what your looking for..
Good luck..
Marty

The browser executes the javascript BEFORE knowing the form.
Put the javascript AFTER the form or into a $(window).load():
<script>
$( window ).load(function() {
var frm = $('#nameFrm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
});
</script>

Related

Why form is fetching all data when i dont give any input?

This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.

how to insert data with ajax and php without page refresh

I real need your help since I'm a beginner in php and Ajax. My problem is that, I can not send data in the database via my appended form in post.php, also when the button of id #reply clicked it sends empty data to database by refreshing the page. When the reply link is pressed I only get the Result of reply link to be shown without other information (name and comment). I need your help to make my appanded form to be able to add/send data to the database without refreshing the page, I also need to disable the form from index.php to make replies when the reply button / link is pressed. Thank you.
post.php
<?php include("config.php"); //inserting
$action=$_POST["action"];
if($action=="addcomment"){
$author = $_POST['name'];
$comment_body = $_POST['comment_body'];
$parent_id = $_POST['parent_id'];
$q = "INSERT INTO nested (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysqli_query($conn, $q);
if(mysqli_affected_rows($conn)==1) { header("location:index.php");}
else { }
}
// showing data
error_reporting( ~E_NOTICE );
function getComments($conn, $row) {
$action=$_POST["action"];
if($action=="showcomment"){ $id = $row['id'];
echo "<li class='comment'><div class='aut'>".$row['author']."</div><div class='comment-body'>".$row['comment']."</div>";
echo "<a href='#comment_fo' class='reply' id='".$row['id']."'>Reply</a>";
$result = mysqli_query($conn, "SELECT * FROM `nested` WHERE parent_id = '$id' ORDER BY `id` DESC");
}
if(mysqli_num_rows($result)>0) { echo "<ul>";
while($row = mysqli_fetch_assoc($result)) { getComments($conn,$row); }
echo "</ul>"; } echo "</li>";
}
if($action=="showcomment"){
$q = "SELECT * FROM nested WHERE parent_id = '".$row['id']."' ORDER BY `id` DESC";
$r = mysqli_query($conn, $q);
while($row = mysqli_fetch_assoc($r)){ getComments($conn,$row); }
}
?>
<!DOCTYPE HTML><head><script type='text/javascript'>
$(document).ready(function(){
$("a.reply").one("click", function() {
var id = $(this).attr("id");
var parent = $(this).parent();
$("#parent_id").attr("value", id);
parent.append(" <br /><div id='form'><form><input type='text' name='name' id='name'><textarea name='comment_body' id='comment_body'></textarea><input type='hidden' name='parent_id' id='parent_id' value='0'><button id='reply'>Reply</button></form></div>");
$("#reply").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){ showComment(); }
});
});
});
});
</script></head></html>
//index.php
<html><head><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function showComment(){
$.ajax({
type:"post",
url:"post.php",
data:"action=showcomment",
success:function(data){ $("#comment").html(data); }
});
}
showComment();
$(document).ready(function(){
$("#button").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
</script></head><body>
<form id="form_comment">
<input type="text" name="name" id='name'/>
<textarea name="comment_body" id='comment_body'></textarea>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
<input type="button" id="button" value="Comment"/>
</form>
<div id="comment"></div> </body></html>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault(); //add this line to prevent reload
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
Here is a simple incomplete ajax example.
FromPage.php
Here is the ajax that I'd use. The variables can be set however you like.
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var name = "John Smith";
$.ajax({
url: 'toDB.php',
type: 'post',
dataType: 'html',
data: {
carArray: cars,
firstName: name
},
success: function(data) {
console.log(data); //Testing
}
});
</script>
toDB.ph
This is the second page - the one that writes the values to the database etc.
<?php
$cars = $_POST['carArray'];
$FirstName=$_POST['firstName'];
//Used to test - it will print out the array
print("<pre>");
print_r($cars);
print("</pre>");
//Do something with $cars array and $FirstName variable
?>

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

Ajax post to database doesn't post anything

I know this has been asked before, but I can seem to find an solution that fixes the problem in my case. I'm trying to post data to a Mysql database with an an Ajax post
HTML
<form action="" method="post">
<input type="text" id="message" name="message">
<<input type="submit" value="Send" id="submit">
</form>
Ajax post
$(document).ready(function(){
$("#submit").click(function(){
var message = $("#message").val();
var data = "message=" + message;
console.log(data);
if(message != ''){
console.log(data);
$.ajax({
type: "POST",
url: "classes/messages.php",
data: data,
succes: function(){
alert("succes");
}
});
}
return false;
});
});
PHP code
class messages{
function getMessages(){
$con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
$message = $_POST['message'];
mysqli_query($con, "INSERT INTO messages(message, time, user_id)
VALUES('$message', 'now()', '12')")or die(mysqli_error($con));
mysqli_close($con);
}
}
$messages = new Messages();
$messages->getMessages();
Everytime I submit the form nothing happends, not even an php error appears. I've checked the Ajax post and both console.logs return the correct value, so I think the variable is reachable.
I've also checked if the php function is executed at all, which is the case.
Try this
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var message = $("#message").val();
var data = "message=" + message;
console.log(data);
if(message != ''){
console.log(data);
$.ajax({
type: "POST",
url: "classes/messages.php",
data: data,
success: function(){
alert("succes");
}
});
}
return false;
});
});
</script>
</head>
<body>
<form action="" method="post">
<input type="text" id="message" name="message">
<input type="button" value="Send" id="submit">
</form>
</body>
</html>
and
<?php
class messages{
function getMessages(){
$con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
$message = $_POST['message'];
mysqli_query($con, "INSERT INTO messages(message, time, user_id)
VALUES('$message', 'now()', '12')")or die(mysqli_error($con));
mysqli_close($con);
}
}
$messages = new Messages();
$messages->getMessages();
Basically I changed input type='button' from `'submit' . Since it was a submit button, the ajax call was never done, instead the form was submitting.
You could try this shorthand method instead:
var message = "message=" + $("#message").val();
$("#submit").on("click", function(ev)){
$.post("classes/messages.php", {message: message}, 'json').done(function (data, textStatus, jqXHR) {
console.log("succes");
}).fail(function () {
console.log("Fail");
return false;
}).always();
}
Use on it's better and recommended than just trigger the function on the selector itself.

Why doesn't my Ajax function work?

I am trying to use a form to submit two javascript variables to a php script and return the output to a new Div on the same page via an ajax function. It doesn't work.
here is my code
javascript/html
<link href="style/background.css" rel="stylesheet" type="text/css">
<script src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
fbPageOptions = {
shadowType: 'halo',
resizeDuration: 5.5,
imageFadeDuration: 4.5,
overlayFadeDuration: 0,
navType: 'both',
width: 580,
height: 405
};
</script>
<body>
<div id ="userForm">Add New User
<br>
<br>
<form id ="form">
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname" ><br>
<input type="submit" value="Submit" id="submit">
</form>
</div>
<script type="text/javascript">
var firstname = "";
var lastname = "";
$('#form').submit(function() {
firstname = $("input#firstname").val();
lastname = $("input#lastname").val();
alert(firstname + lastname);
$.ajax({
type: "POST",
url: "my url is in here",
data: {firstname: firstname, lastname: lastname},
success: function(data) {
$("#submitted").html(data);
alert("success");
}
});
});
</script>
<br>
<div id="submitted"></div>
</body>
here is the php code
<?php
$firstname = $_POST["firstname"];
echo "First name added is $firstname";
echo "<br>";
$lastname = $_POST["lastname"];
echo "Last name added is $lastname";
?>
when I submit the form the alert box triggers but the div is not updated. I'm using virtually the same code on another page and it works fine. :( Any ideas?
Thanks so much.
The form submits, reloading the page, you need to prevent the default submit event :
$('#form').on('submit', function (e) {
e.preventDefault();
var firstname = $("#firstname").val(),
lastname = $("#lastname").val();
$.ajax({
type: "POST",
url: "my url is in here",
data: {
firstname: firstname,
lastname: lastname
}
}).done(function (data) {
$("#submitted").html(data);
alert("success");
});
});
return false in submit function to prevent the default behaviour of submit which is causing the problem.
$('#form').submit(function() {
firstname = $("input#firstname").val();
lastname = $("input#lastname").val();
alert(firstname + lastname);
$.ajax({
......
});
return false;
});
You should use methods like $.param or .serialize to send you data.
http://api.jquery.com/jQuery.param/
http://api.jquery.com/serialize/

Categories