0

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);


});

2 Answers 2

2

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 !

Sign up to request clarification or add additional context in comments.

7 Comments

I've added it like this but it not longer log's in: echo '{"response":{"error": "1"}}'; $data = array( 'responseCode' => 1, 'someData' => 'data'; ); print json_encode($data);
I've edited the response, but you also need to remove your echo.
I've removed the echo from the server code and the client side looks like this:
var json = JSON.parse(data);alert(json.responseCode);}..but no alerts happening...any ideas?
The structure of the php array changed, so the structure of the javascript array changed too.
|
1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.