Reputation: 1189
In js
file I'm sending json object to php file but i don't know how to access to sent object.
first line in code below give me that:{"id":1,"email":"[email protected]","password":"xxxx","location":"London"}
js file
app.showAlert(JSON.stringify(profile));
$.ajax({
type: "GET",
url:"http://www.domain.co.uk/test-login.php",
dataType: 'jsonp',
data: { data: JSON.stringify(profile) },
success:function(json){
// do stuff with json (in this case an array)
app.showAlert(JSON.stringify(json), "Login ok");
},
error:function(){
app.showAlert("Login faild", "Wrong username or password. Please try again.");
},
});
php file:
<?php
header('Content-type: application/json');
$ret=$_GET['data'];
$ret=json_decode($ret, true);
echo '['.json_encode($ret[0]).']';
?>
Php is test, because i want to check if user pass correct details, then I will return json object with 'loggedin' => 1
or so, if not 0
I also tried to access to this object by $ret=$_GET['profile'];
, but it didn't help.
My question is: how to pass json object and access to it in php.
Upvotes: 1
Views: 120
Reputation: 64526
You need to modify both the ajax and PHP to get it to do what you want. I've changed the Javascript to test for the success/fail within the success function. IF you are returning JSON from PHP, then you don't want to be handling the failed password in the error event.
For the PHP you seem to be getting the input and output mixed up. As you can see the input is decoded into the $data
variable, and the output is an array in $output
until it gets encoded and output.
$.ajax({
type: "GET",
url:"http://www.domain.co.uk/test-login.php",
dataType: 'jsonp',
data: { data: JSON.stringify(profile) },
success:function(json){
// do stuff with json (in this case an array)
if(json.loggedin == '1'){
alert("logged in");
} else {
alert("failed to login");
}
}
});
PHP:
$output = array('loggedin' => 0);
$data = json_decode($_GET['data']);
// this shows how to access the data
if($data->email == '[email protected]' && $data->password = '1234')
{
$output['loggedin'] = '1';
}
header('Content-type: application/json');
echo json_encode($output);
Upvotes: 1