How to get the json return value - javascript

If I can get the following string
([{"data":{"id":"1","user_name":"tutor","book":"123","role":"Tutor"}}]);
How can I alert it? data.user_name show undefined.
$.getJSON('http://mydomain.com/getmyDetail.php?jsoncallback=?', function(data) {
alert(data.user_name);
});
}
another question, if I would like to put some value to the URL, such as
http://mydomain.com/getmyDetail.php?username=XXX&role=XXX
, how to put into getJSON function, directly
$.getJSON('http://mydomain.com/getmyDetail.php?username='+username'+'&role='+role+'&'jsoncallback=?' ?

The [{ means that this is nested in a single element array. On top of that, the highest level key of the element is data. Use:
alert(data[0].data.user_name);

In your example, data is the variable name for the whole response, and you need the user_name element inside the data element, so you should probably try something like
alert(data[0].data.user_name);

$.getJSON('http://mydomain.com/getmyDetail.php?jsoncallback=?', { username: 'a', role: 'b' }, function(data) {
alert(data[0].data.user_name);
});

Related

How do I map a variable to object

I'm new to JSON and jQuery/JavaScript.
How would I pull in a object so that I can use it within jQuery, I've tried 2 attempts
var placements = document.querySelector(placements)
var message = document.querySelector(placements.message)
$.ajax({
type: 'GET',
url: 'https://raw.githubusercontent.com/kieranbs96/developer-exercise/master/data/recommendations.json',
async: false,
dataType: 'json',
success: function (data) {
$("header").append(placements.message);
}
});
Below is the JSON I'm trying to pull in:
{
"placements":[
{
"message":"If you like this, you might be into these",
"items":[
{
"id":"029148",
"name":"Woodblock Play Suit",
"price":"46.00"
},
{
"id":"0294526806",
"name":"Smock Dress",
"price":"39.00"
},
{
"id":"0297180006",
"name":"Cami",
"price":"9.00"
},
{
"id":"0298473606",
"name":"Asymmetric Wrap Cami Dress",
"price":"46.00"
},
{
"id":"0297155306",
"name":"Casual Stripe Tee",
"price":"16.00"
}
]
}
]
}
Marked as duplicate - the other question did not solve my problem - it has been solved by an answer to this question.
You haven't included what the error is or the expected output, but here's two potential errors.
You aren't utilizing the data object returned from your AJAX request.
The value associated with the placements key on your JSON object is an array of objects. Therefore, to access the message key, you'll need to traverse the array.
This is likely what your code should look like:
$("header").append(data.placements[0].message);
First off, you're missing the data object within your append function.
Second, you're missing the key notation of data.placements considering the fact that placements is an array.
You can either use data.placements[0].message to get your preferred data, or, if placements will be extended with more objects in the future, map through your objects like this:
data.placements.map(function(obj, index){
if(index == 0){
$("header").append(obj.message);
}
})
Not necessary if your array will always have a length of 1 of course

Parse JSON in Javascript from PHP

I am passing a json encoded string in an ajax response to my Javascript. When I console.log the json, after JSON.Parse, it looks like the following:
[
{"732":
{
"doctor_name":"First M. Last ",
"degree":"MD"
}
},
{"377":
{
"doctor_name":"First M. Last ",
"degree":"MD"
}
},
{"1092":
{
"doctor_name":"First M. Last",
"degree":"DO"
}
},
{"759":
{
"doctor_name":"First M. Last",
"degree":"MD"
}
},
{"1628":
{
"doctor_name":"First M. Last",
"degree":"DO"
}
}
]
I need to access each one of these objects without knowing the ids (in this case "732", "377", "1092", "759", etc.)
Not sure if my data is even structured properly but I cannot even use Object.keys(obj) as it returns an error of a non-object property.
The way I am structuring my PHP array is as follows:
foreach ($doctors as $group){
$doctor_results[][(int)$group->prac_id]=array(
'doctor_name' => (string)$group->name,
'degree' => (string)$group->degree,
);
} // end foreach
I want each array id to be used as the key, not sure if this makes much sense.
TYIA
You most likely want your PHP to look like:
foreach ($doctors as $group){
$doctor_results[(int)$group->prac_id]=array(
'doctor_name' => (string)$group->name,
'degree' => (string)$group->degree,
);
} // end foreach
Note the missing [], which would imply pushing an item onto a numeric array. The second set of brackets in your example is suggesting to PHP that the numeric element created should be an associative array with an item with the 'prac_id' as a key. PHP is automatically creating that associative array, creating the structure with your key nested one level further in than you want for being able to grab an item by 'prac_id' by simple key access in JavaScript. As is, you'd need a nested loop like in Darren's answer.
I heavily agree with the comments posted by Marty and Six Fingered Man, but if you wanted to loop through the json, this would work:
jQuery.each(obj, function(index, data){
jQuery.each(data, function(id, fields){
console.log(id); // returns the ID's of the objects: 732, 377,....etc
console.log(fields); // returns the fields for each object. (doctor_name & degree)
});
});
JSFiddle Demo
[
{prac_id:"732",data:
{
"doctor_name":"First M. Last ",
"degree":"MD"
}
},...]
foreach ($doctors as $group){
$doctor_results[][(int)$group->{'prac_id'}]=array(
'doctor_name' => (string)$group->{'data'}->{'name'},
'degree' => (string)$group->{'data'}->{'degree'},
);
} // end foreach
Your ajax response is array of OBJECT. If you encode it by json_encode($array), your ajax response is OK. You can check your ajax response here : http://json.parser.online.fr/
So I think you can modify your ajax call. You can just add this dataType: 'json' in your ajax. It will automatically handle your JSON response.
$.ajax({
url: 'your_ajax_url',
data: 'data',
dataType: 'json',
success: function(data)
{
$.each(data, function(index, obj){
$.each(obj, function(id, nested_obj){
console.log("ID: "+id);
console.log("doctor name: "+nested_obj['doctor_name']+",degree:"+ nested_obj['degree'] );
});
});
}
)}

How to access a predefined array in AngularJS

I'm facing an issue with accessing the array element in AngularJS. I have an array:
$scope.salesentry = [
{
sales_id:'',
product_id: '',
product_category_id:'',
sale_qty:null,
sale_amount:null
}
];
I want to update the sales_id field value on some button click like:
$scope.saveData = function() {
$scope.salesentry.sales_id='10';
});
I'm not able to access it in the above way. How can I do so?
salesentry is an array, so you need to access a specific element on it first using [0].
So your code becomes:
$scope.saveData = function() {
$scope.salesentry[0].sales_id='10';
});
Do you want to update each salesentry's sales_id ?
If yes you may use
angular.foreach($scope.salesentry, function(value, key){
value.sales_id = 10;
});
You need to index the array
$scope.salesentry[0].sales_id = '10'
Also, no need for the comma at the end.

json result display first value

I have found several posts similar to this topic but nothing I have tried has actually worked. My question is simple and should be easy to answer. My return json object will have one key and one value. For my code below, the alert shows "[{"DISCOUNT":1}]" and all I am trying to do is parse out the "1" and display it. Ultimately, I want to plug that value into a variable and use for multiplication, but I can't even get the darn number to display by itself. My code is below:
function codeMatchTest() {
if ($('#dbReturnString').val() == '') {
alert("Please enter a discount code.");
} else {
$.ajax({
type: "POST",
url: "PROMO.svc/MatchCode",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
success: function (json) {
alert(json.d);
/*alert (json.d.discount); // getting "undefined"
$.each(json.d, function (key, value) {
var discount = value;
});
alert("Success: " + discount); //getting "undefined" */
},
error: function () {
alert("There was an error with your request.");
}
});
}
}
I have found no good references on how to actually use the data in a json object. My json object will only consist of a single key and value and I will only ever need to use the value.
Also, I have tried several iteration using $.each and none work. Based on the jquery documentation, it should be very easy but I am having not luck.
If your alert is showing "[{"DISCOUNT":1}]" that means you have an object within an array.
try alert(json.d[0].DISCOUNT);
JSON parsed objects are case sensivetive, plus its seems that json.d contains a string (wich seems to be in json) rather than an object. Try:
var discount = JSON.parse(json.d);
discount = discount[0].DISCOUNT;
success: function(json) {
alert(json.d[0]["DISCOUNT"]);
}
First comment on your code, you are reinventing what jQuery does.
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
It should just be
data: { codeInput: $('#dbReturnString').val().toLowerCase() },
Now to get the data it is simple, you are returning an array with an object in it.
Let us look at it as a regular variable and not an Ajaqx call.
var json = [{"DISCOUNT":1}];
So you got an array? How do you get the object inside of it? You reference the index. Since you said there will only be one index being returned, than use [0] to access it.
success: function (json) {
alert(json[0].DISCOUNT);
To access the first item from the json you may use
alert(json.d[0].DISCOUNT);
Because json.d is an array and it contains one object which is 0 index. So, json.d[0] will select the first item/object from the array and using .DISCOUNT you can access the object's property. It's also possible to access the property like
alert(json.d[0]["DISCOUNT"]);
Try this way
You can use JSON.parse(json.d) / json.d
var data = json.d;
for(i=0;i<data.length;i++) {
alert(data[i].fieldname);
}

.each parse JSON returns undefined

Hi I have the following codes:
$.ajax({'type':'POST', 'url':'https://www.123.com/site/gethistory',
'data':{'a': this.username, 'b': username},
'success':function(history){
alert(history);
var codes = jQuery.parseJSON(history);
$.each(codes, function(key, value) {
alert(key);
}); //each
},
'error':function(){
}
}); //ajax
Right now the key is undefined. And i tried to alert(value.text), it still gives me undefined.
history is alerted as this:
[{"demo":{"text":"hi
man","time":"1380167419"},"admin":{"text":"hi","time":"1380167435"},"demo":{"text":"this
works flawless now.","time":"1380167436"},"demo":{"text":"we are
basically done with this/","time":"1380167443"}}]
It works fine in this fiddle. However, there is a problem with your JSON.
Although it is syntactically correct, it is structured such that you are returning an array of one object with a number of properties all with the same name:
[
{ "demo":{
"text":"hi man",
"time":"1380167419"
},
"admin":{
"text":"hi",
"time":"1380167435"
},
"demo":{
"text":"this works flawless now.",
"time":"1380167436"
},
"demo":{
"text":"we are basically done with this/",
"time":"1380167443"
}
}
]
Each successive demo will overwrite the previous one, so you'll only see the last demo property.
Looks like there is something wrong with your JSON. Try alert codes and make sure the parsed JSON is in the right format, i.e key/value pairs
no need to use jQuery to parse JSON. Just var codes = JSON.parse(history)
$.each(codes, function(k, v){
console.log(v )
});

Categories