AJAX - Parse JSON object returned in JQUERY - javascript

I stucked a little bit in here>
My php script returns this JSON (in variable response) (encoded array with json_encode) :
{"1":{"id":"pvv001","tooltip":"tip1","link":"http:\/\/domain\/file1.html"},"2":{"id":"pvv002","tooltip":"tip2","link":"http:\/\/domain\/file2.html"}}
I hope this is valid JSON object ...
Then here is JavaScript function which should get this string and process it - load to ELEMENT "id" a content of "link".
function jLinks(idchapter)
{
var url = 'ajax_loadlinks.php';
var data = {
idchapter : idchapter
};
$.post(url,data, function(response)
{
//$('#coursecontent').html(response);
var obj = JSON.parse(response);
for (var i=0; i<obj.length; i+1)
{
$('#'+obj[i].id).html('link');
}
});
}
It is not throwing any error in browser or console, but elements are not updated at all.
I quess my parsing and accessing data is wrong somehow, but I have no idea how to debug.

As your string is an object not array, so you need $.each method to loop over each key of object.
var obj ={
"1": {
"id": "pvv001",
"tooltip": "tip1",
"link": "http:\/\/domain\/file1.html"
},
"2": {
"id": "pvv002",
"tooltip": "tip2",
"link": "http:\/\/domain\/file2.html"
}
};
$.each(obj,function(i,v){
$('#'+v.id).html('link');
});
Fiddle

please try this
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(obj[prop].id);
$('#'+obj[prop].id).html('link');
}
}

Related

JavaScript: How can Get the json.file that it was post to my code?

Imagine if I want to wait to get JSON file If they post to me. I can get it. if it's not I waite for it. I want to get it and store it and parse it to work on it.
(I need to receive the request )How I can have JSON file I can get it to take what I need then post my HTTP response to the agent that sends me file that file.
my JSON file name is : flow_demo_1
var device_array = { device_id : [["7547092d-e03e-5148-a54f-8276a85d7f70","cpp_node_192-168-56-1:6111"]] };
var from_file_array = [
{ device_id_from_file: "7547092d-e03e-5148-a54f-8276a85d7f70" },
{ device_id_from_file: "93e71ba7-fb56-5592-a5f6-d855203dd7ae" },
{ device_id_from_file: "93e71ba7-fb56-5592-a5f6-d855203dd7ae" },
{ device_id_from_file: "fe21abdf-706f-5c7b-adb8-2507e145e820" },
];
var val = device_array['device_id'][0][0];
for (var i= 0; i < from_file_array.length; i++) {
if(from_file_array[i].device_id_from_file === val){
console.log("device ids are matches");
};
};
try this,you just want the which file data is matched right?
from_file_array.filter(each=>each.device_id_from_file===device_array.device_id[0][0])
it will give the matched device_id_from_file;if not you will get empty array

Get object from JSON with jQuery

I'm trying to query a JSON file in my own server using $.getJSON and then cycling inside the objects. No problem so far, then i have an ID which is the name of the object i want to return, but can't seem to get it right:
var id = 301;
var url = "path/to/file.json";
$.getJSON( url, function( json ) {
var items = [];
items = json;
for (var i = 0; i < items.length; i++) {
var item = items[i];
console.log(item);
}
});
This prints the following in the console:
Now let's say i want return only the object == to id so then i can refer to it like item.banos, item.dorms etc.
My first approach was something like
console.log(json.Object.key('301'));
Which didn't work
Any help would be very much appreciated.
It seems like your response is wrapped in an array with one element.
You can access object properties dynamically via square brackets:
var id = 301;
var url = "path/to/file.json";
$.getJSON(url, function(json) {
console.log(json[0][id].banos);
});
As you have the name of the property in the object you want to retrieve you can use bracket notation. you can also simplify your code because of this:
var id = 301;
//$.getJSON("path/to/file.json", function(json) {
// response data from AJAX request:
var json = {
'301': {
banos: 2
},
'302': {
banos: 3
},
'303': {
banos: 4
},
'304': {
banos: 5
},
};
var item = json[id];
console.log(item);
//});
$.each(items,function(n,value){
if(n==301)
alert(value);
});

parsing json file - scan and separate its attributes

I am trying to parse json file to match name of the user
var jsObj = eval('('+request.responseText+')');
var name = document.getElementById("name");
for(var i=0;i<jsObj.names.length;i++)
{
alert(jsObj.names[i].value);
if(name.value==jsObj.names[i].properties['name'])
{
//do additional stuff
}
}
I have a simple JSON file but I get error as cannot read property name of undefined or null
I also tried just jsObj.names[i].name still the error persists. If I alert names[0] etc I get object...
EDIT: My JSON file
{
"names":[
{
"name": "vcjndjvndfjv",
"address": "jnvdfjnvdjn",
"country":""
},
{
"name": "vcjndjvndfjv",
"address": "jnvdfjnvdjn",
"country":""
},
{
"name": "vcjndjvndfjv",
"address": "jnvdfjnvdjn",
"country":""
}
]
}
I have changed the actual values of the attribs but it looks like this..
I have also tried JSON.parse but I think the error is related to jsObj.names[i].name
Where am I going wrong?
try this:
var jsObj = JSON.parse(request.responseText)

How get parametrs from json?

Full code:
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
});
in data i get json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
P.S.: All code php and jquery find here
Just set proper data type json, the default one is string.
And your data is directly under data variable!
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
}, 'json');
Another solution is setting proper header in you PHP response:
Content-Type text/javascript; charset=UTF-8
then jQuery Intelligent Guess, will set proper data type itself.
You can use parseJSON method, exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:
var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
alert(results[i].name + ":" + results[i].date);
}
You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.
getJSON() will parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON).
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
});
Another example:
Parse a JSON string.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;

Loop through a JSON responseText array using the keys with Javascript

Using Javascript. I'm trying to loop through an array encoded with JSON. Here is a sample of the array:
{"test1":"some info","test2":"more info","test3":"more stuff"}
Inside each loop I am checking to see if a DIV id exists with the name of the keys.
<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
I'm using a for() loop, but I can't get it to work. If I remove the for() loop it works just fine if I search for only 1 DIV id.
for(var key in responseText)
Here is the script. Does anyone know how I can loop through the array from responseText using the array keys as the names of the DIV id's?
<script>
function loadInfo() {
var req = new Request({
method: 'get',
url: 'getinfo.php,
noCache: true,
onRequest: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', 'Loading');
}
}
},
onComplete: function(responseText, responseHtml) {
if (JSON.decode(responseText) != null) {
var data = JSON.decode(responseText);
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', data[key]);
}
}
}
},
onFailure: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', '-');
}
}
}
}).send();
}
window.addEvent('domready', function() {
loadInfo();
});
</script>
You have to decode the JSON before you iterate over the keys. So, where you say:
for(var key in responseText) {
replace that with:
for(var key in data) {
assuming
var data = JSON.decode(responseText);
Also, some of your callback functions don't specify responseText as a parameter. If you want to access this for each callback, you have to explicitly include responseText as a parameter. Example:
onRequest: function(){
should be:
onRequest: function(responseText){
I think the problem is that you're using the wrong variable name.
var data = JSON.decode(responseText);
for(var key in responseText) {
Should read
var data = JSON.decode(responseText);
for(var key in data) {
Note that instead of responseText after in, it reads data.
Are you sure you don't want JSON.parse? This would parse the JSON response into a javascript object that you can use the for/in against.
var data = JSON.parse(responseText);
Also, you're missing a closing quotation mark after the url:
url:'getinfo.php', // Closed the quote

Categories

Resources