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";
Related
I have written a POSTMAN call to a server that responds with a list of items in JSON like below:-
{
"count": 6909,
"setIds": [
"1/7842/0889#001",
"2/4259/0166#001",
"ENT0730/0009",
"9D/11181#002",
"1/9676/0001#001",
"2/4718/0001#004",
"2/1783/0044#001",
"1/4501/0001#001",
"1/2028/0002#002",
"2/3120/0079#001",
"2/1672/0024#001",
"2/3398/0064#001"
}
I want to make calls to another server using the value of the setID each time and iterate through all of these so that I end up calling the server thousands of times to verify the response from that server. The problem I have is that the second server expects the set id to be in a form where the forward slashes are converted to underscores and the hashes to dots, so
"1/7842/0889#001"
becomes
"1_7842_0889.001"
I have code that converts one to the other in POSTMAN
var jsonData = pm.response.json()
for (var i=0; i<jsonData.setIds.length; i++)
{
var new_j = jsonData.setIds[i].replace (/#/g, ".");
var new_i = new_j.replace (/\//g, "_");
}
})
This works fine line by line it creates the right thing in the console of POSTMAN but obviously what I really need to do is save the entire JSON in the right form to a file and then read from that file line by line using the corrected data. I don't seem to be able to save the data in a file in the right form using my code and I suspect I am missing something simple. Is there a way to write a file line by line from in side postman or in a script and manipulate the data as I'm creating it?
Alternatively I guess I could read from the JSON I have saved i.e. the full response and iterate through that manipulating the data as a pre-request script?
I have tried to do something like this using environmental variables - so in my first call I do:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable('setIds', JSON.stringify(jsonData));
and then in my second call to the express server where I want to send my payload I run a pre-request script that I thought would work using the env variable but this fails as it doesn't seem to like the {...
SyntaxError: Unexpected token {
I think there are probably some neat ways of solving this either doing all of this outside of POSTMAN in javascript but I'm a little lost where to start. Any help appreciated
Would tell you are plaing with content, but not setting it back to JSON object ??
jsonData.setIds[i] = new_i;
can help or you can use 2x replace it in a string and convert back to make it easier (in case there are no / or # somewhere else).
var src = {
"count": 6909,
"setIds": [
"1/7842/0889#001",
"2/4259/0166#001",
"ENT0730/0009",
"9D/11181#002",
"1/9676/0001#001",
"2/4718/0001#004",
"2/1783/0044#001",
"1/4501/0001#001",
"1/2028/0002#002",
"2/3120/0079#001",
"2/1672/0024#001",
"2/3398/0064#001"
//...
]
}
var str = JSON.stringify(src, null, 4);
str = str.replace(/\//g,'_').replace(/#/g,'.');
console.log(str);
var res = JSON.parse(str);
console.log(res);
Before I start, I'm complete beginner and I hope I'm not misusing terms when I ask my question.
I'm starting off writing an HTML5/Javascript application using Intel XDK to query barcodes of videos games from an online api, and I only need one piece of the JSON result (the title of the game) to then go on and use within my app.
The JSON result looks like this:
{"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
All I want to use in my app is that very first 'productname' entry.
The JSON is from an api provider I have an account with so it's on a remote URL for examples sake we'll call the URL: http://JsonIs.here
I want to be able to query the JSON URL and return "The Elder Scrolls V: Skyrim" as a string which I can then go on to use elsewhere in the application.
I've got my barcode scanning working, I can create the GET request URL already, I just don't know where to start calling that URL and then returning the small piece of information I need.
You can use jQuery's $.getJSON for this. The method returns a promise which has a nice easy-to-understand API.
var productName;
$.getJSON('http://JsonIs.here').then(function (data) {
productName = data[0].productname;
});
A couple of things to note here. 1) getJSON is an asynchronous process, so productName won't be immediately available, so you might have to restructure your code a little to account for this. You can't, for example do this:
var productName;
$.getJSON('http://JsonIs.here').then(function (data) {
productName = data[0].productname;
});
console.log(productName); // undefined
You may find this article useful as it covers how to return a value from an async process in depth.
2) getJSON automatically parses the JSON so you don't have to which is why, in the example, I've called the argument data and not json to save confusion.
To simulate you getting your JSON
var getJSON = function(){
return '{"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}';
};
a function that gets the JSON and creates an array that holds all your productnames
var getProductName = function(){
// get the JSON_string ;)
var JSON_string = getJSON();
// convert it to an obj.
var JSON_obj = JSON.parse(JSON_string);
//create something to store your data in, you don't need to do this ofcourse
var r_productNames = [];
for(var key in JSON_obj){
if(JSON_obj.hasOwnProperty(key)){
r_productNames.push(JSON_obj[key].productname);
}
}
// et voila, you have an array of all the productnames, returned by your request.
console.log(r_productNames);
};
It works for me ;)
Json comes with a key value pair and the indexing starts with 0. Hence json[0] that means json in first index. json[0].productname here productname is the key which will give the value in return
var json = {"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
alert(json[0].productname);
Try using ajax
$.ajax({
type: 'GET',
url: 'http://JsonIs.here',
dataType: "json",
success: function(data) {
console.log(data[0].productname)
},
error: function(data) {
}
});
Using ajax you can try to get the data from the url and you can get the data in the success of the request
Here you go. However I find "0" as key in your JSON response somewhat not seen till today. It is better practice to start of with a character.
Your JSON response have one object. You can access the element in the object by index. Here on 0th index you have your data. The reason we are accessing it as a[0].key where key represent name of key you want to access from the object.
This is how you can get the data from JSON and use it in your application to achieve rest of your functionality as per your question.
var a = {"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
a[0].productname;
I have a server side function which returns content of HTML page:
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
Meteor.methods({
sayHello: function() {
var response = Meteor.http.call("GET", "http://google.com");
return response;
}
});
});
And I have client code where I am trying to get title from this HTML page:
'click .add_tag' : function(e,t) {
//Session.set('editing_tag_id', e.target.id);
Meteor.call("sayHello", function(err, response) {
var title = $(response.content).find("title").text();
var title2 = $(response).find("title").text();
var title3 = response.content.match(/<title[^>]*>([^<]+)<\/title>/)[1];
alert(title3);
});
I would like to get jQuery version ('title' or 'title2'), but it doesn't works. It returns empty string.
'Title3' - version works fine, but I don't like regexps. :)
Is there any way to make 'jQuery'-versions works ?
As requested, I will reiterate my comment as an answer...
I would stick with the regex, even though you don't like it. There is a huge overhead of constructing a DOM element that is essentially an entire page, purely for the purpose of parsing a small amount of text. The regex is more lightweight and will perform adequately in slower browsers or on slower machines.
Wrap response.content in a <div> and then do a selection off of that. This way you have a proper structure to start from rather than an array that you might actually be getting.
var $wrap = $("<div></div>").html(response.content);
$wrap.find("title").text();
An example of what is probably going on: http://jsfiddle.net/UFtJV/
Don't forget one thing : you should never return HTML to client. You should return Json (or even Xml) that your client will transform into Html using Template.
You are doing like a lot of dev doing Bad Ajax.
Don't forget : "only data on wire, not display".
So there should not be any problem coz, on response you just have to take data from Json formatted response and inject it inside your Template.
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
I did a search on stackoverflow and did not find the exact thing that I am looking for.
I am using an in-house server side language, like PHP. I have two drop downs A and B on a web page. B gets populated with values from database based on the input from A. Simple problem right? So I fire an onchange even on A and call a javascript function, which does a post Ajax call to the server side code. This server side code should do the query and return the results to a responseHandler which should give the results as post data to B. The problem I am having is in the server side code, when I do the query I get a bunch of rows as array. How do I pass that array to the Javascript responseHandler ? I am trying to send is JSON but not with much success. Below is the server side code:
// If - then - else , !, query, and get are functions in the language
{if {! {query output post get_data_qry_str}}{then
//JSON object
{
"status":"error",
"errorMessage":"Query did not succeed"
}
}{else
//JSON Object
{
"status":"success",
"successMessage":"how do I pass output here ?"
}
}}
output.values={1,2,3}
If I say {get output} it passes "", if I say {get output.values} it passes 1.
Let me know if I should post more clarity on the syntax of the server side language.
If you are using PHP: http://php.net/manual/en/function.json-encode.php
So after reading #Hyangelo comments, I wrote my own serializing function. I thought I will put it here just in case someone else wants to see it. Below is the JSON for the success part
{
"status":"success",
"successMessage":"[
// for, length, get, set are functions here
{for x=0 to {length output} do
{get comma}
"{get output.values[x]}"
{set comma ,}
}
]"
}
I also learned, that in Javascript, to send arrays as post_data to a post Ajax call, you can do this,
for(var i=0; i < arr.length; ++i)
{
post_string += '&values=' + arr[i];
}
instead of
post_string = '&values=' + arr;
It might be trivial, but I am new to JS and took me a while to figure.. Thanks #Hyangelo
Sorry could not post a reply untill 8 hrs..