My main task is to create a contacts list. So the user presses the button, then the user sees on the screen, types in an Email of contact user and then if the response from server is "result === 0" the contact user will be successfully added to the contacts list. If the response from server is "result === -1", then the user was not found because of email does not exist.
Everything works fine, except one thing: even when the Email is wrong, it shows that the response from the user was successful.
I can't find what I do wrong. Can anyone help me please?
Here is my code:
Contact List (React Native):
addNewContact = (email) => {
this.setState({
promptVisible: false,
});
if (email === this.props.email) {
Alert.alert('This is your username', 'You cannot add yourself to contacts!');
return;
}
for (var i = 0; i < this.state.contacts.length; i++) {
if (email === this.state.contacts[i].email) {
Alert.alert('Existing Contact', 'Contact ' + email + ' already exists');
return;
}
}
this.showLoading();
fetch('LINK')
.then((response) => response.json())
.then((responseData) => {
this.hideLoading();
var result = responseData.result;
var contactId = responseData.id;
var name = responseData.name;
if (result === 0) {
console.log("Success");
var newContacts = this.state.contacts.slice();
newContacts[newContacts.length] = {
contact_id: contactId,
name: name,
email: email
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newContacts),
contacts: newContacts
});
Alert.alert('Contact added', 'User ' + email + ' was added to your contacts')
console.log(newContacts);
} else {
if (result === -1) {
Alert.alert('Not Found', 'User ' + email + ' not found');
console.log("Bad");
console.log(responseData);
}
}
})
.done;
}
Server (PHP):
<?php
include 'DBConfig.php';
$conn = new mysqli($Name, $User, $Pass, $Database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$email = $obj['email'];
$sql = "SELECT id, name, email FROM Registration WHERE email='$email'";
$result = mysqli_fetch_array(mysqli_query($conn,$sql));
if (isset($result)) {
$result = array('result' => 0);
echo json_encode($result);
} else {
$result = array('result' => -1);
echo json_encode($result);
}
echo $json;
$conn->close();
?>
upd: I found out that in my console it shows:
Success
Array [
Object {
"contact_id": undefined,
"email": "Djdf",
"name": undefined,
},
]
Related
I am doing a custom script to restrict a private website, user need access-code and their last name to access the website. The Webiste made with WordPress while the restrict credentials was from an external php application.
I have two files one is home.php and another is autho.php. The login form is in home.php where the form and Ajax code written their. The autho.php is the server-side script and creating the session to restrict WordPress site.
The session validation happening at /wp-content/themes/twentynineteen/header.php file. At the area of wordpress site I cannot able to find the session data which was created at autho.php. Please suggest.
home.php (login form)
<script type='text/javascript'>
$(document).ready(function(){
$('#login_error').hide();
$('#accessform').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"doctor_autho.php?action=login&type=login",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#submit').attr('disabled', 'disabled');
},
success:function(data)
{
if(data.result = 'false')
{
$('#login_error').show();
$('#login_error').html("<strong> Doctors last name or code is invalid </strong>");
$('#submit').prop('disabled', false);
}
if(data.result = 'true')
{
$('#login_error').show();
$('#login_error').html("<strong> Access Granted !!! </strong>");
window.location.href = "/index.php");
}
$('#submit').attr('disabled', false);
},
error: function (response) {
$('#login_error').show();
$('#login_error').html("<strong> Doctors last name or code is invalid </strong>");
$('#submit').prop('disabled', false);
}
})
});
});
</script>
autho.php PHP file
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$type = isset($_GET['type'])?$_GET['type']:"";
$action = isset($_GET['action'])?$_GET['action']:"";
if(isset($_POST) && $action == "login" && $type=="login"){
$doctor_invitation_code= isset($_POST['doctor_invitation_code'])?$_POST['doctor_invitation_code']:"";
$doctor_last_name= isset($_POST['doctor_last_name'])?$_POST['doctor_last_name']:"";
if($doctor_invitation_code =="" OR $doctor_last_name ==""){
$data = array("result" => "false", "msg" => "Parameter is required");
die(json_encode($data));
}else{
check_login($doctor_invitation_code,$doctor_last_name);
}
}else{
$data = array("result" => "false", "msg" => "Parameter wrong used!");
die(json_encode($data));
}
function check_login($doctor_invitation_code,$doctor_last_name){
Global $conn;
$doct_auto_query ="SELECT * FROM `tbl_user_master` WHERE patient_invition_code='".$doctor_invitation_code."' AND user_lname='".$doctor_last_name."' AND user_type='2' and is_deleted=0 limit 1";
//echo $doct_auto_query;
$result = $conn->query($doct_auto_query);
if($result->num_rows > 0){
$data = array("result" => "true", "msg" => "Access Granted !!!");
session_start();
$_SESSION['invitation_code'] = $doctor_invitation_code;
$_SESSION['last_name'] = $doctor_last_name;
die(json_encode($data));
}else{
$data = array("result" => "false", "msg" => "The Invitation code or Last Name is wrong used!");
header ("Location: home.php");
die(json_encode($data));
}
}
Session validation on theme's header.php file
session_start();
if (!isset($_SESSION['invitation_code']) && !isset($_SESSION['last_name']) ) {
header("Location: https://www.website.com/home.php");
}
At WordPress site under the theme header file I cannot able to access $_SESSION['invitation_code'] and $_SESSION['last_name'] there, please suggest how to fix this.
At First Put the session_start(); at wp-config.php file.
define( 'WP_SESSION_USE_OPTIONS', true );
session_start();
Your JQuery something like this
<script type='text/javascript'>
$(document).ready(function(){
$('#login_error').hide();
$('#accessform').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"autho.php?action=login&type=login",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#submit').attr('disabled', 'disabled');
},
success:function(data)
{ console.log(data);
if(data.result =="true") {
$('#login_error').show();
$('#login_error').html("<strong> "+data.msg+" </strong>");
window.location.href = "index.php";
return false;
}
if(data.result == "false") {
$('#login_error').show();
$('#login_error').html("<strong> "+data.msg+" </strong>");
$('#submit').prop('disabled', false);
return false;
}
$('#submit').attr('disabled', false);
},
error: function (response) {
$('#login_error').show();
$('#login_error').html("<strong> There is an error! </strong>");
$('#submit').prop('disabled', false);
}
})
});
});
</script>
Your PHP code something like this
<?php
$con = mysqli_connect("127.0.0.1","dbuser","dbpassword","dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$doctor_last_name = mysqli_real_escape_string($con, $_POST['doctor_last_name']);
$password = mysqli_real_escape_string($con, $_POST['doctor_invitation_code']);
if($doctor_last_name !="" && $password !=""){
$query ="SELECT * FROM `tbl_user_master` WHERE is_deleted=0 AND user_type='2' ";
if($doctor_last_name !=""){
$query .=" AND user_lname='".$doctor_last_name."' ";
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) == 0){
$data = array("result" => "false", "msg" => "The Last Name is invalid.");
}
}
}
//end
//validation for invitation code
if($password !=""){
$query .=" AND patient_invition_code='".$password."' ";
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) == 0){
$data = array("result" => "false", "msg" => "The Invitation Code is invalid.");
}
}
}
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) > 0){
session_start();
$_SESSION['invitation_code'] = $password;
$_SESSION['last_name'] = $doctor_last_name;
$data = array("result" => "true", "msg" => "Access Granted !!!");
echo json_encode($data);
exit();
}else {
//validation of code and lastname only
$data = array("result" => "false", "msg" => "The Last name & Invitation Code is invalid.");
echo json_encode($data);
exit();
}
}
}else{
$data = array("result" => "false", "msg" => "Parameter is required.");
echo json_encode($data);
exit;
}
reset($doctor_last_name);
reset($password);
mysqli_close($con);
exit;
?>
And Lastly you can put session validation in any header file of your WordPress theme.
session_start();
if(!isset($_SESSION['invitation_code']) || $_SESSION['invitation_code'] == '') {
header('location:home.php');
}
So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code?
add-college.php
<?php
function findDuplicate($code) {
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$sql = "SELECT * FROM colleges WHERE collegecode = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $code);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
return true;
}
else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$code = $_POST['code'];
$name = $_POST['name'];
$result = array();
if (findDuplicate($code)) {
$result['message'] = 'duplicate';
}
else {
$sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $code, $name);
if ($stmt->execute()) {
$result['message'] = 'success';
}
else {
$result['message'] = 'error';
}
}
echo json_encode($result);
}
catch (Exception $e) {
echo json_encode($result);
}
?>
script.js
$("#save-new").click(function() {
var form = $("#add-college");
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
type: "POST",
data: {
code: code,
name: name
},
url: "../ajax/add-college.php",
dataType: "html",
success: function(data) {
if (data.message = "success") {
$.notify({
// options
message: 'College has been added.'
},{
// settings
type: 'success'
});
}
else if (data.message = "duplicate") {
$.notify({
// options
message: 'College already exists.'
},{
// settings
type: 'warning'
});
}
else {
$.notify({
// options
message: 'College cannot be added.'
},{
// settings
type: 'error'
});
}
$("#code").val("");
$("#name").val("");
$("#add-new").modal('hide');
showColleges();
}
});
});
data.message = "success" this is assignment operation, if you want to compare two string use == operator.
So, the correct statement would be for the if condition would be if(data.message == "success")
Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!
I am building a website that has a reservation. I use ajax to send information from forms into the another page which insert the information into my database. To make it even useful, I want to make a test connection into my database. After a user fills up all the fields required he will click the submit button and a test connection must check first before sending the data. And when the connection fails, it will tell the user that the connection is not set(maybe his internet connection is lost, or the server itself is failing). In that way, the website prevents prompting the user that their reservation data is sent, but actually NOT.
EDITED:
Here's my running and fixed code:
$("#esubmit2").click(function(){
var event2 = document.getElementsByName("eevent2")[0].value;
var engager2 = document.getElementsByName("eengager2")[0].value;
var contact2 = document.getElementsByName("econtact2")[0].value;
var eadd2 = document.getElementsByName("eeadd2")[0].value;
var venue2 = document.getElementsByName("evenue2")[0].value;
var datein2 = document.getElementsByName("edatein2")[0].value;
var message2 = document.getElementsByName("emessage2")[0].value;
var reg2 = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(event2 == "" || event2 == " "){
$("#eevent2").focus();
return false;
}
else if(engager2 == "" || engager2 == " "){
$("#eengager2").focus();
return false;
}
else if(contact2 == "" || contact2 == " "){
$("#econtact2").focus();
return false;
}
else if(venue2 == "Venue:"){
$("#evenue2").focus();
return false;
}
else if(datein2 == "" || datein2 == " "){
$("#edatein2").focus();
return false;
}
else if(message2 == "" || datein2 == " "){
$("#emessage2").focus();
return false;
}
else if(eadd2 != ""){
if(reg2.test(eadd2) == false){
$("#eeadd2").focus();
$("#eeadd2").css("backgroundColor","#800517");
$("#eeadd2").css("color","#FFFFFF");
return false;
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
})
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string,
success: function(json) {
if(json == 1){
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").val("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
return false;
}
else{
alert("Sorry for the inconvenience but the connection to our database failed.\nPlease check you internet connection or refresh you page.\n\nIf one of the above failed please report to our admin.\nThank You.");
return false;
}
}//end success function
}); //end ajax call
return false; // IMPORTANT
}
submitreserve_eventpc.php:
if($test){
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$ok = 1;
}
else{
$ok = 0;
}
echo json_encode($ok);
If there's any improvement that you see please edit. For now this met my needs :)
You should do something like this.
Your php.file
<?php
$con=mysql_connect('localhost','root','root');
if($con){
// do insertion data here into the database
$sql = "Insert into table query";
if($sql){
echo "Data inserted successfully";
}else{
echo "Sorry! some error occured ".mysql_error();
}
}else{
echo "Unable to connect to the server";
}
?>
You could try something like this.
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string
}).done(function(data) {
data = $.parseJSON(data);
message = data.message;
if (message == "success")
{
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").text("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
$("#esubmit2").blur();
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
} else {
console.log(message);
}
});
return false; // IMPORTANT
}
In your PHP file could be changed to what is below.
$myDatabase = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$myDatabase)
{
$message = 'Could not connect: ' . mysql_error();
} else {
$event2 = $_POST['eevent2'];
$engager2 = $_POST['eengager2'];
$contact2 = $_POST['econtact2'];
$eadd2 = $_POST['eeadd2'];
$venue2 = $_POST['evenue2'];
$datein2 = $_POST['edatein2'];
$message2 = $_POST['emessage2'];
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done
I have tried using the following code. But it is not working. I have a temporary sqllite table, I need to insert all data from temporary database to remote mysql server.
var url = "http://bmcagro.com/manoj/insertopinion.php";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this.responseText holds the raw text return of the message (used for JSON)
// this.responseXML holds any returned XML (used for SOAP web services)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == "true") {
var newtoast = Titanium.UI.createNotification({
duration: 1000,
message: "Inserted"
});
newtoast.show();
} else {
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "False"
});
toast.show();
}
},
onerror: function(e) {
Ti.API.debug(e.error);
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "Error in Connection!!"
});
toast.show();
},
timeout:5000 });
xhr.open("POST", url);
xhr.send({names: names});
});
and the php code is
<?php
$con = mysql_connect("MysqlSample.db.8189976.hostedresource.com","MysqlSample","xszZ#123ddlj");
if (!$con) {
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db("MysqlSample",$con);
if (!$db) {
echo "Failed to select db.";
exit;
}
$names = $_POST['names'];
foreach ($names as $name) {
mysql_query("INSERT INTO seekopinion(uid,gid,opiniondescription,date,postedto) VALUES (" + $name.gid + "," + $name.tempid + "," + $name.gid + ",NOW()," + $name.gid + ")");
}
if($query) {
$sql = "SELECT * FROM MysqlSample.seekopinion";
$q= mysql_query($sql);
$row = mysql_fetch_array($q);
$response = array(
'logged' => true,
'seekopinion' => $row['seekopinion']
);
echo json_encode($response);
} else {
$response = array(
'logged' => false,
'message' => 'User with same name exists!!'
);
echo json_encode($response);
}
?>
actually iam a beginer in php as well as titanium...anybody pls help me out.
Finally i found a way out ....
I changed the entire row to a string using delimiter '-' in appcelerator and then passed the parameter to the php code...from where the code is split using explode and then inserted using for loop
the appcelerator code for posting a table from an sqllite database to mysql database..
postbutton.addEventListener('click', function(e)
{
var names = [];
var datarow ="";
var db = Ti.Database.open('weather');
var rows = db.execute('SELECT tempid,gid,name,email FROM postedto');
while (rows.isValidRow())
{
datarow=datarow+"-"+rows.fieldByName('tempid')
rows.next();
}
db.close();
var params = {
"uid": Ti.App.userid,
"opiniondescription": question2.text,
"database": datarow.toString()
};
var url = "http://asdf.com/as/asd.php";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this.responseText holds the raw text return of the message (used for JSON)
// this.responseXML holds any returned XML (used for SOAP web services)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged ==true)
{
var seekopinion11=require('seekopinion2');
var seekop11 = new seekopinion11();
var newWindow = Ti.UI.createWindow({
//fullscreen : true,
backgroundImage : 'images/background.jpg',
});
newWindow.add(seekop11);
newWindow.open({
//animated : true
});
}
else
{
var toast = Titanium.UI.createNotification({
duration: 2000,
message: response.message
});
toast.show();
}
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "There was an error retrieving data.Please try again"
});
toast.show();
},
timeout:5000
});
xhr.open("GET", url);
xhr.send(params);
});
the php code for breaking the string using explode
<?php
$con = mysql_connect("MysqlSample.db.hostedresource.com","MysqlSample","xszZ#");
if (!$con)
{
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db("MysqlSample",$con);
if (!$db)
{
echo "Failed to select db.";
exit;
}
$uid= $_GET['uid'];
$opiniondescription= $_GET['opiniondescription'];
$database= $_GET['database'];
$insert = "INSERT INTO seekopinion(uid,opiniondescription,date) VALUES ('$uid','$opiniondescription',NOW())";
$query= mysql_query($insert);
$rows = explode("-", $database);
$arrlength=count($rows);
for($x=0;$x<$arrlength;$x++)
{
$insert = "INSERT INTO seekopinionuser(sid,postedto) VALUES ((SELECT MAX(sid) FROM seekopinion),$rows[$x])";
$query= mysql_query($insert);
}
if($query)
{
$sql = "SELECT s.sid,s.opiniondescription,s.uid,u.postedto FROM seekopinion s left join seekopinionuser u on s.sid=u.sid WHERE uid=$uid AND s.sid=(SELECT MAX(sid) FROM seekopinion) ";
$q= mysql_query($sql);
$row = mysql_fetch_array($q);
$response = array(
'logged' => true,
'opiniondescription' => $row['opiniondescription'],
'uid' => $row['uid'] ,
'sid'=>$row['sid']
);
echo json_encode($response);
}
else
{
$response = array(
'logged' => false,
'message' => 'Seek opinion insertion failed!!'
);
echo json_encode($response);
}
?>
I want to be able to set the following:
1) If the email already exists to return an error
2) If successful to return an error
3) if error to return error
At the moment it works, but allows you to add same email address and sends successful response but need to add one for existing email
$('form').submit(function(){
// check if passwords match; you might want to do more thorough validation
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
} else if(hasError == false) {
// make ajax post request and store the response in "response" variable
$.post('submit.php', $(this).serialize(), function(response){
// process response here (assume JSON object has boolean property "ok"
if(response.ok==true){
// sweet, it worked!
alert('OK!');
}else{
// handle error
alert('Ooops');
}
}, 'json');
}
// stop the form from being submitted
return false;
});
And the php is:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","root",""); //Replace with your actual MySQL DB Username and Password
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("table", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['firstname']);
$last_name=mysql_real_escape_string($_POST['lastname']);
$email=mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
echo "The form data was successfully added to your database.";
mysql_close($con);
?>
Thanks!
$sql="SELECT email FROM email_list WHERE email = '$email'";
$result = mysql_query($sql, $con) or die('Error: ' . mysql_error());
if (mysql_num_rows($result) > 0)
{
// Error - Email already exists
echo "Error: The email address already exists.";
} else {
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
echo "The form data was successfully added to your database.";
}
mysql_close($con);
I have added a check to see if the email address already exists, and output an error if it does. There are also error outputs for mysql errors.
If you need the output to be formatted in a certain way, use JSON. But the above should get you started.
Just check for the email in the db before u add.
Hope This Helps.
<?php
$first_name=mysql_real_escape_string($_POST['firstname']);
$last_name=mysql_real_escape_string($_POST['lastname']);
$email=mysql_real_escape_string($_POST['email']);
$sql = "SELECT * FROM email_list WHERE `email`='$email'";
$res= #mysql_query($sql);
if(#mysql_num_rows($res)>0)
{
echo "Email Already Exists" ;
}
else
{
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
echo "The form data was successfully added to your database.";
}
?>
jquery
$('form').submit(function(){
// check if passwords match; you might want to do more thorough validation
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
} else if(hasError == false) {
// make ajax post request and store the response in "response" variable
$.post('submit.php', $(this).serialize(), function(response){
// process response here (assume JSON object has boolean property "ok"
if(response.ok=='0'){
alert('required fields empty');
}else if(response.ok=='1'){
alert('email already exists');
}
else if(response.ok=='2')
{
alert('thankyou for your input');
}
}, 'json');
}
// stop the form from being submitted
return false;
});
php code
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","root",""); //Replace with your actual MySQL DB Username and Password
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("table", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['firstname']);
$last_name=mysql_real_escape_string($_POST['lastname']);
$email=mysql_real_escape_string($_POST['email']);
if(empty($first_name) || empty($last_name) || empty($email) ) {
echo json_encode( array('ok'=> '0' ) );
exit();
}
$sql="Select * from email_list where email='".$email."' ";
$sqll=mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$data=mysql_fetch_array($sqll);
if($data['email']) {
echo json_encode( array('ok'=> '1' ) );
exit();
}
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$value = mysql_insert_id() > 0;
if($value)
echo json_encode( array('ok'=> '2' ) );
mysql_close($con);
exit();
?>
just add following line in end of you php file
$value = mysql_insert_id() > 0;
echo json_encode( array('ok'=> $value ) );