Reputation: 49384
I have a login using getJSON and PHP.
Right now all it does it checks if the user and password is valid but if it is I want to pass further information to the client.
Right now on the server side I do this:
if ($result->num_rows) {
echo '{"response":{"error": "1"}}';
} else {
echo '{"response":{"error": "0"}}';
}
and on the client side I have this:
if (json.response.error == "1") {
data = "Welcome "+username;
alert(data);
} else {
// Login fail
data = "Wrong Username/Password";
alert(data);
}
So basically it's just checking.
How can I pass some more information from the server to the client?
Update: I've changed the code to this but it's now not working:
Server:
if ($result->num_rows) {
//echo '{"response":{"error": "1"}}';
$data = array(
'response' => array(
'error' => 1,
),
'someData' => 'data';
);
print json_encode($data);
}
Client:
$.getJSON("server.php", {username:username,password:password},function(data)
{
alert('hello');
var json = JSON.parse(data);
alert(json.responseCode);
});
Upvotes: 0
Views: 617
Reputation: 8508
On the server side, You can create an array containing all the data you need and then send it from the server to the client using json_encode() :
$data = array(
'response' => array(
'error' => 1,
),
'someData' => 'data',
...
);
print json_encode($data);
And on the client side :
var json = JSON.parse(data);
alert(json.response.error);
Hope it helps !
Upvotes: 2
Reputation: 74738
You have to use jQuery.parseJSON(json)
where json here is a well formed json string.
From the documentation:
It takes a well-formed JSON string and returns the resulting JavaScript object.
So you have to parse the string first to a javascript object.
var json = $.parseJSON(data); // data is the json string
if (json.response.error == "1") {
data = "Welcome "+username;
alert(data);
} else {
// Login fail
data = "Wrong Username/Password";
alert(data);
}
Upvotes: 1