Not able to make Ajax request to PHP file - php

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.

Related

Trying to see if an email is not a duplicate

I've tried to verify if an email already exists in the database.
The same system worked perfectly if I tried to verify a username.
I'm using AJAX and PHP.
This is the file that gets the $_POST variables.
<?php
require_once 'Config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
$password = $_POST['password'];
if (!empty($password) and !empty($email)) {
$notEmpty = true;
include 'validate.php';
if($notEmpty == true and validateEmail($email) == true){
$password = md5($password);
$stmt = $link->prepare("INSERT INTO `Users`(`user_password`, `user_email`) VALUES (?,?)");
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
}
}else{
$notEmpty == false;
}
}
?>
and this is the file that verifies the email doesn't exist on the database.
function validateEmail($user_email){
include '../Backend/Config.php';
$sql = "SELECT `user_password`, `user_email` FROM `Users` WHERE `user_email` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("s",$user_email);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
echo 1;
return false;
}
else{
// echo json_encode(array('status' => 'OK'));
echo 0;
return true;
}
}
Js code(ajax):
$('#form').submit(function(e) {
//Don't refresh the page
e.preventDefault();
//Collecting data for the server call
post_data = {
'email' : $('input[name=email]').val(),
'password': $('input[name=password]').val()
};
//AJAX server call to signup.php,which calls validate.php
$.ajax({
method: "POST",
url: "../Backend/signup.php",
data: post_data
})
//Server response and setting the input values to ""
.then(function( msg ) {
if(msg == 0){
console.log("Success, user data inserted. Code: " + msg);
}
//Failed
if(msg == 1){
console.log("Inserting failed. Error code:" + msg);
document.getElementById("error").innerHTML = "This email already exists.";
}
$('input[name=email]').val("");
$('input[name=password]').val("");
});
});
It inserts it anyway, what is the problem here?
If you immediately call num_rows() after executing a prepared statement, it will usually return 0 as it has no way to know how many rows are in the result set, since the result set is not saved in memory yet. You must first call store_result() to buffer the results so that the subsequent call to num_rows() will contain the correct results.
This is explained in the "User Notes" section at the bottom of the PHP documentation for num_rows().

Call to MySQL SP from Ajax/PHP returns null-ish values

I've been pounding on this for a few days, so time to ask for help. I'm trying to use Ajax/PHP/MySQL to show only a subset of a table based on the user's selections in dropdown. The PHP code calls a MySQL stored procedure. The call I'm constructing is right, and if I echo it out and then copy it and run it as is from the phpMyAdmin MySQL console, I get exactly the results I expect. But from the PHP code that's called by Ajax, I instead see this result (echoed in Firebug, after I JSON_encode it):
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
The relevant part of the page itself is:
<script>
function updateActions() {
var results = '';
var success = false;
var selectedIssues = getIssues();
var fnargs = "GetActions|'" + selectedIssues + "'";
$.ajax({
url: 'retrievedata.php',
type: "POST",
async:false,
data: {"functionname":"getactions", "arguments":fnargs},
dataType: "JSON",
complete: function (obj, textStatus) {
if( (obj.error != '') ) {
alert(JSON.parse(obj));
$("#testresult").text(textStatus);
}
else {
$("#testresult").text("Error");
// console.log(obj.error);
}
success = true;
},
error: function(textStatus, errorThrown) {
success = false;
$("#testresult").text('Error occurred: '.textStatus);
}
})
};
</script>
Two notes. First, the getIssues script it calls returns the expected value. Second, I haven't actually written the right code to process the result once I get it. Still trying to get the right result back to the page.
Page retrievedata.php looks like this:
<?php
include "dbfns.php";
$aResult = array();
$returnval = 'before tests';
if( !isset($_POST['functionname']) ) {
$aResult['error'] = 'No function name!';
}
if( !isset($_POST['arguments']) ) {
$aResult['error'] = 'No function arguments!';
}
if( !isset($aResult['error']) ) {
$functionName = $_POST['functionname'];
$argsarray = explode('|', $_POST['arguments']);
$argcount = count($argsarray);
$returnval = 'before switch';
switch($_POST['functionname']) {
case 'getactions':
if( $argcount < 2 ) {
$returnval = 'too few arguments';
}
else {
$returnval = 'in else';
$returnval = getactions($argsarray[0], $argsarray[1]);
}
break;
default:
$returnval = 'function not found';
break;
}
}
return $returnval;
?>
The relevant portions of dbfns.php (with identifying data and credentials removed, of course) are:
<?php
function connect2db() {
$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$database = "XXX";
$conn = mysqli_connect($hostname, $username, $password, $database);
if( $conn == false ) {
echo "Connection could not be established.<br />";
die( print_r( myslqi_connect_error(), true));
}
return $conn;
}
function getactions($spname, $params, $errorstring = 'Unable to retrieve requested data') {
$conn = connect2db();
$query = "CALL ".$spname."(".$params.")";
echo $query."\r\n";
$result = mysqli_query($conn, $query);
if ($result == false) {
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
echo "In else case\r\n";
$allresult = json_encode($result);
}
echo $allresult;
return $allresult;
}
?>
I have another PHP function in retrievedata that calls the same MySQL SP, but not from Ajax and it returns the expected result, so I'm pretty confident that the SP does what I expect.
I think there must be something I don't get about how to do all this from Ajax.
Edit: Just want to add that I've tried success rather than complete in the ajax call, and _GET rather than _POST. No change in results.
That looks like it's serializing the result object from mysqli_query(). I'm not sure what it does internally, but it may not return the actual resulting data until you enumerate/fetch the results.
See this example on one way to convert it to a JSON result.

ajax error handling / show error if mysql result is false?

I have a form where a user can input a voucher code:
<form>
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
the user can click on my div 'promo_check' which runs the following ajax:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
$.ajax({
type: "POST",
url: "process_promo.php",
data: {data:promo},
success: function(data)
{
window.alert(data);
}
});
});
});
</script>
this then executes my mysql query to check if the voucher exists in the database and that the $_SESSION['user_name'] / i.e. the logged in user has the permission to use that voucher.
process_promo.php:
<?php
$username = "mark";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$_SESSION['username'] = 'mark';
$promo = $_POST['data'];
$query = "SELECT * FROM hewden1.supplier_users WHERE promo_code = '$promo'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (mysql_num_rows($result) > 0) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}else{
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
} }
}else{
echo 'error';
}
}
?>
this all works fine, if the voucher code matches for that user then it echo's 'correct' and my ajax will show an alert saying 'correct'. Then if the voucher code does not match for the user then it echo's 'not correct for user'.
The problem i have is when the voucher is not valid at all and cannot be found in the database it is suppose to echo 'error' however ajax show a blank/empty alert message instead of showing 'error'.
I think this is because i am using success: in my ajax but when i try to add an error: call back my script stops working. can someone please show me what i'm doing wrong? thanks in advance
Looking at process_promo.php, if you get no result from the database query, then the contents of the while loop never get executed. Putting it another way, inside the while loop you'll never have a mysql_num_rows($result) == 0 condition.
Here I moved your while loop inside your mysql_num_rows check:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}
else {
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
}
}
}
}
else {
echo 'error';
}
...which also pulls the error report outside the while loop and gives it a chance to execute.

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

PHP AJAX Responses, how can i add different conditions?

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

Categories