Currently, I'm trying to move away from mySQLi procedural to object oriented style. So, I passed an object to a php file via the Jquery Post() function.
Below:
JS file
var newemployer = {
newemployeremail:newemployeremail,
newcompanyname: newcompanyname,
secondpassword:secondpassword,
};
var employerdata = JSON.stringify(newemployer);
console.log("in jquery: " + employerdata);
$.post('api/employerprocess.php', {employerdata:employerdata}, function(data){
console.log(data);
});
On the PHP side: I have this:
$employerdata = $_POST['employerdata'];
$data = json_decode($employerdata, true);
print_r($data['newemployeremail']);
I can access the object in the above, but I can't seem to get access to the values in the object using the -> operator.
$accessed = $data->newemployeremail;
var_dump($data->newemployeremail);
echo $data->newemployeremail;
echo $accessed;
echo 'Hi';
The $accessed variable, var_dump, the echoing of the object each yield this error, last two statements have a NULL at the end:
Trying to get property of non-object
I'd like to use the -> operator. I don't get it. Why can't I access the values in the object with the -> operator?
true as a second argument to json_decode() means "returned objects will be converted into associative arrays". Hence you're receiving array, not an object.
You need to either pass false to second argument to receive object or access properties using array syntax: $accessed = $data['newemployeremail'];
You are assigning the values as an associative array
$data = json_decode($employerdata, true);
// the true param in json_decode mean that teh result is converted in associative array
echo $data['newemployeremail'];
so you have an array and not an object
then try assign the json decode without true eg:
$data = json_decode($employerdata);
echo $data->newemployeremail;
Related
I have the following angularjs code for posting value to php:
$scope.aToUn = function(aName) {
//$scope.question.question_16 =UnionsId;
var outputType=[{type:'aName',action:'none',PassId:aName}];
$http.post('addressManagement.php',outputType).success(function(dataJsonUnions) {
//alert(dataJsonUnions);
$scope.question =dataJsonUnions;
//question or dataJsonUnions is an object that passed from json,
//something like question={{id="2",questionvalue="Name"}}
//calling another function
$scope.anotherFunction(questionvalue); // here i want to pass only value that from json eg. 'Name' only)
});
};
I am getting json object value, which i want to do something with that only single value. (object contain only one single value, dont want if/else or foreach)
Did you try
$scope.anotherFunction($scope.question[0].questionvalue);
As i understand your question, You first need to conver json response to object by using angular.fromJson() and then pass object's property for example:
$scope.question = angular.fromJson(dataJsonUnions);
then call function with argument that you want to pass:
$scope.anotherFunction($scope.question.questionvalue);
hope this helps you.
If the response is a JSON object and if you want to access the value of field 'questionValue' then you can try the below.
var json = JSON.parse(dataJsonUnions);
json.questionValue; // THis will fetch you the value
//OR
json['questionValue'];
// Then you can pass this value to any function that you need
I know others have already asked about this, but I don't find a solution for my problem. In my PHP page I call an external service and I can't modify the response obtained.
I'm moving my first steps both with JSON and PHP.
The response is a JSON like this, I print this using the var_dump method:
object(stdClass)#1 (3)
{
["search_string"]=>string(15) "ABCDEFG HI LMNO"
["resut"]=>string(5) "apixi"
["0"]=>array(1){
[0]=>object(stdClass)#2(2){
["resp_code"]=>string(7) "12.34.0"
["resp_description"]=>string(15) "ABCDEFG HI LMNO"
}
}
}
In my PHP page I can read the value ”ABCDEFG HI LMNO” for the key "search_string" with this code, in the $output variable I store the result of the cUrl call
.......
$output = curl_exec($ch);
$jsonDecode =json_decode(str_replace('""','"',$output));
var_dump($jsonDecode);
echo $jsonDecode -> search_string;
I need the str_replace method because the JSON is dirty but not always, how can I access at the fields "resp_code" and "resp_description" and then store them in a variable? I tried many solutions but none works for me.
Instead of converting JSON array to stdClass object you can also convert it to regular PHP array by adding second parameter to the json_decode function:
$jsonDecode =json_decode(str_replace('""','"',$output), true);
In your case in the output, you'll get a multidimensional array.
Then, to access resp_code and resp_description, you can do something like this:
$respCode = $jsonDecode[0]["resp_code"];
$respDescription = $jsonDecode[0]["resp_description"];
In the decoded JSON you have, the resp_code and resp_description keys are difficult to get to, because the top-level object has a numerical ("0") attribute. Trying to reach that attribute like this:
$jsonDecode -> 0
will give this parsing error:
syntax error, unexpected '0' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
Trying the same with a string notation (-> "0") also fails.
However, the suggestion in the error message is useful: encapsulate the zero with braces. Then you can proceed easily by adding the array index selector ([0]) to get to the object and keys of your interest, like this:
echo $jsonDecode->{0}[0]->resp_code;
echo $jsonDecode->{0}[0]->resp_description;
If you expect more elements in that array $jsonDecode->{0}, then loop over them like this:
foreach ($jsonDecode->{0} as $element) {
echo $element->resp_code;
echo $element->resp_description;
}
Alternative
If, however, you prefer to work with associative arrays instead of objects, you can use the second argument of json_encode as stated in the docs:
assoc
When TRUE, returned objects will be converted into associative arrays.
So then you would pass true as second argument:
$jsonDecode = json_decode(str_replace('""', '"', $output), true);
The above code would then be rewritten like this to access the variable as an associative array:
foreach ($jsonDecode[0] as $element) {
echo $element["resp_code"];
echo $element["resp_description"];
}
I have a key/value pair passed from Javascript via $.post as data : user_id.
I've brought it into PHP with $data = $_POST['data'] and when I vardump() that I get {"id":"1"}" as expected. However, I'd like to just access the value of 1.
How would I do that?
It's just JSON. Use json_decode() to turn it into an object (or an array if you so choose) and then get the value of ID using standard object member variable access methods:
$data = json_decode($_POST['data']);
echo $data->id;
Demo
If you're using PHP 5.4+ (using array syntax and array dereferencing):
echo json_decode('{"id":"1"}', true)['id'];
Demo
You can also try this:
$data = json_decode($_POST['data'], true)['id']
I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.
I'm trying to output the value of the email value of an array, but have problems doing so.
The array is based on json_decode()
This is the error I receive
Fatal error: Cannot use object of type stdClass as array in /home/.... line 57
JSON (value of: $this->bck_content)
{"email":"test#email.com","membership_id":"0","fname":"Kenneth","lname":"Poulsen","userlevel":"1","created":"2012-04-23 10:57:45","lastlogin":"2012-04-23 10:58:52","active":"y"}
My code
# Display requested user details
$details_array = json_decode($this->bck_content);
$value = $details_array['email'];
print $value;
You need to use the second argument to json_decode to force array structures on JS objects.
json_decode($this->bck_content, true);
This will make sure all JS objects in the json are decoded as associative arrays instead of PHP StdObjects.
Of course that is assuming you want to use array notation to access them. If you're fine with using object notation then you can just use:
$value = $details_array->email;
try this one
$value = $details_array->email;
or
json_decode($json, true);
or
$details_array = (array)json_decode($json);
what have you done wrong is writen in error description