I am not able to get response in angular js $http.post - php

I want to check whether the email id already exists in the db. If the email id exists, it should return false, else true. I'm not able to get the response. I've attached the controller code and the php code. [the variable validUser is undefined]
Controller.js
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
});
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
}
}
});
checkUser.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "user_details");
//$data = json_decode(file_get_contents("php://input"));
//$email = mysql_real_escape_string($data->email);
$email = $_POST['email'];
$result = $conn->query("SELECT count(*) as count from user where email='$email'");
$outp = "";
$rs = $result->fetch_array(MYSQLI_ASSOC)
if ($rs['count']==0)
{
$outp ="true";
}
else
{
$outp ="false";
}
$conn->close();
echo($outp);
?>

You're not checking the response in the correct place, or rather - at the correct time.
$http.post returns immediately. Your .then callback is called when the response is returned from the server. The code after the call to post (your if statements) is executed right after $http.post returns, and before the response is received from the server.
You should place your validation code inside your callback:
$http.post(...).then(function(response) {
validUser = response;
if(validUser==="true") {
...
} else if (validUser==="false") {
...
}
}

You're if statement needs to be inside the .then callback, otherwise you'll end up checking it before youre ajax request gets responded to
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
});
}
}
});

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().

is there any way to check ajax function return value is true or false?

i'm trying to build a signup form there i need to check that the value of load function of ajax is true or false.
i stuck in this problem here is my code
$("button").click(function(){
$("#error").load("newEmptyPHP.php",{email:mail});
})
newEmptyPHP.php
<?php
$mail=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$mail]);
if($STH->rowCount() == 1){
//echo "<script>$('#error').html('Email alreday exist')</script>";
return false;
}
else{
return true;
}
**
You know, an ajax call returns the output of a function or a script not its evaluation. I strongly suspect that you will have an empty response when you call your code by hand, and the same is for the javascript issuing the ajax request.
If your are showing all the code involved in your program and do not have any middleware to decorate your return value, you should modify your script in a way similar to this:
<?php
$mail=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$mail]);
$result = [];
if($STH->rowCount() == 1){
// echo "<script>$('#error').html('Email alreday exist')</script>";
$result["success"] = false;
$result["message"] = 'Email already exists';
} else{
$result["success"] = true;
}
// comunicate to the client that the response is json encoded
header('Content-type:application/json');
// output the response
echo json_encode($result);
The javascript part have to change too (i'm not used to jquery, take it carefully):
$("button").click(function(){
$.get("newEmptyPHP.php",{email:mail}, function(data) {
if (data.success == false) {
$('#error').html(data.message);
} else {
// do wathever you need in case of data.success
}
})
})
you must echo true or false in json format.
sth like this.
<?php
$result = array();
$mail=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$mail]);
if($STH->rowCount() == 1){
$result['status'] = false;
}
else{
$result['status'] = true;
}
echo json_encode($result);
exit(0);
?>
Edit :
you can handle response like this.
$("button").click(function(){
$("#error").load("newEmptyPHP.php",{email:mail},function(response){
result = $.parseJSON(response);
if(result.status){
//true
} else {
//false
}
});
});

How to use angularjs $resource with php script

