Need to grab the JSON here from an external file - javascript

This code does what I need but I want to store the JSON values it uses in a separate file using standard JSON format so the same data can be used elsewhere with getJSON requests.
(I need to run this to match up data returned from a getJSON request with additional values. I use the id to do the match on returned items. This is how I build the complete HTML items I need.)
CODE SAMPLE
$(function() {
var json = {
"nwsltrs":[
{
"id":"53c57dede4b07621dafde5d1",
"nwsltrNames":"Hello",
"author":"Joe"
} // these entries will grow to a hundred or more.
]
};
var titleID = "53c57dede4b07621dafde5d1"; // in actual code getting this value from a separate getJSON call
$.each(json.nwsltrs, function(i, v) {
if (v.id === titleID ){
nwsltrName = v.nwsltrNames;
author = v.author;
console.log(nwsltrName + ":" + author);
return;
}
});
});
Want the external JSON file to look like this with and use .json extension:
{
"nwsltrs":[
{
"id":"53c57dede4b07621dafde5d1",
"nwsltrNames":"Hello",
"author":"Joe",
},
{
"id":"54b57dede4b07621dafde5d2",
"nwsltrNames":"Bye",
"author":"Mary",
} // these entries will grow to a hundred or more.
]
I'm sure there are better ways to approach this and am open to hearing them—as long as I can use an external JSON file.

Solved.
Moved getJSON request that was tried earlier before posting.
It needed to run and return the data prior to this .each.
This allows me to replace the local JSON function and use a validated external JSON file here and elsewhere as desired.

Related

Reading json file

In my ASP.NET backend I am creating json file from a query, I want to use this json file and take some data from it.
I wrote this code:
$(document).ready(function ()
{
$.getJSON("/Content/smartParkTotalJson.json", function (json)
{
});
}
And now I want to see the json , take some data from it (there are many landmarks inside this json file and I want to take the ID element, latitude and longitude).
How can I get access to the things I'm interested in?
In order to parse your json data, use JSON.parse(). Pretty-printing is implemented through JSON.stringify(); the third argument defines the pretty-print spacing.
$.getJSON("/Content/smartParkTotalJson.json", function(data)
{
var obj = JSON.parse(data);
var obj_str = JSON.stringify(obj, null, 2);
console.log(obj_str);
// ...
});
For reading/traversing json objects in javascript, take a look at this simple tutorial. It can represent a good starting point for understanding the basic principles, and unless you provide an example of your json data, also your only choice to perform your data extraction.

Use Javascript array on PHP function be it on the same file or on another along with other functions

I know this question has been asked multiple times but I still have not found an answer to the specific problem I am facing. I am creating a web page and whenever a user clicks a specific button, I want the page to get data from a dynamically created table on a php function. Since PHP doesn't have a built-in function to do so, at least not to my knowledge, I have decided to use Javascript to convert the table data into am array with JSON elements. I figured out to do that by using:
function getTableData(){
var array = [];
var headers = [];
$('#tablaListado th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#tablaListado tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).html();
});
array.push(arrayItem);
});
actualizarCostos(array);
}
I am using this data in another function to parse it on to a PHP function:
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
<?php updateCosts(JSON.stringify(array[i]))?>
}
}else{
alert("Input must be array");
}
}
I know the way above is not the correct way of doing so, I have also read up on AJAX a little bit. My question is: is there a way I can call a function on the same file? If not, is there an easier way to use AJAX on another PHP file which will have the function I need along with other ones?
Thank you all!
The answer to the question is: No. You can't use a variable from Javascript inside PHP. You can generate valid Javascript code with PHP, but not the other way around. The reason is that PHP is processed in the server side, while Javascript is processed on the client side (the browser)
NOTE: You can process Javascript on the server side as well using Node, but you are already using PHP. How to use server side javascript with NodeJs is out of the scope of the question.
Now, you can create that table with PHP, and not use JS at all. I'm assuming your data is in an array format, so look into PHP loops like foreach. Then build a table by echoing (see echo('')) the table tags (table, thead, tbody, td, tr, etc).
You can't use a variable from Javascript inside PHP
because
Javascript (Client side) and PHP (Server Side)
So in current context what you can do is as follows
Client Side
function actualizarCostos(array){
if(array.constructor === Array){
// Here you need ajax
$.post('http://myhost.mydomain.com/update_cost.php',
{ table_data : array }, function(response){
// do something after getting response
});
}else{
alert("Input must be array");
}
}
Server Side (update_cost.php)
<?php
function updateCosts($item)
{
// do something here...
}
if(isset($_POST['table_data']))
{
foreach($_POST['table_data'] as $index => $item)
{
// do something here
updateCosts($item);
}
// Response back - if needed
echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}
?>

