PHP AJAX Responses, how can i add different conditions? - php

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

Related

inserting data into database table issue

i wanna make register form.But i cant insert datas into my db table "yeni"
and get "Error....!!".I really need to solve this problem guys pls help me.
http://i.stack.imgur.com/SoCNK.png
registration.js
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var tc = $("#tc").val();
var tel = $("#tel").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || tc == '' || tel == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
}
else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
}
else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
}
else {
$.post("sign.php", {
name1: name,
tc1:tc,
tel1: tel,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
sign.php
<?php
$connection = #mysql_connect("localhost", "root", "");
$db = mysql_select_db("babo", $connection);
$name = $_POST['name1']; // Fetching Values from URL.
$tc = $_POST['tc1'];
$tel = $_POST['tel1'];
$password = sha1($_POST['password1']);
$query = mysql_query("insert into yeni(adi, tc_no, password, tel) values ('$name', '$tc', '$password', '$tel')");
if($query) {
echo "You have Successfully Registered.....";
} else {
echo "Error....!!";
}
mysql_close ($connection);
?>
As allready suggested use mysqli_ function in favor of mysql_ functions
You should use prepered statements
To get a better starting point on whats actually wrong replace echo "Error....!!"; with echo mysqli_error($connection);

Not able to make Ajax request to PHP file

I'm using the following code to send Ajax request to a PHP file:
var d = "email=" + email + "&password=" + password;
$.ajax({
url: "login/c_login_form.php",
data: d,
type: "POST",
success: function(str) {
if ( str === "#" ) { //# means success
alert("Login successful!");
return;
}
else {
//login failed
alert("Error logging in: " + str);
return;
}
},
error: function(obj) {
alert("Failed to send Ajax request.");
return;
}
});
The contents of the PHP file are:
<?php
/*
*
* The controller file for login form
*
*/
if( isset( $_POST["email"] ) && isset( $_POST["password"] )) {
$email = $_POST["email"];
$password = $_POST["password"];
//load the config file to read settings
require_once($_SERVER['DOCUMENT_ROOT'] . '/hrms/lib/config.php');
//connect to database
$conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if(!$conn) {
echo "Can't connect to database";
return;
}
//check if employee is active
$query = "SELECT employee.emp_id, role, is_active FROM employee INNER JOIN user ON employee.emp_id = user.emp_id WHERE email_bb = '{$email}' AND password = '{$password}'";
if( $query === FALSE ) {
echo "Failed to query database.";
return;
}
$result = mysqli_query($conn, $query);
if( $result === false ) {
echo "No such user exists. Please re-check login details.";
return;
}
$row = mysqli_fetch_assoc($result);
if( (count($row) > 0 ) and ($row['is_active'] == "0") ) {
echo "Employee not active anymore. Please contact HR.";
return;
}
if( count($row) === 3 ) {
//Everything looks okay. Process login now.
$emp_id = $row['emp_id'];
$role = $row['role'];
//close connection
mysqli_close($conn);
session_start();
$_SESSION['emp_id'] = $emp_id;
echo "#";
$path = $_SERVER['DOCUMENT_ROOT'] . '/hrms/dashboard.php?role={$role}';
header("Location://{path}");
die();
}
}
else {
echo "Error. POST is not set.";
return;
}
Strangely enough, if I make the first two statements in the PHP file to be echo "#"; return; then I'm able to see the "Login successful" message. Otherwise, even when I send the correct query (verified in phpMyAdmin), I keep getting the error saying "Failed to send Ajax request".
Any idea what might be causing it?
Posting an answer so as to close this question. The problem was indeed related to headers already being sent, as I was using the echo and header functionalities in the same place. When I removed the header part and performed the redirection from JavaScript, it worked as expected.

check database connection after button is click

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','$message‌​2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done

Ajax and PHP with database connection

i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // 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
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.

Preventing Duplicate Entries - Ajax Not returning error. PHP MySQL jQuery

I'm trying to prevent duplicate entires in my DB for a newsletter submissions form. I'm successfully preventing the duplicate entries, but I haven't been able to revise my the jQuery to print the error. I've included the PHP just incase I'm missing something there... Any help would be appreciated!
jQuery:
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
success: function() {
$('#newsletterForm').html("<div id='success-message'></div>");
$('#success-message').html("<p><strong>Thank you.</strong> <br/>You've been added to our list and will hear from us soon!</p>");
},
error: function() {
$('#newsletterForm').html("<div id='success-message'></div>");
$('#success-message').html("<p><strong>That email already exists.</strong> <br/>Please enter another email address.</p>");
}
});
}
PHP:
if(isset($_POST['submit'])) {
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(!isset($hasError)) {
$con = mysql_connect("xxx.xxx.xxx.xxx","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$query = "SELECT COUNT(id) AS mycount FROM newsletter WHERE email = '$email'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if($row['mycount'] == 0) {
$query = "INSERT INTO newsletter (email,dt) VALUES ('$email',NOW())";
mysql_query($query) or die ("Error writing to database");
} else {
echo "I'm sorry our database already contains that email address. Please use a new email address to continue.";
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
}
}
The error only gets called if your AJAX request fails (such as a 404).
Inside your success: function() { } you'll need to determine if what your PHP script returned was a success message, or error message. The easiest way to do this is with JSON instead of plain text.
To do this, in your PHP instead of echoing a string, do..
echo json_encode(array('result'=>'success','response'=>'Everything worked');
or..
echo json_encode(array('result'=>'error','response'=>'Already exists');
Then in your ajax, set the dataType to 'json' and in your success function, you can then access the JSON as an object.
Instead of echoing out the messages, why can't you just print out a JSON representation of what happened? This will allow you to directly manipulate the object in JavaScript.
Remember: jQuery is not a language.

Categories