i have question related to PHP - AngularJs, so i have simple PHP script
<?php
require_once '../../dbConnect.php';
$driverId = $_POST['driverId'];
if (isset($_POST['driverId'])) {
$sql = "delete from drivers where driver_id='$driverId'";
if ($mysqli->query($sql) === TRUE) {
echo mysqli_insert_id($mysqli);
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
At the moment i pass data to script like this
return $http({
method: 'POST',
url: '/api/drivers/deleteDriver.php',
data: $.param(driverObject),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
And i don't like that code, on other Java project i send params to end points with angularjs $resource service like this
var deleteDriverResouce = $resource('/api/drivers/deleteDriver.php');
function deleteDriver() {
deleteDriverResouce.save(driverObject);
}
And as you can see that is cleaner code and easier to use, i'm wondering can i use $resource service to pass object to php script ?
So i have found solution and i will share it here so maybe someone will need it. In order to use AngularJs $resource service you just need to make small change in PHP script, just add $object = json_decode(file_get_contents("php://input"), true); on that way you can access to object that you sent via $resource. And here is example of one working PHP script.
<?php
require_once '../dbConnect.php';
session_start();
$object = json_decode(file_get_contents("php://input"), true);
if (isset($object['email']) && isset($object['password'])) {
$email = $object['email'];
$password = $object['password'];
$query="select * from members where email='$email'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$row = mysqli_fetch_assoc($result);
if($row) {
if (password_verify($object['password'], $row['password'])) {
$_SESSION["id"] = $row['id'];
echo 'Login Success!';
} else {
session_destroy();
var_dump(http_response_code(400));
}
} else {
session_destroy();
var_dump(http_response_code(406));
}
$mysqli->close();
} else {
session_destroy();
var_dump(http_response_code(400));
}
?>
And on UI i have this simple and minimal code:
var userLoginObject = {
email: 'login#email.com',
password: 'password123'
};
var authenticationResource = $resource('/api/authentication/authenticate.php');
function logIn() {
authenticationResource.save(userLoginObject );
}
That's much better and cleaner than using ugly
return $http({
method: 'POST',
url: '/api/drivers/authenticate.php',
data: $.param(userLoginObject),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});

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

Show Error Message from Server Response

I have some problems with jqGrid.
I've added a method that validates users input. If the department exist then it will show a warning message, "Department is Exist!"
Here's my jqGrid code:
afterSubmit: function(response, postdata){
var res = $.parseJSON(response.responseText);
if (res === "1") {
return [false,"Department Already Exist"];
} else {
return [true,"Sucess"];
}
}
And my php add method:
if($oper == 'add') {
$deptid = $_POST['idms_department'];
$deptnm = $_POST['department'];
if(checkUser($deptnm) == "FALSE"){
return "1";
} else {
$ins = "INSERT INTO ms_department(department) VALUES('$deptnm')";
if(mysql_query($ins)){
"Success INSERT msDept";
} else {
die("Failed : " .mysql_error());
}
}
mysql_close();
} else .... (another operation)
The message itself is not showing. How do you use the afterSubmit method properly?
thanks
UPDATE
i've change the method to
crudMessage = function(response,postdata){
var res = response.responseText; // response text is returned from server.
if (res === "1") {
return [false,"Department Already Exist"];
} else {
return [true,"Sucess"];
}
}
then removing the afterSubmit from the jqgrid body and add this line into the jqgrid navigation:
jQuery("#departments").jqGrid('navGrid','#pager-departments',{edit:true,add:true,del:true}, {closeAfterEdit: true},{beforeShowForm: function(form) { $('#idms_department', form).hide(); },closeAfterAdd:true},{afterSubmit: crudMessage},{closeAfterSearch:true},{});
here's newest php syntax:
include 'configuration.php';
function checkDepartment($department){
$query = "SELECT department FROM ms_department WHERE department ='$department' LIMIT 1";
$result= mysql_query($query);
return mysql_num_rows($result);
}
if($oper == 'add') {
$deptid = $_POST['idms_department'];
$deptnm = $_POST['department'];
if(checkDepartment($deptnm) == 1){
echo '1';
} else {
$ins = "INSERT INTO ms_department(department) VALUES('$deptnm')";
if(mysql_query($ins)){
"Success INSERT msDept";
} else {
die("Failed : " . mysql_error());
}
}
mysql_close();
} else
if($oper == 'edit'){ ....
In your code, why are you expecting res.insertStatus? From the snippet of PHP code that you provided, it seems you would want to write:
var res = $.parseJSON(response.responseText);
if (res === "User Already Exist!") {
Or maybe I am missing something? Have you tried debugging your code?
That should explain why the alert is not appearing.
Also, for what its worth, according to the jqGrid documentation for form editing:
afterSubmit
fires after response has been received from server. Typically used to display status from server (e.g., the data is successfully saved or the save cancelled for server-side editing reasons). Receives as parameters the data returned from the request and an array of the posted values of type id=value1,value2.
When used this event should return array with the following items [success, message, new_id]where
success is a boolean value if true the process continues, if false a error message appear and all other processing is stopped. (message is ignored if success is true).
new_id can be used to set the new row id in the grid when we are in add mode.
afterSubmit : function(response, postdata)
{
…
return [success,message,new_id]
}
Based on these docs, your final code should remove the alert and just use jqGrid directly:
if (res === "User Already Exist!") {
return [false, "TODO: put your error message here"];
}

Categories