How to get JSON from PHP to JS? - javascript

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.

Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});

Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}

Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/

If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH

Related

Converting JSON Data to String

Edit: This first paragraph got cut off somehow during posting
I am a retired farmer not a coder. I do dabble with html/js but am very far from competent at either. What I am working on is modifying the html interface for my weather station. It is for my own in house use only. The JSON I am trying to use is hosted by the weather station software on an Raspberry pi on the URL listed a couple paragraphs down.
I will just post what I'm trying to do rather than anything about what I have tried. The following code produces what I want - being able to add a temperature to an html page using the tag "extratemp". It also truncates the sample temp from 69.0 to 69.
The sample data is actually contained in a JSON on the host computer (../api/extra/temp.json). Again, my html page displays the desired "69" using the code below, I just cannot seem to replace the sample data (var str = line) with the live data from the JSON.
$(document).ready(function() {
var str = '{"data":[["Sensor 1","69.0","°F"],["Sensor 2","0.0","°F"],["Sensor 3","0.0","°F"],["Sensor 4","0.0","°F"],["Sensor 5","0.0","°F"],["Sensor 6","0.0","°F"],["Sensor 7","0.0","°F"],["Sensor 8","0.0","°F"],["Sensor 9","0.0","°F"],["Sensor 10","0.0","°F"]]}'
var jsonData = JSON.parse(str);
document.getElementById("extratemp").textContent = Math.floor(jsonData.data[0][1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extratemp"></div>
Any help will be greately appreciated.
Thanks
You can use jQuery's getJSON function to download the JSON file & handle it by means a callback function:
$.getJSON( "../api/extra/temp.json", function( data ) { ... });
According with your data, the JSON object is an array of arrays, each item of the main array containig 3 values:
[ ["Sensor 1", "69.0", "°F"], [...], ...]
Once again using jQuery library you can use the $each function to iterate thorugh each item of the main array, then accessing any particular subitem by index (0,1,2).
$.each(data, function( index, item ) {
console.log("Item =>", {item[0], item[1], item[2]} );
});
See: https://api.jquery.com/jquery.getjson/, http://api.jquery.com/jquery.each/

Adding to localStorage with JavaScript and Jade

Having issues with Jade and the way the data is passed to it when it is rendered.
I am trying to save the data which is in [{key1: "val1", key2: "val2"}, ...}];
format but having issues as it shows up as the result below.
Result
key: xyz value:[{"artist":"Lady Gaga",...
This is the code I am working with on the server-side Node.js which is passing it fine ...
res.render('musics', {
title: 'site',
result: JSON.stringify(result)
});
This is the code I am having issues with because of the way I have to call result in jade...
script
function local (arr) {
var i;
i = "#{result}";
localStorage.setItem('xyz', i);
}
console.log('stored');
local();
The quotes around result are messing it up but without them I get an error for unexpected identifier...
Any suggestions or if it might be better to go an ajax route through Backbone(which is what I am using with the client-side) I am willing to, just to put some pointers out - the data is being scraped and through selections of a form post - so the data comes back after the post and is a on time transfer, so if I did an ajax call it would have to include the post and the get, otherwise i am not sure of how to receive it... maybe res.json(result) on the server side, but then the page needs to render somehow... Open to suggestions. Thanks! Ultimately I want it to go into localStorage without the " around everything.
your jade snippet should look like this then:
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(" +result + ");})();"
by using != you tell jade to not escape the following content, and on the clientside you have to stringify again before puting your data to local storage.
As an improvement to #greelgork's answer:
This is for JSON array
script!= "(function() {var items = []; items = JSON.parse(localStorage.getItem('Stored_items')); console.log(JSON.stringify(items)); items.push(" + JSON.stringify(product) + "); localStorage.setItem('Stored_items', JSON.stringify(items)); })();"
Anyways, pushing an item into localStorage needs to be stringified before inserted into localStorage hence, #greelgorke's answer should be modified so:
single item
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(result)); })();"
So the JSON.stringify is outside the string just like all the other javascript code is,
This is what I use in my project and it worx
Credit Push JSON Objects to array in localStorage
if usersList.length
script.
const userList = !{JSON.stringify(usersList)}
localStorage.setItem('xyz',JSON.stringify(userList))
const loader = document.querySelector(".loader");
loader.className +=" hidden";

LungoJS Json, fill content returned into a list

