JSON setting up in php and js - php

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.

Related

Ajax cannot display json data from php. What's wrong with json format?

I have read all the related questions that reference to this topic, but still cannot find answer here. So, php and ajax works great. The problem starts when i try to include json, between php and ajax, to passing data.
here is my ajax:
function likeButton(commentId, userId, sessionUserId) {
// check if the comment belong to the session userId
if(sessionUserId == userId) {
alert("You cannot like your own comment.");
}
else if(sessionUserId != userId) {
var like_upgrade = false;
$.ajax({
url: "requests.php",
type: "POST",
dataType: "json",
data: {
keyLike: "like",
commentId: commentId,
userId: userId,
sessionUserId: sessionUserId,
like_upgrade: like_upgrade
},
success: function(data) {
var data = $.parseJSON(data);
$("#comment_body td").find("#updRow #updComLike[data-id='" +commentId+ "']").html(data.gaming_comment_like);
if(data.like_upgrade == true) {
upgradeReputation(userId);
}
}
});
}
}
Note, that i try not to include this:
var data = $.parseJSON(data);
Also i tried with diferent variable like so:
var response = $.parseJSON(data);
and also tried this format:
var data = jQuery.parseJSON(data);
None of these worked.
here is requests.php file:
if(isset($_POST['keyLike'])) {
if($_POST['keyLike'] == "like") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sessionUserId = $_POST['sessionUserId'];
$sql_upgrade_like = "SELECT * FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result_upgrade_like = mysqli_query($conn, $sql_upgrade_like);
if($row_upgrade_like = mysqli_fetch_assoc($result_upgrade_like)) {
$gaming_comment_like = $row_upgrade_like['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update_like = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update_like = mysqli_query($conn, $sql_update_like);
$sql_insert_like = "INSERT INTO gaming_comment_likes (gaming_comment_id, user_id, user_id_like) VALUES ('$commentId', '$userId', '$sessionUserId')";
$result_insert_like = mysqli_query($conn, $sql_insert_like);
$like_upgrade = true;
//json format
$data = array("gaming_comment_like" => $gaming_comment_like,
"like_upgrade" => $like_upgrade);
echo json_encode($data);
exit();
}
}
Note: i also try to include this to the top of my php file:
header('Content-type: json/application');
but still not worked.
What am i missing here?
Don't call $.parseJSON. jQuery does that automatically when you specify dataType: 'json', so data contains the object already.
You should also learn to use parametrized queries instead of substituting variables into the SQL. Your code is vulnerable to SQL injection.

Javascript, Php, Ajax

I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.

Php function return empty json to Ajax

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';
...

Null response in PHP AJAX call

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.

Getting multiple values returned from a $.ajax POST

I have some ajax code that executes on mouseclick. It calls a file called update.php that does a bunch of stuff, including checking for user permissions, numerous database calls, etc. In the end, I also want to be able to return a few variables from PHP for the callback to use, but not sure how to reference them - or if there's a better way to return this info.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text("[first variable here]");
$("div.numbert2").text("[second variable here]");
}
From my update.php file (some snippets):
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
// Email - function returns data to variable
$emaillist = emailAdmins($user);
} else {
$message = "Sorry you do not have access";
}
So I'd like to figure out how to use the variables $message, $value and $emaillist in my callback if possible.
I'm wondering if I just need to make multiple $.ajax POST calls, with each .php function that returns a variable having it's own call?
Thanks!
----UPDATE-------
Updated code trying to use the json methods - thanks for all the help - but seems I'm missing one last thing.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
and update.php:
$storage = array();
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$storage['value'] = "some user";
// Email - function returns data to variable
$storage['emaillist'] = "some stuff";
header('Content-type: application/json');
echo json_encode($storage);
exit(0);
Thanks again.
You can use a JSON wrapper:
$messages = array();
$messages['value'] = GiveAccess($user);
$messages['emaillist'] = emailAdmins($user);
$messages['message'] = "Sorry you do not have access";
echo json_encode($messages);
And then simply use:
data.value data.emaillist data.message
in your Javascript.
Easiest way would be to use JSON...
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
if(data.error){
alert(error.message||'Unknown Error');
} else {
$("div.numbert").text(data.access||'No value');
$("div.numbert2").text(data.emailList||'No value');
}
}
PHP:
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$responseData = array();
// Give access - function returns data to variable
$responseData['access'] = GiveAccess($user);
// Email - function returns data to variable
$responseData['emailList'] = emailAdmins($user);
} else {
$responseData['error'] = array('code' => 403, 'message' => "Sorry you do not have access");
}
header('Content-type: application/json');
print json_encode($responseData);
exit(0);
No, just return a JSON object or a dataset that's delimited that you can parse.
You can return your values using json:
$storage = array();
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
$storage['value'] = $value;
// Email - function returns data to variable
$emaillist = emailAdmins($user);
$storage['emaillist'] = $emaillist;
} else {
$message = "Sorry you do not have access";
$storage['message'] = $message;
}
header("Content-Type: application/json; charset=utf8");
$return = json_encode($storage);
echo $return;
exit;
You can then iterate over the object and go
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
}

Categories