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");
}
Related
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 trying to build an costum login to Wordpress in a AJAX call. I a remove the wp_signon() from the PHP function I do get the right echo. But then I add the wp_signon() it always return my whole login page in HTML. I can't see what I am doing wrong. And can't get the login to work.
Please help!
js
$.ajax({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
'action': 'getLoggedIn',
'user_name': user_name,
'user_password': user_password,
'user_remember': user_remember
},
success: function(response) {
if (response === 'ok') {
window.location = '/app/';
}
},
error: function(){}
});
PHP
function getLoggedIn() {
global $wpdb;
// Check if users is already logged in
if ( is_user_logged_in() ) {
echo 'You are already logged in';
die;
}
//We shall SQL escape all inputs
$username = $wpdb->escape($_REQUEST['user_name']);
$password = $wpdb->escape($_REQUEST['user_password']);
$remember = $wpdb->escape($_REQUEST['user_remember']);
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = $remember;
$user_signon = wp_signon( $creds, false );
// Check if error
if ( is_wp_error($user_signon)) {
echo $user_verify->get_error_code();
exit();
} else {
echo 'ok';
exit;
}
die();
}
add_action('wp_ajax_getLoggedIn', 'getLoggedIn');
add_action('wp_ajax_nopriv_getLoggedIn', 'getLoggedIn');
The problem was not the wp_signon() function. It was an other Wordpress action that redirects the page after user login has failed. This:
add_action( 'wp_login_failed', 'login_failed' );
I got caught up in the same situation. did you remove that wp_login_failed action or how did you work this out?
i have a form with some text inputs, then i have an ajax event to send this value via POST to my database php script, the issue is that i dont know how to send special chars from my ajax event, if the string has ' " \ or similar chars, it wont insert data to my database, but if the string only contains Numbers/Letters and no special chars...i can insert the data without a problem.
Ajax event
$$("#message").click(function(e) {
var nick_ = window.localStorage.getItem("username");
var message_ = $.trim(($("#msgtext").val()).replace(/(\r\n|\n|\r)/gm,""));
if (message_ .length>0 && message_ .length<=500)
$.ajax({type: "POST",
url: "insert.php",
data: ({nick: nick_, mensaje: message_ }),
cache: false,
dataType: "json",
success: function(data) {
if(data.status == 'success'){
$('input[type=text], textarea').val('');
}
}});
else myApp.alert('Min:1 Max:500','Chars:');
});
And this is my database script
<?php
//jSON
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
//Connect to DB
include('con.php');
//POST vars
$nick=htmlspecialchars(trim($_POST['nick']));
$message=htmlspecialchars(trim($_POST['mensaje']));
$date=date("Y-m-d H:i:s");
//DB insert
$mysqli->real_query("INSERT INTO messages VALUES ('0','$nick','$message','$date')");
if ($mysqli) $response_array['status'] = 'success';
else
$response_array['status'] = 'error';
echo json_encode($response_array);
?>
before sending your data ({nick: nick_, mensaje: message_ }) in ajax, you can verify it using:
function isValid(data){
for (i in data){
if(!data[i].match(/^[a-zA-Z0-9]*$/))
return false;
}
return true;
}
use it like:
isValid({nick: nick_, mensaje: message_ })
this will return true if the data is either letter or character, and false otherwise.
Moreover, you should not be relying on any client side script for this kind of validation.
The problem is in your php script. Try this
$v = trim($_POST['mensaje']);
$message = htmlspecialchars($conn->escape_string($v));
All i did is to escape the post value.
And also the way you are checking if your query was sucessfull should be changed. you are checking the conn object instead of catching a return boolean value from the $conn->real_query () which should give you the real outcome of your query processing (True of false).
$result = $conn->real_query("........);
if ($result){
//do something
}else{
echo $conn->error;
}
If you have a form you can try data:$(this).serializeArray() which escapes those characters
OR
You can use an editor which I would recommend something like tinyMCE.
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"
I am trying to submit a form via ajax but it doesn't let me:
Ajax - samepage
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe'},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
HTML - same page
<form class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail" >
<input type="submit" id="ssub" value="Subscribe">
</form>
PHP - common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ($sname, $email, 0)");
echo "You have been subscribed";
}
?>
EDIT added dbconn
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
In the console I get nothing. After I click submit and check the console. I can see in red how is actioning common-functions.php but doesn't do anything. Please help.
TL;DR You need to do six things to fix the problems in the code you have provided. There are pitfalls with event propagation, scoping, and variable validation.
First, add this to your JavaScript: event.preventDefault(); event.stopPropagation();.
Second, submit your actual data.
Example showing these fixes:
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
Third, actually call subscribe().
Fourth, you have a scoping problem: $db is a global, but you don't refer to it as one. That's why I added global $db; below.
Fifth, check the existence of your POST values.
Sixth, put quotes around your database values and escape them first.
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($sname)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
NOTE: This just shows how to fix the code that you have posted. The code in the question, however, is wide open to SQL injection. You really should use prepared statements instead of relying on escaping of special characters.
You have to include the data youre accessing via Post in PHP in the data object in the $.ajax call:
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#name").val()
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
Also your PHP function subscribe doesnt get called just by setting action:"subscribe"
You have to check wheter $_POST["action"] is "subscribe":
if($_POST["action"]=="subscribe")
{
subscribe();
}