Consider this image which is an iframe window when user clicks on a link.
My Problem
When user clicks deposit the form gets submitted and the window closes, thus the user does not know if deposit was successful or not.
What I want to do
I am looking for a way to keep the iframe window open after the form has been submitted, to display appropriate message
Form HTML
<form name="depForm" action="" id="register_form" method="post">
User Name<br /><input type="text" name="uname" value="" /><br />
Credit Card Nr<br /><input type="text" name="cc" value="" /><br />
CSV Nr<br /><input type="text" name="csv" value="" /><br />
Amount<br /> <input type="text" name="amount" value="" /><br />
<input type="submit" value="deposit" name="deposit" class="buttono" />
</form>
PHP Code
if(isset($_POST['deposit'])){
if(isset($_SESSION['FBID'])){
$uid=$_SESSION['FBID'];
$amount = $_POST['amount'];
$cc = $_POST['cc'];
$csv = $_POST['csv'];
//new bal
$bal = getBal($uid);
$newBal = $bal+$amount;
$sql="UPDATE members SET balance='$newBal' WHERE member_nr='$uid'";
$result = mysql_query($sql) or die("error please try again");
if($result){
}
}
if anyone can advise me how to keep iframe open after form has been submitted it will be greatly appreciated.
You would need to change the form submission to use AJAX. In the response you can include a state flag to indicate to the UI whether the request was successful or not and act appropriately. Something like this:
$('#register_form').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(data) {
if (data.success) {
// show success message in UI and/or hide modal
} else {
// it didn't work
}
},
error: function(xhr, status, error) {
// something went wrong with the server. diagnose with the above properties
}
});
});
$success = false;
if (isset($_POST['deposit'])) {
if (isset($_SESSION['FBID'])) {
$uid = $_SESSION['FBID'];
$amount = $_POST['amount'];
$cc = $_POST['cc'];
$csv = $_POST['csv'];
$bal = getBal($uid);
$newBal = $bal + $amount;
$sql = "UPDATE members SET balance='$newBal' WHERE member_nr='$uid'";
$result = mysql_query($sql) or die("error please try again");
if ($result) {
$success = true;
}
}
}
echo json_encode(array('success' => $success));
Related
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
I have this "register users" file in which I have a form, I'll simplify in here what I have:
<form action="" method="POST">
<label for="user" class="control-label">User </label>
<input type="text" name="user" class="form-control" id="user" value="" required=""/>
<label for="user" class="control-label">Password1 </label>
<input type="text" name="password1" class="form-control" id="password1" value="" required=""/>
<label for="user" class="control-label">Password2 </label>
<input type="text" name="password2" class="form-control" id="password2" value="" required=""/>
<button type="button" value="signUp" name="submit" class="btn btn-lg btn-primary btn-block" onClick="register()">Sign up!</button>
As you can see, there is an event in there, in a JS file. This file has all the vaidations of the inputs and it works just fine (I don't think it's relevant, so I won't post it). It also has the AJAX call to the PHP file that will insert the data into the database.
function register(){
if(validationRegister()){
$.ajax({
url: "http://localhost/myProject/extras/processSignUp.php",
type: "POST",
data: {"user": user,
"password": password,
"password2": password2,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "Registered"){
window.location.href = "http://localhost/myProject/index.php";
}else{
window.location.href = "http://localhost/myProject/signUp.php";
}
}
});
}else{
alert("Incorrect data");
}
}
And this is the PHP file:
<?php
include_once "connection.php"; --> this has all the data for the connection to the database
if($_POST['user'] == '' || $_POST['password'] == '' || $_POST['password2'] == ''){
echo 'Fill all the information';
}else{
$sql = 'SELECT * FROM `user`';
$rec = mysqli_query($con, $sql);
$verify_user = 0;
while($result = mysqli_fetch_object($rec)){
if($result->user == $_POST['user']){
$verify_user = 1;
}
}
if($verify_user == 0){
if($_POST['password'] == $_POST['password2']){
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "INSERT INTO user (user,password) VALUES ('$user','$password')";
mysqli_query($con, $sql);
echo "Registered";
}else{
echo "Passwords do not match";
}
}else{
echo "This user has already been registered";
}
}
?>
The PHP code, works great when used on its own (it used to be at the beginning of the form file, surrounded by if($_POST['submit']){}) But now I want to use it in a separate file, and use AJAX, and I'm unable to register a user :/ the value of data is never "Registered"... Any ideas?
Thanks in advance! :)
Please never run this code in a live environment, your code is open to SQL injection and you NEED to hash passwords.
This line:
if($_POST['user'] == '' or $_POST['password']){
Looks to be your issue. You want to be testing $_POST['password'] somehow, like $_POST['password'] == '' or !isset($_POST['password']).
Your logic is also horribly constructed, you may want to go look at a few tutorials. e.g. why are you fetching ALL your users just to test if one exists, do that logic in the SQL code itself to avoid fetching an entire table for no reason.
I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong
here gose the DB_Function.php
<?php
class DB_Functions {
private $db;
// constructor for database connection
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
die('Error in database requirments:' . $e->getMessage());
}
}
/**
* Storing new user
* returns user details of user
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
/*to check if user is
already registered*/
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
$sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch(Exception $e){
die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction
//more functions to be added
}
?>
here gose the .php file to be clear on what am doing..!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) > 6){
//validate your mobile
if(strlen($mobile) == 12){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
} else {
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
and here gose the main file .js
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
e.preventDefault();
}
});
});
});
and here gose the corresponding .html file
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
<!-- End Thumbnail-->
</div>
<?php include("js/captcha.php");?>
</div>
<div class="form-group">
<div cle the terms and policy </label></div>
</div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
<
/form>
From the comments:
So only after displaying Registeration successful! I want to submit the form and redirect it to login.html
Well the solution is quite simple and involved adding and setting async parameter to false in .ajax(). Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
So the form will only get submitted if the registration is successful, otherwise not.
Edited:
First of all make sure that <!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supports required attribute.
Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method.
For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.
So here's your HTML code snippet:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required />
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required />
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required />
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required />
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required />
</div>
<!--Your checkbox goes here-->
<!--Your Google ReCaptcha-->
<input type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b" value="Register" />
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
And your jQuery would be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
your form submit takes action before ajax action so its reloading the page and use form submit instead of submit button click
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
Ok steps to be sure that everthing works fine while you try to use ajax
1st : use form submit and use e.preventDefault(); to prevent page reloading
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
alert('Form submited');
});
if the alert popup and form not reloading the page then the next step using ajax
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
$.ajax({
url: "register.php",
type: "POST",
dataType: "JSON",
data: {success : 'success'},
success : function(data){
alert(data);
}
});
});
and in php (register.php)
<?php
echo $_POST['success'];
?>
this code should alert with "success" alert box .. if this step is good so now your ajax and php file is connected successfully then pass variables and do another stuff
I have a form that currently after pressing the submit button it changes website to echo a success message. I want when the user clicks the submit button, a message will show him that he successfully added a record, without changing the page. I think the proper way is ajax .
OPEN TO ANY SUGGESTIONS
Below is the form and php file used to insert values into the database
form
<div id="addForm">
<div id="formHeading"><h2>Add Product</h2></div><p>
<form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
<label for="title">Title: </label><input type="text" name="title"/>
<label for="description">Desc: </label><input type="text" name="description"/>
<label for="price">Price: </label><input type="text" name="price" />
<label for="stock">Quan: </label><input type="text" name="stock" />
<p>
<small>Upload your image <input type="file" name="photoimg" id="photoimg" /></small>
<div id='preview'>
</div>
<select name="categories">
<option value="mens">Mens</option>
<option value="baby_books">Baby Books</option>
<option value="comics">Comics</option>
<option value="cooking">Cooking</option>
<option value="games">Games</option>
<option value="garden">Garden</option>
<option value="infants">Infants</option>
<option value="kids">Kids</option>
<option value="moviestv">Movies-TV</option>
<option value="music">Music</option>
<option value="women">Women</option>
</select>
<input type="submit" id="submit_form" name="Submit" value="Add new item">
</form>
insert.php (used in the form)
session_start();
$session_id='1'; //$session id
$path = "../cms/uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$table = $_POST['categories'];
$title = $_POST['title'];
$des = $_POST['description'];
$price = $_POST['price'];
$stock = $_POST['stock'];
$sql="INSERT INTO $table (title, description, price, image, stock)
VALUES
('$title','$des','$price','$path$actual_image_name','$stock')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
die("1 record added into the $table table");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
I have this script but i cant get it to work
<script>
$(document).ready(function () {
$('input#submit_form').on('click', function() {
$.ajax({
url: '../insert.php',// TARGET PHP SCRIPT
type: 'post', // HTTP METHOD
data: {
'title' : $('input[name="title"]').val()
},
success: function(data){
alert(data); // WILL SHOW THE MESSAGE THAT YOU SHOWED IN YOUR PHP SCRIPT.
}
});
});
})
</script>
Your code is fine. The AJAX call is probably happening, but you haven't told he button to stop its default behavior (navigating away). Here is what needs to change. Notice that I've added an event parameter to your callback.
$('input#submit_form').on('click', function(event) {
event.preventDefault(); //Don't do your default behavior, button
$.ajax({
url: '../insert.php',
type: 'post',
data: {
'title' : $('input[name="title"]').val()
},
success: function(data){
alert(data);
},
//if it breaks, you want to be able to press F12 to see why
error: function(data){
window.console.log(data);
}
});
return false;
});
Even if this doesn't work and there is something else wrong with your code, you will at least be able to press F12 after submitting your form to see if there are other errors (500 errors from your php, 404 errors from a bad link, etc). It's not so easy to see what you did wrong when you are directed to the submission page immediately.
I'm new to ajax concept. Here i'm trying to insert the user details(signup form) into the database. it inserted the datas into the db succesfully. But, ajax is my problem.
1) i didn't get any error message if form fields are empty. you can see my below codes i've done validation on post.php page. but, it doesn't return the error values. 2) it stores the empty values into database. 3) if datas stored successfully i want to get the success message & if datas failed to store in db i want to get the error message. How should i do these all things?
Ajax.js
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#e_name").html('Name required');
}
if(msg=='error_m')
{
$("#e_mobile").html('Mobile required');
}
//success and error alert
if(data="inserted")
{
alert("insertion success");
}
else
{
alert("falid to insert into database");
}
}
});
e.preventDefault();
});
});
Post.php
<?php
include_once('config.php');
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
try
{
$stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
$conn->errorInfo();
$stmt->bindParam('1', $name, PDO::PARAM_STR);
$stmt->bindParam('2', $mobile, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database' .$e->getMEssage();
}
?>
Homepage.php
<p>register here</p>
<div id="light" class="white_content">
Close
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
After your error messages are returned, you need to stop the script execution. Your current code still tries to add the values and hence overrides your custom error messages. Most probably then your PHP returns your exception message and which is not what your JavaScript is expecting.
if($name == "")
{
echo 'error_n';
die(); // Stop here
}
if($mobile == "")
{
echo 'error_m';
die(); // Stop here
}
Also add echo 'inserted'; when your database insert is successful.