I am a beginner in Javascript. I hope to get some help.
I built a local server using MAMP, and all my files are local. I want to read a value from a json file. This json file(data.json) has only one item {"type":2}, and I only want to use the value(2 in this case). But the value of "type" changes, so Javascript should read it constantly and maybe save it into a var in Javascript.
Can I listen for changes to that file so that I can be sure I always have the most up to date value for type?
I am still not familiar with Javascript. I would really appreciate it if you could give me some specific codes or examples.
//Either
var json = {test:"test"};
console.log(json);
//Access JSON
console.log(json.test);
//Or
$.getJSON( "test.json", function( data ) {
//Assign the json to your JSON variable
json = data;
});
console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JSON can come from anywhere, inbuilt into jquery is parseJSON which will return the json input string as a javascript object.
http://api.jquery.com/jquery.parsejson/
var obj = $.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
where the json can come from anywhere.. an ajax call or where ever else.
$.ajax({
url:'some url',
data: someobject,
type: 'get',
success: function( responseFromServer ){
var obj = $.parseJSON( responseFromServer );
alert( obj.name === "John" );
}
});
Related
I would like to extract a CSV local file in PHP using AJAX.
To do that I tried to use Papa Parse and it works great. The problem is to pass the results with AJAX. I tried with JSON.stringify, I tried to pass only the first field; I tried also to create a JSON object and then add the results to this object but, I don't know why, when I extract in PHP I got only the values of the original object.
values = {};
values['row_1'] = 'value1';
values['row_2'] = 'value2';
i = 3
$("input[type=file]").parse({
config: {
delimiter: ",",
step: function(results) {
value = results.data[0]
values['row_' + i] = value
i = i + 1
}
}
});
$.ajax({
type: "POST",
url: "extract-csv.php",
data: {
id: $('#id').val(),
...
values: values
}
...
})
With this code on PHP I returned only "value1" and "value2" (if I print "values" in the console I get object with 2++ elements)
Papa Parse worked after Ajax, so the solution is to put the Ajax call in the "Complete" Papa Parse function and then everything works fine!
I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.
I am unable to parse the json file obtained from this http://dbpedia.org/data/Los_Angeles.json url.
I need to find the populationTotal, areaTotal, populationDensity fields from the json data obatined from the URL above.
This is a snippet of the json data obtained from http://dbpedia.org/data/Los_Angeles.json url.
Eg.
"http://dbpedia.org/ontology/populationTotal" : [
{ "type" : "literal",
"value" : 3792621 ,
"datatype" : "http://www.w3.org/2001/XMLSchema#integer" } ] ,
"http://dbpedia.org/ontology/PopulatedPlace/areaTotal" : [
{ "type" : "literal",
"value" : "1301.9688931491348" ,
"datatype" : "http://dbpedia.org/datatype/squareKilometre" } ,
How could i get this Json data and output it using Javascript.
Do this help you?
var populationTotalData=[];
for(var key in data) {
if(key.match(/populationTotal/))
// or simplier: if(key.indexOf("populationTotal")>-1)
populationTotalData.push(data[key]);
}
Because of the Same-Origin Policy, you often can't directly fetch the data using JavaScript. However, it turns out that dbpedia.org supports JSON-P, so you can get the data with straight JavaScript like this:
// This is the "callback" function. The 'data' variable will contain the JSON.
// You can access it like I have done in the alert below.
mycallback = function(data){
alert(data["http://fr.dbpedia.org/resource/Los_Angeles"]["http://www.w3.org/2002/07/owl#sameAs"][0].value);
};
// This is the function we use to fetch the JSON data:
function requestServerCall(url) {
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
// Note the query string that I have added (?callback=mycallback).
// This is the name of the function that will be called with the JSON data.
requestServerCall('http://dbpedia.org/data/Los_Angeles.json?callback=mycallback');
A lot more really excellent information on JSONP can be found here. You could loop inside of the mycallback function using some code like this. Obviously, you'd have to make nested loops to get exactly what you want, so this code would need modifying to fit your exact needs.
<script type="text/javascript">
for(var index in data) {
console.log(data[index]);
}
</script>
The other method would be via PHP. For example: you could pitch the whole page into a JavaScript variable like this:
<?php
$los_angeles = file_get_contents('http://dbpedia.org/data/Los_Angeles.json');
?>
<script type="text/javascript">
var data = <?php echo $los_angeles; ?>;
alert(data["http://fr.dbpedia.org/resource/Los_Angeles"]["http://www.w3.org/2002/07/owl#sameAs"][0].value)
</script>
I use a dojo request.get to read a txt file in JSON format, but can't convert it to JSON object.
The "datagrid.txt" stored some data as:
[
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"}
]
The requesting client code is as:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore', 'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = JSON.stringify(text);
for(var i = 0, l = 16; i < l; i++){
console.log( datalist[i] );
}
});
The console.log displays things in string(such as "[","{"), not what as I expected an array({"col1":"val1", "col2":"val2", "col3":"val3"}), which I could used to populate a dojo datagrid data store.
Dojo can handle the JSON format on its own. Official docs
I think your Problem lies in the way you're writing your datagrid.txt and the style you try to read the data later.
Here's my solution:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore',
'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = [];
dojo.forEach(text,function(thisText,i){
//add each single Object from the datagrid.txt to datagrid-array
datalist.push(thisText);
//alert the newly added item in datagrid
console.log(datalist);
});
});
I think this should fix your Problem.
Regards, Miriam
I receive the following
[{"user_id":"1","user_invoice_add1":"Stark Towers","user_invoice_add2":"123 Reginald Street","user_invoice_city":"Newport","user_invoice_state":"New York","user_invoice_country":"US","user_invoice_zip":"321654"}]
How do I pick out information from it?
trying data.user_id or data[0].user_id returns as undefined
jQuery
$.post('post.php', qString, function (obj) {
console.log(obj);
}
You'd have to first convert this string into JSON object by using a jQuery function var obj = $.parseJSON(data).
It will return you a JSON object that you can access like obj[0].user_id
use this:
myObject = jQuery.parseJSON( dataReceived );
and then you can access the data as properties of the object
Try like this..
$.map(data.d, function (item) {
alert(item.user_id)
});
jquery.ajax has a setting called dataType this is what your getting response from server as..
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
$.ajax({
....
dataType:"json",
success:function(data){
alert(data.user_id) //no need to parseJSON...dataType does it
};
});
Using POST
$.post('post.php', qString, function (obj) {
console.log(obj);
}, "json");
or you can use $.parseJSON(data) to convert the string as json object