I have a working login script on another site that loads a PHP script via AJAX. I can't seem to figure out why I am getting a null response when it should either be simply false or an array of values.
When I manually put the values into the php script (hard coded) it working. I can see in the console that the variables are being sent from the form. However, nothing is being returned. Can anyone spot what I am missing?
Thanks for any help or ideas.
Login PHP
<?php
$login = $_POST['login'];
$password = $_POST['password'];
require_once("DB.php");
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$query = "SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$output = "true";
while(list($member_id, $firstname, $lastname, $login, $passwd, $City, $State, $bday, $approved, $organization, $school, $trainingdate, $Subscriber, $wscoordinator, $Position, $subdate, $enddate, $notice, $book, $trial) = mysql_fetch_row($result)) {
echo json_encode(array('memberid' => $member_id, 'firstname' => $firstname, lastname => $lastname, approved => $approved, subscriber => $Subscriber, position => $Position, school => $school, login => $login, book =>$book, ws => $wscoordinator, trial => $trial, enddate => $enddate));
}
} else {
$output = "false";
echo json_encode($output);
}
?>
AJAX, using jQuery.
$('#loginForm #loginButton').click(function(){
var $form = $('#loginForm'),
$inputs = $form.find("input"),
serializedData = $form.serialize();
var login = $('#login').text('');
var password = $('#password').text('');
$.ajax({
type: 'POST',
url: 'Scripts/php/login.php',
data: serializedData,
success: function(response){
console.log("Response: "+response);
if(response != "false")
{
//window.location.href='toolstart.html';
$.cookie('lastname', response.lastname, { expires: 365, path: '/' });
} else {
alert("Your email and password combination did not match.");
}
},
dataType: 'json'
});
(Yes, I know I need to move from MD5; just haven't gotten there yet.)
Simply replace .text(); to .val() as text() gives blank result for text input types. val() will give actual value. Secondly use var_dump($_POST); die;. Ahh...check whether your function:
$('#loginForm #loginButton').click(function(){
var $form = $('#loginForm'),
$inputs = $form.find("input"),
serializedData = $form.serialize();
var login = $('#login').text('');
var password = $('#password').text('');
$.ajax({
type: 'POST',
url: 'Scripts/php/login.php',
data: serializedData,
success: function(response){
console.log("Response: "+response);
if(response != "false")
{
//window.location.href='toolstart.html';
$.cookie('lastname', response.lastname, { expires: 365, path: '/' });
} else {
alert("Your email and password combination did not match.");
}
},
dataType: 'json'
});**});**
is missing some curly braces, as I found. Do respond with your var_dump($_POST);die; message.
After several days, I did a little more research. It turns out, the server my client is using, only supports up to PHP 5.1 and json_encode is only supported in 5.1. Found this awesome script to make it work. http://www.boutell.com/scripts/jsonwrapper.html
Thanks for all the help.
Related
I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins
Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.
I use ajax to check if it's the first time that the user logs in:
$.ajax({
url: '/checkFirstLogin.php',
type: 'post',
dataType: 'json',
data: {'user_id': userId},
success: function(data) {
if(data == 'firstTime') {
showWelcome();//this open a popup
}else{
alert('been here before');
}
},//end success
}); // end ajax call
checkFirstLogin.php simply does this:
<?php require 'core/init.php';
$user_id = filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
$myUser = new User($user_id);
$myUser->checkFirstLogin();
if($myUser){
$response = 'firstTime';
echo json_encode($response);
}else{
$response = 'beenHere';
echo json_encode($response);
}
User::checkFirstLogin():
public function checkFirstLogin(){
$sth = $this->_db->prepare("SELECT COUNT(user_id) FROM users WHERE first_login = '0' AND user_id= ? ");
$sth->bindParam(1, $this->data()->user_id, PDO::PARAM_INT);
$sth->execute();
$data_exists = ($sth->fetchColumn() > 0) ? true : false;
return $data_exists;
}
json response is always "firstTime" even when first_time = 1 in the database.
You're checking $myUser, not the actual return value of the function; what you mean to do is probably something like;
$is_new_user = $myUser->checkFirstLogin();
if($is_new_user) {
$response = 'firstTime';
...
I have been stuck with this problem for days already. I used Ajax group of web development techniques to call the php file from the server. It appears that the success method was not called. Here is my code:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#email", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://prefoparty.com/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["email"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace(main.html);
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter email and password");
}
return false;
}
In php, I used a typical MySQL call and as I run this file from Google Chrome browser. It returned the JSON correctly. Here is my php:
<?php
require_once('includes/configinc.php');
$link = mysql_connect(DB_HOSTNAME, DB_USERNAME,DB_PASSWORD) or die("Could not connect to host.");
mysql_select_db(DB_DATABASE, $link) or die("Could not find database.");
$uname = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM User_Profile WHERE Email = '$uname' AND Password = 'md5($password)'";
$result=mysql_query($sql);
$num_row = mysql_num_rows($sql);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
?>
Please check my code and point out where I did wrong.
Thank you all in advance :)
Adding
header("access-control-allow-origin: *")
to the Top of your PHP page will solve your problem of accessing cross domain request
I know I had already this question asked, but I'm doing something wrong in my code. I know that I need to use JSON, and after going through few pages I understand the theory, but somehow can't make it work here is my code once again (btw I know about my security issues and I'll work on them as soon as I solve my technical issues with JSON):
$(document).on('pageinit',function(){
$("#login").click(function(){
username=$("#usr").val();
password=$("#psw").val();
$.ajax({
type: "POST",
url: "http://imes.**********.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
success: function(html){
//in case of success
if(html=='true')
{
var usr = console.log(data.usr);
var psw = console.log(data.psw);
$.cookie('usr', usr);
$.cookie('psw', psw);
$("#login_message").html("Logged in, congratulation.");
$.mobile.changePage("http://imes.**********.com/userpanel.php");
}
//in case of error
else
{
$("#login_message").html("Wrong username or password");
}
},
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
});
return false;
});
And my php:
<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);
$res1 = mysql_query("SELECT * FROM temp_login WHERE username='$username' AND password='$password'");
$num_row = mysql_num_rows($res1);
$res2 = mysql_fetch_array($res1);
if( $num_row == 1 ) {
$arr = array('usr' => $username, 'psw' => $password);
echo json_encode($arr);
echo 'true';
}
else{
echo 'false';
}
?>
Your out put is not valid json, echoing a true or false after the json will cause it to be invalid. You have to insert the success message into the json data.
if( $num_row == 1 ) {
$arr = array('usr' => $username, 'psw' => $password);
echo json_encode(array('data'=>$arr, 'success'=>true);
//echo 'true';
}
else{
echo json_encode(array('success'=>false);
}
then check in your ajax success callback
success: function(json){
//in case of success
if(json.success){
var usr = json.data.usr;
...
}
else{
...
}
Also you should pass your parameters to data as an object so it will be properly encoded.
data: {"name":username,"pwd":password},
Here's what I would do (PHP). First setup your response array, default to success FALSE.
$arr = array('success' => FALSE);
Then your condition overwrites if successful:
if( $num_row == 1 )
{
$arr = array('success' => TRUE, 'usr' => $username, 'psw' => $password);
}
Finally at the end of the script return the result as JSON encoded data.
echo json_encode($arr);
exit();
I would make the following change to your jQuery also:
$.ajax({
type: "POST",
url: "http://imes.**********.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
dataType: 'json', // let's it know the response will be JSON formatted
success: function(json){
if (json.success === true){
// do whatever you want here
}
});
A bit of advice though: you should never pass a user's password to the front-end.There is no need for it, ever.
If it helps, JSON is basically the right-hande-side of a variable definition in JS:
var myvar = ....;
^^^^---- basically JSON
Since you're doing
echo json_encode($var);
echo 'true';
in your PHP code, consider how it'll look from the client side:
var myvar = 'somestring'true;
^^^^---syntax error
if you're outputting JSON for consumption by an AJAX call in your JS code, then the JSON text is the ONLY thing that can be output by the server as its response. Anything else will simply mangle the json string somehow, and make it invalid.