samedi 5 avril 2014

php - Ajax retour indéfini de JSON - système de connexion & meilleures pratiques - Stack Overflow


I'm receiving an error of undefined when I try and retrieve values in the JSON. I'm new to ajax / js etc and trying to create an 'elegant' drop down login down.


I've tried various things and read a few of the posts that I've found here but I notice that the layout has changed somewhat and I also notice that I'm using success and now that deprecated.


So could I ask for help in firstly understanding what the problem is and how i solve the undefined issue and secondly what is the best way to achieve this. I'd prefer not to use deprecated code if I can help it.


I've also noticed that since changing the code so that it gets to the 'success' park of the ajax call, the drop down box no longer rolls back up or displays the error messages. -.-


Thanks in advance.


The Ajax


function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}

var params = {username: username, password: password};
var url = "../js/loginProcessAjax.php";

$("#statusLogin").show();
$("#statusLogin").fadeIn(400).html('<img src="images/loading.gif" />');

$.ajax({
type: 'POST',
url: url,
data: params,
datatype: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= 'checking...' ;
},

success: function(data) {
alert("success Area ofAjax");

$("#statusLogin").hide();

if(data.success == true){
alert("if data.success Area of Ajax");
alert(data.message);

}else{
alert("data.message... " + data.message);//undefined
$("#errorConsole").html(data.message);
}

},
error: function( error ) {
console.log(error);
}
}, 'json');
}

PHP


<?php

if($_POST){

if($users->userExists($username) === false){
$data['message'] = "User doesn't exist";
$data['success'] = false;

}else if($users->userExists($username) === false){
$data['message'] = 'That username does not exist';
$data['success'] = false;

}else if($users->emailActivated($username) === false){
$data['message'] = 'You need to activate the account, please check your email.';
$data['success'] = false;

}else{

$login = $users->login($username, $password);

if($login === false){

$data['message'] = 'Incorrect Password or username';
$data['success'] = false;
}else{
$data['success'] = true;
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
}

echo json_decode($data);
}

}

Markup:


<form method="post" action="" id="ourLoginFormID_JS">
<div class="ourContactFormElement2">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autocomplete="off" class="required" value="<?php if(isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</div>

<div class="ourContactFormElement2">
<label for="password">Password:</label>
<input type="password" id="password" name="password" autocomplete="off" class="required"/>
</div>

<div class="ourContactFormElement2">
<label> &nbsp; </label>
<input type="submit" name="loginButton" id="loginButton" value="Login!" onclick="validLogin(); return false;"/>
</div>

<div id="statusLogin"></div>
</form>



Your if/else/else/else chain only outputs json if the final else block executes. You need to move the json_encode call outside the block:


if (...) {
} else if (...) {
} else if (...) {
} else {
...
}
echo json_encode($data);

This way your code will output the encoded $data, no matter WHICH of the various if() clauses actually executed.




The problem with your undefined error is this:


datatype: 'json',

Javascript is case sensitive and the property is dataType not datatype. Because of this, jQuery is not being told to automatically parse the JSON and so you're just getting the JSON string, causing the undefined error on data.message.


Also I don't see where you access $_POST['username'] or where you instantiate the $users object, I see $username but not $_POST['username'].




A couple of things. You might want to explicitly use contentType parameter of application/json here so that it is clear that you are both sending and receiving JSON.


The main issue is that when sending POST data to PHP that is not form-encoded, $_POST will not be populated automitically. You need to read http raw input like this:


$json = file_get_contents('php://input');

if(!empty($json)) { // replace your if($_POST) with this
$object = json_decode($json);
$username = $object->username;
$password = $object->password;

// the rest of your code

}


I'm receiving an error of undefined when I try and retrieve values in the JSON. I'm new to ajax / js etc and trying to create an 'elegant' drop down login down.


I've tried various things and read a few of the posts that I've found here but I notice that the layout has changed somewhat and I also notice that I'm using success and now that deprecated.


So could I ask for help in firstly understanding what the problem is and how i solve the undefined issue and secondly what is the best way to achieve this. I'd prefer not to use deprecated code if I can help it.


I've also noticed that since changing the code so that it gets to the 'success' park of the ajax call, the drop down box no longer rolls back up or displays the error messages. -.-


Thanks in advance.


The Ajax


function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}

var params = {username: username, password: password};
var url = "../js/loginProcessAjax.php";

$("#statusLogin").show();
$("#statusLogin").fadeIn(400).html('<img src="images/loading.gif" />');

$.ajax({
type: 'POST',
url: url,
data: params,
datatype: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= 'checking...' ;
},

success: function(data) {
alert("success Area ofAjax");

$("#statusLogin").hide();

if(data.success == true){
alert("if data.success Area of Ajax");
alert(data.message);

}else{
alert("data.message... " + data.message);//undefined
$("#errorConsole").html(data.message);
}

},
error: function( error ) {
console.log(error);
}
}, 'json');
}

PHP


<?php

if($_POST){

if($users->userExists($username) === false){
$data['message'] = "User doesn't exist";
$data['success'] = false;

}else if($users->userExists($username) === false){
$data['message'] = 'That username does not exist';
$data['success'] = false;

}else if($users->emailActivated($username) === false){
$data['message'] = 'You need to activate the account, please check your email.';
$data['success'] = false;

}else{

$login = $users->login($username, $password);

if($login === false){

$data['message'] = 'Incorrect Password or username';
$data['success'] = false;
}else{
$data['success'] = true;
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
}

echo json_decode($data);
}

}

Markup:


<form method="post" action="" id="ourLoginFormID_JS">
<div class="ourContactFormElement2">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autocomplete="off" class="required" value="<?php if(isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</div>

<div class="ourContactFormElement2">
<label for="password">Password:</label>
<input type="password" id="password" name="password" autocomplete="off" class="required"/>
</div>

<div class="ourContactFormElement2">
<label> &nbsp; </label>
<input type="submit" name="loginButton" id="loginButton" value="Login!" onclick="validLogin(); return false;"/>
</div>

<div id="statusLogin"></div>
</form>


Your if/else/else/else chain only outputs json if the final else block executes. You need to move the json_encode call outside the block:


if (...) {
} else if (...) {
} else if (...) {
} else {
...
}
echo json_encode($data);

This way your code will output the encoded $data, no matter WHICH of the various if() clauses actually executed.



The problem with your undefined error is this:


datatype: 'json',

Javascript is case sensitive and the property is dataType not datatype. Because of this, jQuery is not being told to automatically parse the JSON and so you're just getting the JSON string, causing the undefined error on data.message.


Also I don't see where you access $_POST['username'] or where you instantiate the $users object, I see $username but not $_POST['username'].



A couple of things. You might want to explicitly use contentType parameter of application/json here so that it is clear that you are both sending and receiving JSON.


The main issue is that when sending POST data to PHP that is not form-encoded, $_POST will not be populated automitically. You need to read http raw input like this:


$json = file_get_contents('php://input');

if(!empty($json)) { // replace your if($_POST) with this
$object = json_decode($json);
$username = $object->username;
$password = $object->password;

// the rest of your code

}

0 commentaires:

Enregistrer un commentaire