Read CSV from server and put contents into drop down list in html or javascript

I have a csv file sitting on my server (using Apache 2) which I would like to "read" when a webpage loads. After reading the contents (two columns that are comma separated), I want to have one column be the display contents of a drop down list and the other column be the "data" contents. For instance, if I had a csv where the first row was [1,"me"], I would want the "me to be displayed to the user and the 1 to be the data that I could understand (selected value).
I know very little on javascripting and html (still learning), so any simple help would be much appreciated. To recap:
How do I read CSV file off my server (currently doing localhost)?
How do I parse this CSV file and add each row as an entry of a dropdown list?
Thanks!
How do I read CSV file off my server (currently doing localhost)?
First, you'll need to fetch the data from the CSV file so you can work with it as a native JavaScript object. Using jQuery's $.get() method, you can make an asynchronous request to the server and wait for the response. It would look something like this:
$.get(csv_path, function(data) {
var csv_string = data;
//Do stuff with the CSV data ...
});
How do I parse this CSV file and add each row as an entry of a dropdown list?
This can be accomplished with a for loop and some jQuery:
(function() {
var csv_path = "data/sample.csv",
var renderCSVDropdown = function(csv) {
var dropdown = $('select#my-dropdown');
for(var i = 0; i < csv.length; i++) {
var record = csv[i];
var entry = $('<option>').attr('value', record.someProperty);
dropdown.append(entry);
}
};
$.get(csv_path, function(data) {
var csv = CSVToArray(data);
renderCSVDropdown(csv);
});
}());
Note that this code calls a CSVToArray method, which you must also define in your code. An implementation can be found here, thanks to Ben Nadel: Javascript code to parse CSV data

using and storing json text in JavaScript

I'm making a 2D, top-down Zelda-style web single player rpg...
I'd like to store dialog in JSON format...
Currently I'm getting the json as an external javascript file. The json is stored as such in js/json.js:
function getJson() {
var json = {
"people" :
[
{//NPC 1 - rescue dog
etc...
Then I use it in my main game javascript file as such <script src="js/json.js"></script>..`
var json = getJson();
Then use it as such:
Labels[index].text = json.people[index].dialogs.start.texts[0];
Does it matter if I keep the json as a js file in a javascript function? Or should it be stored as a .txt file then parsed?
Thanks!
It does not matter but JSON data is also JavaScript so store it as .js and later on you can add more data related functions to it if needed, btw your data file already has a getJSON function so it doesn't make sense to store it as .txt
On the other hand if an API is serving this data it need not have any extension at all.
It's better off storing the data in pure JSON format and retrieving it via jQuery.getJSON() or an XMLHttpRequest, if you're using vanilla JavaScript. Otherwise, it looks like you're adding getJson() to the global scope, which may result in a conflict if you have another getJson() defined elsewhere.
So you could have a dialog.json that looks almost the same as what you have now, just without the unnecessary getJson() function:
{
"people" :
[
{//NPC 1 - rescue dog
...
}
]
}
If you choose to use jQuery:
var dialog;
$.getJSON('json/dialog.json', function(data) {
dialog = data;
// Asynchronous success callback.
// Now dialog contains the parsed contents of dialog.json.
startGame();
});
Keeps your data separate from your logic.

Accessing JSON values with a variable

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).
try to list all properties from data, to have sure the data is being returned:
for (var p in data){
if (data.hasOwnProperty(p){
alert(data[p]);
}
}
It's not your solution but with this you can know how your data is coming.

Categories

Resources