Insert records to mysql database with php using Ajax - php

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

Related

Error while login with valid credentials

I have a simple ajax login page, as shown below. I'm trying to get it working for 4 days but don't know why it's not working.
Even if I enter valid email ID and name, it shows invalid credentials, I don't know what I'm doing wrong.
Here is my code:
login.php
<?php
session_start();
$mysqli = mysqli_connect("localhost","root","","ajax1");
?>
<!DOCTYPE HTML>
<html>
<head>
<title> login script with ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body style="background-color:#b3ffff">
<div style="padding-left:500px ; padding-top:200px">
Name: <input id="name" type="text" name="name" placeholder="Enter name"><br><br>
E-mail: <input id="email" type="email" name="email" placeholder="Enter E-mail"><br><br>
<input id="submit" name="submit" type="button" value="Log In">
<p style="color:black">Havent Registered? Register.</p><br><br>
<div id="display" style="color:red"></div>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var datastring = 'name=' + name + '&email=' + email;
if(name=='' || email==''){
$("#display").html("Please Enter All The Fields");
}
else{
$.ajax({
type: "POST",
url: "success.php",
data: datastring,
cache: false,
success: function(result){
$("#display").html(result);
window.location = "welcome.php";
}
});
}
return false;
});
});
</script>
</div>
</body>
</html>
success.php
<?php
session_start();
$mysqli = mysqli_connect("localhost","root","","ajax1");
if (isset($_SESSION['id'])){
header('location:welcome.php');
}
if (isset($_POST['submit'])){
// removes backslashes
$name = stripslashes($_REQUEST['name']);
//escapes special characters in a string
$name = mysqli_real_escape_string($mysqli,$name);
// removes backslashes
$email = stripslashes($_REQUEST['email']);
//escapes special characters in a string
$email = mysqli_real_escape_string($mysqli,$email);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE name='$name' and email='$email'";
$result = mysqli_query($mysqli,$query);
$row1 = mysqli_fetch_array($result);
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['name'] = $name;
$_SESSION['id']=$row1['userid'];
echo 'Logged in Successfully '
}
else{
echo ' Invalid Name or E-MAIL ';
}
}
?>
welcome.php
<?php
session_start();
if (!isset($_SESSION['id'])) {
header('location:login.php');
}
?>
<!DOCTYPE html>
<html>
<body>
<?php
include_once 'connect.php';
$query=mysqli_query($mysqli,"select * from `users` where userid='".$_SESSION['id']."'");
$row=mysqli_fetch_array($query);
echo 'Welcome - '.$row['username'];
?>
<!--br>
Logout
<br><br-->
</body>
</html>
Both your AJAX and PHP codes require some fixing. Also try to use password in login instead of Email and Name only. Try fixing both your AJAX Code and PHP code.
Use the following code in your AJAX.
<script>
var name = $("#name").val();
var email = $("#email").val();
var formData = {
'name' : name,
'email' : email
};
if(name=='' || email==''){
$("#display").html("Please Enter All The Fields");
} else {
$.ajax({
type: "POST",
url: "success.php",
data: formData,
dataType : 'json', // what type of data do we expect back from the server
encode : true
success: function(data){
console.log(data);
if(data == 1) {
window.location = "welcome.php";
} else {
$("#display").html("Please Enter All The Fields");
}
}
});
}
</script>
in PHP:
instead of $_REQUEST['name'], $_REQUEST['email'] try using $_POST['name'] and $_POST['email']
then echo '1' for success or echo '0' it it fails.
try building it in block bby block and check for errors as you develop it
You really need to make this as simple as possible to troubleshoot. Then when you get this working, slowly add more code to it until it all works. Do it one step at a time.
Change your success.php page to just this:
<?php
$myPostArray = array(
'name' => $_POST['name'],
'email' => $_POST['email']
);
echo json_encode($myPostArray);
?>
login.php to this:
<!DOCTYPE HTML>
<html>
<head>
<title> login script with ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="background-color:#b3ffff">
<div style="padding-left:500px ; padding-top:200px">
Name: <input id="name" type="text" name="name" placeholder="Enter name" required><br><br>
E-mail: <input id="email" type="email" name="email" placeholder="Enter E-mail" required><br><br>
<input id="submit" name="submit" type="button" value="Log In">
<p style="color:black">Havent Registered? Register.</p><br><br>
<div id="display" style="color:red"></div>
</div>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
if(name != '' && email != ''){
var datastring = 'name=' + name + '&email=' + email;
$.ajax({
url: "success.php",
type: "POST",
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log(data); //This will show what you get back from success.php.
if (data) {
//It works, do something.
alert('Here is your response from the php page:' + response);
console.log('Here is your response from the php page:' + 'Name: ' + data['name'] + ' ' + 'Email: ' + data['email']);
} else{
//It does not work, do something.
alert('Your ajax failed to get the info from your php page. Keep troubleshooting');
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
}else{
alert('You must enter a valid name and email.');
}
});
});
</script>
</body>
</html>
You really need to be using you console to aide you in trouble shooting this problem. You get much more detailed information. Stop using alert() to troubleshoot.

