I have created a simple Login Register program using PHP.
Now I am trying to validate if username already exists or not using jquery ajax. The jquery code runs but keeps on showing 'Checking Availability'.
Here is the code I have used. Please ignore the vulnerability and other errors in my PHP code ( which may not affect jquery ajax process ) as I am new to this. I'm working for improving those things.
Register.php
<?php
include('config.php');
if(isset($login_session))
{
header("Location: login.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$name = mysqli_real_escape_string($obj->conn,$_POST['name']);
$email = mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = md5($password);
$sql ="SELECT uid from users WHERE username = '$username' or email = '$email'";
$register_user = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$no_rows = mysqli_num_rows($register_user);
if($no_rows == 0)
{
$sql2 = "INSERT INTO users(username, password, name, email) values ('$username', '$password', '$name', '$email')";
$result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
echo "Registration Successfull!";
}
else{
echo "Registration Failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/username.js"></script>
</head>
<body>
<form action="register.php" method="post">
<label>UserName:</label>
<input type="text" id="username" name="username" required/>
<span id="status"></span><br />
<label>Password :</label>
<input type="password" name="password" required/><br/>
<label>Full Name :</label>
<input type="text" name="name" required/><br/>
<label>Email :</label>
<input type="email" name="email" required/><br/>
<input type="submit" value=" Submit "/><br />
</form>
</body>
</html>
username.js
$(document).ready(function()
{
$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");
if(username.length > 3)
{
$("#status").html('<img src="img/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "php/username-check.php",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK')
{
msgbox.html('<img src="img/yes.png" align="absmiddle"> <font color="Green"> Available </font> ');
}
else
{
$("#username").removeClass("green");
$("#username").addClass("red");
msgbox.html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
username-check.php
<?php
include("config.php");
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$username = mysqli_real_escape_string($obj->conn,$username);
$sql = "SELECT username FROM users WHERE username='$username'";
$sql_check = mysqli_query($obj->conn,$sql);
if (!$sql_check)))
{
echo 'could not complete query: ' . mysqli_error($obj->conn,$sql_check);
}else{
echo 'query successful!';
}
if(mysqli_num_rows($obj->conn,$sql_check))
{
echo '<font color="#cc0000"><b>'.$username.'</b> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
and I want to know if there is a way to check if jQuery Ajax sent the POST request to that file or not?
You are confusing ajax functions...Syntax will be like this
$.ajax({
url: url,
data: data,
type: "POST",
beforeSend: function () {
},
success: function (returnData) {
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function () {
}
});
Examine the request using a browser utility
- Launch the chrome browser
- Right click and select inspect element menu
- click on Network tab
- Load your URL
- Perform the Ajax request
- You can see the request here (new request will be last in the list).
- Click on it
- Right side window shows you request and response data
You did correct.Easy way to check them is use firebug tool on your browser...I recommend firefox with firebug.install it first and then open it before you post your form.then goto console log and send your form...Check it out,best software.
Related
I am checking email id is available or not in the database using ajax which is working.I have one submit button and that is disabled on page load.I have to enable that button when the user enters the right email address which is available on the database. If email is available in the database the button will enable otherwise button will be disabled.There is some issue in if condition. I tried button still the same issue. Would you help me in this?
$("input[type='submit']").removeAttr("disabled");
$("input[type='submit']").prop('disabled', false);
If I used CSS for button then disable is not working.
Html
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" >
Ajax
$(document).ready(function()
{
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 1) {
$('input[type="submit"]').attr('disabled' , false);
}
else{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr('disabled', true);
}
},
});
});
});
//Disable the button on page load
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
}
Try this-
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "ok") {
$(elem).attr('disabled' , false); //here pass elem
}
else{
$("#email-validation-error").html('Email not available');
$(elem).attr('disabled', true); //here pass elem
}
},
});
});
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "ok";
}
}
You should check and verify your response:
Process.php
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
else{
echo "success";
}
Ajax
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
html
<input id="submitYesNo" type="submit" name="next" value="submit" >
Try This Code .
Hope it will work properly
success:function(data)
{
if (data == 1)
{
$('input[type="submit"]').removeAttr("disabled", "disabled");
}
else
{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr("disabled", "disabled");
}
Finally, I found my answer with the help of Mr.Ahmed Ginani
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form >
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" disabled>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$(elem).attr('disabled', true);
$("input[name='email']").bind('change',function() // Changes from key press to change and bind
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 'success') { // getting success name from process.php page
$("#id").attr('disabled' , false);
$("#email-validation-error").html(''); //Change here for hiding the error message
}
else{
$("#email-validation-error").html(data);
$('#id').attr('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
Process.php
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}
I'm trying to create a log in form using html > ajax > php, the problem is the php is not working, I don't know where is the problem, I think the ajax cannot execute my php file. I need help. Thanks in advance.
Here is my HTML code: my form and inputs are below
<form id="loginForm">
<input type="text" data-clear-btn="true" name="username" id="username" value="" placeholder="Username / ID No.">
<input type="password" data-clear-btn="true" name="password" id="password" value="" placeholder="Password">
<input type="checkbox" name="rem_user" id="rem_user" data-mini="true">
<label for="rem_user">Remember me</label>
<input type="submit" name="login" id="login" value="Log in" class="ui-btn" />
</form>
<div class="err" id="add_err"></div>
AJAX script that sends request on my php file
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is in database.
var dataString = 'username=' + username + '&password=' + password;
if (username == '' || password == ''){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: dataString,
success: function(result){
window.location="#report_page";
}
});
}
return false;
});
});
</script>
PHP File
<?php
require "includes/connection.php";
include "includes/function.php";
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = sanitize($username);
$password = sanitize($password);
$pass2 = md5($password);
$salt = "sometext";
$validateHash = $salt.$pass2;
$pass = hash("sha512", $validateHash);
$sql = "SELECT * FROM user_login WHERE username='".$username."' and password='".$password."'";
$result = mysqli_query($con,$sql) or die("Error: ". mysqli_error($con));
$count=mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
$id = $row['user_id'];
$username = $row['username'];
$name = "".$row['firstname']." ".$row['lastname']."";
$acc_type = $row['Acc_Type'];
}
if($count==1){
if($acc_type == 'user') {
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
echo 'true';
}
else {
echo 'false';
}
}
}
?>
as Cattla mentioned in comments.
Your PHP is looking for $_POST['login'], and your $.ajax call didn't pass that in.
so here is the answer
var dataString = 'login=login&username=' + username + '&password=' + password;
Debug tips
Did ajax send all required inputs to PHP (you can inspect this from browser developer tool)
Did php receive all required inputs (you could var_dump($_POST)
Did php connect to mysql successfully
Did ajax receive data from PHP (use alert or console.log)
try this, and if you get error state what it is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
if (username == ' ' || password == ' '){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: $(this).serialize(),
success: function(result){
alert('sucess'); //window.location="#report_page";
}
});
}
return false;
});
});
</script>
I'm echoing a message ('ok') from a PHP script to a JQuery ajax call.
I'm echoing out the correct message, and its showing up in the console when i log it, but the appropriate jquery function is not firing - according to the code i should get an Your password has been changed successfully" message, but I only get a "there was a problem" message - can anyone suggest a reason why?
here is the code first the PHP:
if(isset($_POST['oldpass'])){
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$sql = "SELECT password, salt FROM users WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$current_salt = $row["salt"];
$db_pass = $row["password"];
}
$old_pass_hash = crypt($oldpass, $current_salt);
if ($old_pass_hash != $db_pass){
echo "problem";
exit();
}
}
$s = "$2a$10$";
$random = randStrGen(20);
$salt = $s.$random;
$p_crypt = crypt($newpass, $salt);
$sql = "UPDATE users SET password='$p_crypt', salt='$salt' WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
if ($query == true){
$_SESSION['password'] = $p_crypt;
echo 'ok';
exit();
}
}
?>
This is the javascript/JQuery
function change_password(){
var oldpass = $('#old_pass').val();
var newpass = $('#new_pass').val();
var newpass_conf = $('#confirm_new_pass').val();
if(newpass != newpass_conf){
$('#status').html("Your passwords do not match");
} else if(newpass=="" || oldpass==""){
$('#status').html("You have not entered anything");
}
$.ajax({
type: 'POST',
url: "changePassword.php",
dataType: 'text',
data: {
"oldpass": oldpass,
"newpass": newpass_conf },
success:function(data){
if(data == "ok"){
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
});
}
$(document).ready(function(){
$(document).on('click','#change_password', function(){
change_password();
});
});
</script>
and finally the html
<div> <h1>Change your password</h1></div><hr>
<form id="change_password_form" class="input" onsubmit="return false;">
<div> <label for="old_pass">Current Password:</label>
<input id="old_pass" type="text" class="searchbox" onfocus="emptyElement('status')" maxlength="88" value=""></div>
<div> <label for="new_pass">New Password:</label>
<input id="new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""> </div>
<div><label for="confirm_new_pass">Confirm New Password:</label>
<input id="confirm_new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""><div>
<input type="button" style="position:relative;top:10px; float:right;" id="change_password" value="Change Password"></form>
<span id="status" class="statuserror"></span>
</body>
</html>
change the dataType: "json" in your ajax call
then in your php code return json data
json_encode(array('response'=>'ok'));
your ajax success function should look like this,
success: function (data) {
var resultObject = jQuery.parseJSON(data);
if(rersultObject['response']=='ok') {
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
}`
here parseJSON is used to convert JSON string to javascript object.
I got this problem a while ago and could never figure it out, although different scenario. What I did was to change the data type to json like so:
$.ajax({
type: 'POST',
url: url,
data: 'data=data&other=other'
dataType: 'json',
//if everything goes out as planned
success: function(response) {
alert(response['data']);
}
});
and in the php
$respond = array("data" => 'ok',
"other" => 'whatever else'
);
echo json_encode($respond); //send a response back to javascript
exit();
I've spent some time looking on SO for an answer to this and have found some related issues, but nothing quite like mine...as usual....
I've got a fairly simple php/jquery ajax registration page that is working right up until the ajax callback. What I mean is the form data is passing to php and inserting into the db but when the php response is supposed to come back all that happens is the response displays in the browser. I've followed the logs, checked fiddler, re-written the code with/without json, and anothing seems to change. The odd thing is I have another form on a different page that is set up exactly the same way and everything works there perfectly. The only difference I can find between the two pages is the Request Headers of the php file. The one that works accepts json and the one the other one doesn't, but I have no idea if that means anything . . . I'm kind of grabbing for anything at this point.
So, without further delay, here is my code. Any thoughts/input are greatly appreciated. Thank you!
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="mobile.css" media="screen and (max-device-width: 480px)" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" media="screen and (min-width: 481px)" href="IEjoin.css" />
<![endif]-->
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="register.js" type="text/javascript"></script>
<script src="jquery.placeholder.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<div id="logo">
</div>
<div id="headline">
<h1>Create your account</h1>
</div>
<div id="container">
<form id="register" action="form.php" method="post">
<ul>
<li id="first_name">
<input name="fname" type="text" value="" id="fname" placeholder="First Name" maxlength="30">
<div class="error"></div>
</li>
<li id="last_name">
<input name="lname" type="text" value="" id="lname" placeholder="Last Name" maxlength="30">
<div class="error"></div>
</li>
<li id="email_address">
<input name="email" type="text" value="" id="email" placeholder="Email Address" maxlength="60">
<div class="error"></div>
</li>
<li id="uname">
<input name="username" type="text" value="" id="username" placeholder="Username" maxlength="15">
<div class="error"></div>
</li>
<li id="pword">
<input name="password" type="password" value="" id="password" placeholder="Password">
<div class="error"></div>
</li>
<li id="gender_select">
<select id="gender" name="gender">
<option value="" selected="selected">Select your gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="unspecified">Unspecified</option>
</select>
</li>
<li id="submit_button">
<button id="register_button" class="register_button_disabled">Create Account</button>
</li>
</ul>
</form>
<script> $('input[placeholder]').placeholder();</script>
</div>
</div>
</body>
$(document).ready(function() {
function validateEmail(email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email);
}
function submitButton() {
if (($("#first_name").hasClass("good")) && ($("#email_address").hasClass("good")) && ($("#uname").hasClass("good")) && ($("#pword").hasClass("good")) ){
$("#register_button").removeAttr("disabled");
$("#register_button").removeClass("register_button_disabled").addClass("register_button");
} else {
$("#register_button").attr("disabled", "disabled");
$("#register_button").removeClass("register_button").addClass("register_button_disabled");
}
}
$("body").mousedown(submitButton);
$("body").keyup(submitButton);
$("body").hover(submitButton);
$("body").mouseover(submitButton);
$("#fname").keydown(function(){
$("#first_name").removeClass("required");
$("#first_name div").html("");
});
$("#fname").bind ("keyup mousedown",function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("wait");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#fname").blur(function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#email").keydown(function(){
$("#email_address").removeClass("required");
$("#email_address div").html("");
});
$("#email").bind ("keyup mousedown",function(){
var email = this.value;
var emailLength = email.length;
if (emailLength<=4){
$("#email_address").removeClass("good").addClass("wait");
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#email").blur(function(){
var email = this.value;
var emailLength = email.length;
if ((emailLength<=4) || (!validateEmail(this.value))) {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (emailLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "Check.php",
data: "email="+email,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");}
else {
$("#email_address").removeClass("wait").addClass("good");
}
}
});
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#username").keydown(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("wait");
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#username").bind ("keyup mousedown",function(){
$("#uname").removeClass("required");
$("#uname div").html("");
});
$("#username").blur(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (unLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "check.php",
data: "username="+un,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
$("#uname").removeClass("wait").addClass("good");
}
}
});
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#password").keydown(function(){
var pw = this.value;
var pwLength = pw.length;
if(pwLength<=5){
$("#pword").removeClass("good").addClass("wait");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#password").bind ("keyup mousedown",function(){
$("#pword").removeClass("required");
$("#pword div").html("");
});
$("#password").blur(function(){
var pw = this.value;
var pwLength = pw.length;
if(pw===""){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please enter a password");
}
if(pwLength<=5){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please use at least 6 characters");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: "form.php",
data: $('#register').serialize(),
success: function(data) {
if (data === "fname") {
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else if (data === "email") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (data === "email2") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");
} else if (data === "username") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (data === "username2") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
window.location.href = "http://site.com";
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
return false;
});
});
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$gender = mysql_real_escape_string($_POST['gender']);
//validate inputs
$emailpull = "SELECT email FROM $tbl_name WHERE email='$email'";
$emailresult=mysql_query($emailpull);
$emailnum=mysql_num_rows($emailresult);
$emailReg = "/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/";
$unpull = "SELECT username FROM $tbl_name WHERE username='$username'";
$unresult=mysql_query($unpull);
$unnum=mysql_num_rows($unresult);
if ($fname == "") {
$response = "fname";
} elseif ($email == "") {
$response = 'email';
} elseif (!preg_match($emailReg, $email)) {
$response = 'email';
} elseif ($emailnum > 0) {
$response = 'email2';
} elseif (strlen($username)<3) {
$response = 'username';
} elseif ($unnum > 0) {
$response = 'username2';
} elseif (strlen($password)<6) {
$response = 'password';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(fname,lname,email,username,password,gender)VALUES ('$fname','$lname','$email','$username','$password','$gender')";
}
$result=mysql_query($sql);
if($result)
$response = "success";
// send message back
echo $response;
?>
<?php
// close connection
mysql_close();
?>
The click handler for #button has this line which may be the culprit:
window.location.href = "http://crushonit.com";
This will redirect to that page when the form has no validation errors.
I'm having a problem with my ajax call. I'm submitting some info via php to mySQL, the submission part works perfectly, it's adding the data to the database, but the ajax function isn't loading that php in the background, it's loading it in the window and showing the php file results.
Here's the HTML code.
<form action="upload.php" class="addItem" method="post">
Firstname:<br><input type="text" class="firstname" name="firstname" /><br>
Lastname:<br><input type="text" class="lastname" name="lastname" /><br>
Age:<br><input type="text" class="age" name="age" /><br>
Photo:<br><input type="file" name="image" accept="image/jpeg" /><br><br>
<input type="submit" class="submitItem" value="Add Row" />
</form>
Logout
</div>
<script>
$(document).ready(function(){
$(".submitItem").click(function(){
// Start AJAX send
jQuery.ajax({
// Enter below the full path to your "send" php file
url: "upload.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
// If form submission is successful
if ( html == 1 ) {
$('.successMessage').show(200);
$('.successMessage').delay(2000).hide();
}
// Double check if maths question is correct
else {
$('.errorMessage').show(200);
$('.errorMessage').delay(2000).hide();
}
}
});
});
});
</script>
Here's the PHP code
<?php
$name = $_POST['firstname'];
$surname = $_POST['lastname'];
$age = $_POST['age'];
if(($name === "") || ($surname === "") || ($age === "")){
echo "please fill in all fields";
} else {
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
if ($sql) { echo "1"; }
else{echo "error";}
}
mysql_close($con);
?>
Your handler needs to return false; to instruct the browser not to do its regular submission action.
(Also, you should really consider using the submit event of the form, rather than the click event of the button.)
<script type="text/javascript">
$(function(){
$("form.addItem").submit(function(){
// Start AJAX send
jQuery.ajax({
// ... your parameters ...
});
return false;
});
});
</script>