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
Related
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;
Got a $.getJSON results from MySql SELECT Query via PHP_PDO: fetchAssoc echoed with json_encode(), the output goes like this in firebug console:
//Console.log shows
[Object { user_id="10", user_age="80", user_name="Adam"},
Object { user_id="11", user_age="70", user_name="Eve"},
Object { user_id="12", user_age="60", user_name="Cain"},
Object { user_id="13", user_age="30", user_name="Abel"},
Object { user_id="14", user_age="180",user_name="Satan"}]
Please note that this is being viewed as console.log(result), however, in javascript's interpretation, this will be something like: user_id:"10", user_age:"80" etc... replacing the "=" with ":" to form key:value pairs .
Now, how does one extract something like the 4th object's user_name from this kind of a result and have an alert like alert( to out put: 'Abel')?
If i understand you right, you have a variable 'result' with type of Array, and every item in your Array has type of Object. So, you can just get an element with index and then access to property you need:
result[3].user_name
I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS.
On the PHP end, I did this
while($row = mysql_fetch_array($result))
{
$jmarkers = array(
'id'=> $row['id'],
'lat' => $row['lat'],
'lng' => $row['lng'],
etc...
);
array_push($json, $jmarkers);
}
$jsonstring = json_encode($json);
echo $jsonstring;
I can access the data in JS using jQuery, and I made an array to save the JSON data:
$.getJSON("getjson.php", function(data)
{
myMarkers = data;
console.log(myMarkers);
});
I'd planned to access the data in the myMarkers array inside loop, with a statement like this:
var tempLat = myMarkers.jmarkers[i].lat;
The problem is my JSON objects aren't called jmarkers or anything else, they have this generic name "Object" when I print them to the console:
Object { id="2", lat="40.6512", lng="-73.9691", more...},
So I'm not sure how to point to them in my JS array. I looked the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!
That's to be expected. JSON is essentially the right-hand-side of an assignment operation:
var x = {'foo':'bar'};
^^^^^^^^^^^^^---- JSON
The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:
$arr = array(
'jmarkers' => array(...your data here...);
);
But all this does is add another layer to your data structure for no useful reason.
$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.
In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.
You... don't. The whole thing is an object. You only need to refer to the elements within.
alert(myMarkers.id);
Hello there I have a really complex php script that produces a javascript file in jquery
There is a string that is stored in an input type text and I want to converted into json.
The input type text has undedined number of elements.
So I initisialize the string in the input box
<input type="text" id="selectbuttons" value="{}">
After some actions the string in the input box is something like that:
{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}
etc...
Then this is my script , i use the function addScriptto to add it to the document's header, also I am using the core of jquery jquery-1.6.2.min.js to make the json object
$document->addScriptto('
$.noConflict();
jQuery(document).ready(function($) {
var loaded=$("#selectButtons").val();
var obj = jQuery.parseJSON(loaded);
}); //end of dom ready
');
But I can't make it work, when the string is not empty
Is there something wrong with my json syntax? Also, I would be later able to loop all the elements and retrieve the data? Thanks in advance
Your JSON string should be in an array format like below
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
And then you can use the $.each to loop through the JOSN values as below:
$.each(yourJSONstring,function(i,values) {
//yourJSONstring holds the JSON array
// i is just the loop index. it will increment by 1 in every loop
alert(values.button) //will alert bt1 in the 1st loop, bt2 in 2nd
alert(values.style) //will alert style1 in 1st loop, style2 in 2nd
//You can have values here of the keys in JSON using the dot notation as above and do your operations.
})
maybe just put [ ... ] around the JSON so it is understood as an array, something like:
var obj = jQuery.parseJSON( '[' + loaded + ']' );
Yes, your JSON syntax is wrong. You should have it like:
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
and then you will have array of your objects.
I've got a PHP array and echo that into javascript with json encode, i need to do it this way because it's going to be very dynamic. This is the code it echo's:
{"notempty":true}
And i use this to, convert it to javascript:
var myarray = eval('(' + json + ')');
For some reason it creates an object instead of an array and for that reason i cant use .length or a for loop.
Does someone know what im doing wrong here?
Thanks
You're trying to treat an Object like an Array, and an Object is not an Array, it is an Object.
Any time you see {} in JSON, that means "What is contained within these hallowed brackets is a dynamic object". When you see [], that means "Behold! I am an Array" (there are notable exceptions to this one: jQuery does some special work with to make itself look like an array).
So, in order to iterate through an Object, you'll want to use for... in.
// eval BAD unless you know your input has been sanitized!.
var myObj = JSON.parse('{"notempty":true}');
// personally, I use it in for... in loops. It clarifies that this is a string
// you may want to use hasOwnProperty here as sometimes other "keys" are inserted
for( var it in myObj ) console.log( "myObj["+it+"] = " + myObj[it] );
{} is an object, which contains one attribute named notempty. If you want an array, it'd have to be
[{"notempty":true}]
which is an array with a single element at index 0, which is an object with the single attribute 'notempty';.
By default, if you use encode an assoc array in php, it will become a js object when you decode. In order to have it be an array, you need to make it an array in php:
PHP:
$arr = "['notempty','notempty2','notempty3']";
Otherwise, you should convert it to an array in JS, but that seems to me a waste since looping through the object in javascript is so much easier:
Javascript:
var arr = new Array();
for(var i in obj) arr[i] = obj[i];
You can use jQuery to parse it into an array like this:
var p = [];
$.each(jsonData, function (key, val) {
p.push([val.propertyOne, val.propertyTwo]);
});
I am presuming of course that you want to parse JSON, not an array or any other string.