Issue with Ajax Contact Form

I am trying to put together a simple contact form with ajax, where users are not redirected to the contact.php file once the submission is done..
There is no errors.. I am always redirected..
Any idea please? Any suggestion is highly appreciated. Thanks!
contact.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<form action="contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your Name">
</div>
<div>
<input type="email" name="email" placeholder="Your Email">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
<div>
<input type="submit" value="Send">
</form>
</body>
</html>
contact.php
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
print_r($_POST);
}
?>
main.js
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success:function(response) {
console.log(response);
}
});
return false;
});
You need to prevent the default form behavior.
$('form.ajax').on('submit', function(evt) {
evt.preventDefault();
You need to ouput json format so header need to be setting and you need to return json value to ajax success so need json_encode($object_or_array_form_php);
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
header("Content-type:application/json");
$_POST['success'] = "You form is sending ...";
echo json_encode($_POST); //this is the "response" param form ajax
}
?>
Hacked! Here's a little bit different way ..
<script>
$(document).ready(function() {
$('form').submit(function (event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-message").load("contact.php", {
name: name,
email: email,
message: message,
submit: submit
});
});
});
</script>

Google reCaptcha validate using jquery AJAX

I don't know how can i apply this to my login page, once captcha success response on ajax then submit form.
Here's my html form(i leave action null because i'm still in testing)
<form action = "" method = "post">
<input type = "text" id = "email" name = "email">
<input type = "password" id = "pass" name = "password">
<div class = "form-group col-lg-6">
<div class="g-recaptcha" data-sitekey="MY_KEY"></div>
</div>
<input type = "button" id = "submit" value = "submit">
</form>
Here's how i understand ajax on captcha sending captcha word.. if captcha success submit form if failed i will give an alert.
$('#submit').click(function() {
var captcha = "captcha";
$.ajax({
url: "captcha.php",
method: "post",
data:{captcha:captcha},
success:function(data){
if(data=='success'){
$('form').submit();
}
}
else{
alert('captcha failed. try again');
}
});
});
my captcha.php how i receive $_POST['captcha']
<?php
if($_POST['captcha']){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = 'MY_SECRET_KEY';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if($data->sucess==true){
echo "success";
}
else{
echo "failed";
}
}
?>
please help me to understand how will it work and how can it be done using AJAX
THANK YOU IN ADVANCE :)
UPDATE
i just notice how can i $_POST['g-recaptcha-response']; ??
You can use this code:
HTML Code:
<form action="" method="POST" id="loginForm">
<input type="text" id = "email" name="email">
<input type="password" id="pass" name="password">
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="10LDDpf0ehtMZY6kdJnGhsYYY-6ksd-W"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
JavaScript
$(document).ready(function() {
var loginForm = $("#loginForm");
//We set our own custom submit function
loginForm.on("submit", function(e) {
//Prevent the default behavior of a form
e.preventDefault();
//Get the values from the form
var email = $("#email").val();
var pass = $("#pass").val();
//Our AJAX POST
$.ajax({
type: "POST",
url: "login.php",
data: {
email: email,
password: pass,
//This will tell the form if user is captcha varified.
g-recaptcha-response: grecaptcha.getResponse()
},
success: function(response) {
console.log(response);
//console.log("Form successfully submited");
}
})
});
});
PHP Code:
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '10LDDpf0ehtMZY6kdJnGhsYYY';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//captacha validated successfully.
$email = !empty($_POST['email'])?$_POST['email']:'';
$password = !empty($_POST['password'])?$_POST['password']:'';
echo "captacha validated successfully.";
else:
echo "Robot verification failed, please try again.";
endif;
else:
echo 'invalid captcha';
endif;
else:
//Nothing
endif;
?>
I am using re-captcha validation using jQuery / ajax as per below :
<script src="https://www.google.com/recaptcha/api.js" >;
<form method="post" name="contactForm">
<input type="text" name="fname"/>
<input type="text" name="lname"/>
<input type="text" name="Phone"/>
<div class="g-recaptcha" data-sitekey="[site_key]" data-callback="onReturnCallback" data-theme="dark"></div>
<input value="submit" type="submit"/>
</form>
Validation / ajax :
//Initialize jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var onReturnCallback = function(response) {
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response},
success: function(result) {
var res = result.success.toString();
alert(res);
if (res == 'true') {
document.getElementById('g-recaptcha').innerHTML = ' Your Success Message';
}
}
});
};
</script>

Submit a Form without Reloading

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>

Page refreshes on submit click with ajax

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

Categories