i am a Java Developer and i need to create a SIMPLE app, as i need this to run into ios & Android i decided to try it using lungoJS, my main problem is that i dont know much JavaScript.. :(
well i have created the prototipe of the app using lungo, but now i need to fill a list with the response (on Json) from my server. I saw in lungos api the function that is used to get a Json request. looks like this:
var url = "http://localhos:8080/myService";
var data = {id: 25, length: 50};
var parseResponse = function(result){
//Do something
};
Lungo.Service.json(url, data, parseResponse, "json");
//Another example
var result = Lungo.Service.json(url, "id=25&len=50", null, "json");
my http request is indexed from 1 to 4 so for each element would be "www.myapp.com/api/1" "www.myapp.com/api/2"
....
my question is, hoy could i get the answer (json) of my request and how do i select items for example if i only want the "name" or "surname"...
thanks, hope some1 could help me :)
I solved my problem long time ago, i will share it:
function some_function(callback) {
var my_number = $$.get('http://app.com/applications/3.json',{ }, function(api) {
obj=api;
template="{{#name}}\
\
{{/name}}";
html=Mustache.render(template,obj);
$$('section#main article#main-article').html(html); //Painting Json obtained on my HTML
}
);
;
callback(my_number);
}
// call the function
some_function(function(num) {
// this anonymous function will run when the
// callback is called
console.log("callback called! " + num);
});
This code uses the obtained Json to Prototype HTML, useful to load images or data from server and not stored on local.
BR, Kike

$.get with dynamic data names?

I am having an issue trying to set the data name or the objects being passed in. I am writing a system that uses AJAX to send requests to the server which then returns the necessary data. However, I am trying to make things generic to where if the developer adds more "slates" then it will automatically send the request on its behalf. The code looks as following:
$(document).ready(function() {
$(".slate").each(function(){
$.get("requests.php", { $(this).attr('name') : "true" }, function(data){
});
});
});
in other words it takes the name of the element and applies it to the query string. JavaScript doesn't seem to like the
$(this).attr('name')
in the syntax which is understandable since it expects just text (not a var or a string). Is there a way to make this work? Any help is greatly appreciated!
$(document).ready(function() {
$(".slate").each(function(){
var data = {};
data[$(this).attr('name')] = "true";
$.get("requests.php", data, function(data){
});
});
});

Help with passing multidimensional JSON array to jQuery autocomplete via AJAX

I'm trying to implement a live search on my photos site using jQuery and the autocomplete plugin. Everything works when I specifiy the data locally:
var data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ];
However when I move this to PHP, jQuery is unable to parse the results properly. I'm really not sure what's going on here. My current code is below:
<script>
$(document).ready(function(){
var data = '/livesearch';
$("#aut_field").autocomplete(data, {
formatItem: function(item) {
return item.text;
}
}).result(function(event, item) {
location.href = item.url;
});
});
</script>
And my PHP script prints a multidimensional array in the following format:
{"1":{"text":"Google Website","url":"http:\/\/www.google.com"},
"2":{"text":"Yahoo Website","url":"http:\/\/yahoo.com"},}
However when I do alert(item.text) the variable says undefined.
If I do alert(item) I see the entire string as outputted by PHP.
I tried playing around with eval() but I'm not sure where to put it or how to get JS to actually interpret the data. Thanks for your help. Sample code specific to my implementation is appreciated.
The issue is with the php code.
Your job is to mimic the strcuture of the working javascript array. See php's json_encode()
try in your php this pattern:
[
{"text":"Google Website","url":"http:\/\/www.google.com"},
{"text":"Yahoo Website","url":"http:\/\/yahoo.com"}
]
And your PHP script return a multidimensional array/object mix.
If you insist (you blow up your var with several "text:" amd "url;") it shou1ld be:
[[{"text":"Google Website","url":"http:\/\/www.google.com"}],[{"text":"Yahoo Website","url":"http:\/\/yahoo.com"}]]
Better:
var x=[["Google Website","http:\/\/www.google.com"],["Yahoo Website","http:\/\/yahoo.com"]];
If you want to jump to Yahoo Website: var url=x[1][1];
Or:
var x={"Google_Website":"http:\/\/www.google.com","Yahoo_Website":"http:\/\/yahoo.com"};
If you want to jump to Google_Website: var url=x["Google_Website"];
My tip: visit enter link description here

Categories