I have sent an email address via an ajax post from javascript to php. I have then searched the database in php to find out if this email exists in the database. How can i then send a message back to the javascript/html to say that the value was present?
This is what I used to send the request:
function postEmail(){
var checkEmail = "someone#gmail.com";
var dataString = 'checkEmail1='+ checkEmail;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "myfile.php",
data: dataString,
cache: false,
success: function(result){
alert("Sent successfully");
}
});
}
and then in the PHP:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
if ($row == 0 ) {
echo "email doesnt exist";
}
}
Not sure if I should do a get request? Or if you return values or something. Thanks.
(p.s, Im developing a hybrid app so need to use JSON to send/retrieve from PHP)
I think you need to remove second condition! output json or any other format you want. I use json_encode for arrays
try:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
echo "email doesnt exist";
}
JAVASCRIPT
from your success function, print the result to the console to see the output
console.log(result);
What you echo from the PHP script is sent back to the success function in the javascript, as the result parameter. So the result parameter will contain "email already exists" or "email doesnt exist"
Related
I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js
I tried researching a lot before posting here.
There are two files login.php and login-validation.php
Login.php file contains code including login form and jQuery AJAX script to call login.validation.php
--- Code of login.php ---
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
mobile_no = $('#mobile_no').val();
upassword = $('#upassword').val();
console.log(mobile_no, upassword);
$.ajax({
type: "POST",
url: "server/login-validation.php",
data: {
Mobile_no: mobile_no,
Password: upassword
},
cache: false,
dataType:'json',
success: function(response) {
console.log("Data gone successfully");
if(response["type"] == 'LoginSuccess'){
$('#success-message').text(response); // This works but not below ones
}
if(response["type"] == 'WrongCredentials'){
$('#success-message').text(response);
}
else{
$('#success-message').text(response);
}
},
error: function(xhr, textStatus, errorThrown){
console.log(xhr.responseText); Shows my echo message i.e. Wrong credentials for wrong credentials
console.log(textStatus); // Shows parseError
console.log(errorThrown); // Shows SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
}
});
});
});
</script>
---Code of login.validation.php---
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
echo "Wrong credentials". $mysqlconnect->error;
}
}
else{
$message["type"] = 'WrongMobile';
echo "Mobile number doesn't exists";
}
header('Content-type: application/json');
echo json_encode($message);
?>
Tried dataType: 'json' - Didn't work
Tried without dataType - Didn't work
Php script is running properly with right error messages for different "if" statements but AJAX responses goes to error:function() rather than success: function()
In the network tab - The response type is JSON and it displays [type] i.e [WrongCredentials]
Not understanding what is wrong here. Any help would be appreciated.
You need to parse the JSON response using jQuery.parseJSON()
var data = jQuery.parseJSON(response);
Now, you can check it
if(data.type == "LoginSuccess"){
// do something
}elseif(data.type == "Wrong Password"){
// do something else
}
And remove echo from your php code
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
}
}
else{
$message["type"] = 'WrongMobile';
}
header('Content-type: application/json');
echo json_encode($message);
?>
How do I convert Ajax response into plain text string?I have global variable and I store the ajax response to it but when I'm going to compare it with javascript string when even they are equal It returns false.
Here is my code:
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
myGlobalContainer.usn = response; //convert it to compare with string
$('#status').html(response);
}
});
}
}
in console when I type the existing username in database it logs OK. This OK stores in myGlobalContainer.usn, but when I do comparison like code below it return false.
if(myGlobalContainer.usn == "OK"){
return true;
}else{
return false;
}
I will add php file.
<?php
header("Content-Type: text/plain");
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if(isset($_POST['emp_username'])){
$usn = $_POST['emp_username'];
$checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0){
echo "OK";
}else{
echo "Your Username not exist";
}
exit();
}
if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
$pw = $_POST['emp_pw'];
$usn = $_POST['emp_usn'];
$get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $get_pw);
//$get_num_rows = mysqli_num_rows($query);
//echo $get_num_rows;
$row = mysqli_fetch_assoc($query);
//echo $row["emp_password"];
// check if password is match with username
if($pw == $row["emp_password"]){
echo "MATCH";
}else{
echo "Wrong password";
}
exit();
}
?>
Please help Thanks!
By default, jQuery's ajax function will determine the type of data it is receiving from the Content-Type response header.
You can override that with the dataType parameter.
$.ajax({
dataType: "text",
// etc etc
});
… however, since the response seems to be "OK" and not HTML, it is likely that your PHP should be adjusted so it outputs the correct Content-Type:
<?php
header("Content-Type: text/plain"); # Override the default (text/html)
echo "OK";
So also make sure that the response is really simply "OK" and that you are not outputting (for example) "OK" followed by a new line.
I've change my code to
success: function(response){
console.log(response);
myGlobalContainer.usn = response.trim(); //convert it to compare with string
$('#status').html(response);
and It works but Guys thanks for your help very appreciated!
also thanks to this question
Ajax response doesn't equal what I think it should
i seem you should use a function in ajax success.
var myGlobalContainer.usn = "";
function signAndCompare(str)
{
myGlobalContainer.usn = str
if(myGlobalContainer.usn == "OK")
{
console.log("true");
return true;
}
console.log("false");
return false;
}
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
signAndCompare(response);//this line: **compare** and sign response
$('#status').html(response);
}
});
}
I am currently handling a form with php and calling it via an ajax request, i want to handle exceptions showing a small div instead of the basic popup
so i did multiple if conditions based on the responsetext, however one of the exceptions doesnt get handled
This exception is the empty fields exception it always shows the wrong username or pw instead
here is the ajax call
function sendLogin(){
username = $('#loginEmail').val();
password = $('#loginPassword').val();
a = $.ajax({
type: 'post',
data: 'username='+username+'&password='+password,
url: '/account/login.php',
async: false,
});
if(a.responseText == "LoggedIn"){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeOut("fast");
$("#LoggedIn").fadeIn("fast");
setTimeout(location.reload(),2200);
}
else if(a.responseText == "Empty_Fields") {
//alert(a.responseText);
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeIn("fast");
}
else if(a.responseText == "Wrong_Credentials") {
//alert(a.responseText);
$("#Empty_Error").fadeOut("fast");
$("#WrongPW_Error").fadeIn("fast");
}
}
and here is the php file
<?php
if(!isset($_POST['username']) || !isset($_POST['password'])){
echo "Empty_Fields";
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$hashed_pass = hash("sha512", $password);
$stmt = $dbh->prepare("SELECT Count(email)as total, username from Users where email = :username and password= :password");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $hashed_pass, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total = $row['total'];
if($total == 1){
session_start();
$_SESSION['user'] = $username;
$_SESSION['user_name'] = $row['username'];
echo "LoggedIn";
die();
}
else{
echo "Wrong_Credentials";
die();
}
?>
You are not performing the correct check in PHP to see if the POST variables are empty.
Read: What's the difference between 'isset()' and '!empty()' in PHP?
isset($_POST['username'])
will return true if the POST parameter exists, even if its content is an empty string. You need both tests: isset AND empty.
if(!isset($_POST['username']) || !isset($_POST['password'])){
echo "Missing_Param";
die();
}
if(empty($_POST['username']) || empty($_POST['password'])){
echo "Empty_Fields";
die();
}
Edit: I did not notice that you're using async: false; leaving this answer for reference. In general it's a good idea to use non-blocking calls in JS so other UI elements aren't affected.
$.ajax does not return anything; it's an asynchronous call that will call a function when it completes. You'll need to do something like this:
$.ajax({
// other arguments here
success: function(data) {
// handle success
},
error: function() {
// handle error
}
});
More examples available here and here.
Instead of calling die() on your PHP code, send an error response. Call http_response_code(401) (not authorized response). Second issue is that $.ajax doesn't return a response and async = false has been deprecated and should not be used. Instead, define two functions for success and failure and just set those as the success and error parameters of your AJAX request.
$.ajax({
type: 'post',
data: 'username='+username+'&password='+password,
url: '/account/login.php',
async: false,
success: successFunction,
error: errorFunction
});
function successFunction(response){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeOut("fast");
$("#LoggedIn").fadeIn("fast");
setTimeout(location.reload(),2200);
}
function errorFunction(response){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeIn("fast");
}
I am using ajax to submit a login form in Yii. Here is my ajax function:
$("#login-form").submit(function() {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin",
type: "post",
data: "email=" + email + "&password=" + password,
success: function(response) {
if (response === "1") {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
}
else
{
//Dispaly response errors above login form
}
},
error: function() {
alert("Could not perform the requested operation due to some error.");
return false;
}
});
});
My PHP controller function is validatelogin as follows:
$email = $_POST['email'];
$password = $_POST['password'];
$model = new LoginForm();
$model->email = $email;
$model->password = $password;
if ($model->validate() && $model->login()) {
echo "1";
} else {
print_r($model->getErrors());
}
If the user enters correct credentials I send 1 as response to view and user is redirected to dashboard.
But if user enters incorrect credentials then different errors are received in ajax response depending upon the type of error.
I want to display those errors above login form in else part of success function through a loop.
But when I run the loop over response then that array has very large length i.e for example if the error in response was "Incorrect password" then the response array has length of 18(the number of characters) in the error message. In short the response array is like:
array('I','n','c','o','r','r'....)
rather than
array([0]=>"Incorrect password")
How do I convert response array in the latter format and iterate over each index to display error message to the user above the login form?
Encode it to JSON.
In your php:
echo json_encode($model->getErrors());
In your js (in the else):
var errors = $.parseJSON(response);
Edit:
In your case it would be better to always return JSON.
Your JS could be changed to:
var jqxhr = $.post("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
email: email,
password: password
}, 'json');
jqxhr.done(function(response) {
if (response.valid) {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
} else {
if (response.errors) {
...
}
}
});
jqxhr.error(function(response) {
alert("Could not perform the requested operation due to some error.");
});
Your PHP:
$response = array('valid' => false);
if ($model->validate() && $model->login()) {
$response['valid'] = true;
} else {
$response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);
In addition to #sroes's answer, use Yii library for JSON
echo CJSON::encode($response);
instead of
echo json_encode($response);
why ?
Why use CJSON encode when we have json_encode