I have this code:
var sidebars = {};
var counter = 0;
// Loop through all already crated sidebars
$('.custom_dynamic_sidebars li').each(function(event) {
sidebars[counter] = $(this).text();
counter++;
});
var sidebars_string = JSON.stringify(sidebars);
but it gives me this string:
{\"0\":\"aa\",\"1\":\"bb\"}
Here is javascript which sends array to the server:
$.ajax({
url:"/welit_2/wp-admin/admin-ajax.php",
type:'POST',
data:'action=dynamic_sidebars&sidebars='+sidebars_string+'',
success:function(results) {
console.log(results);
}
});
does anyone know what am I doing wrong?
thx for your time
So I found a solution If you run stripslashes() on the JSON string before you output it, it works fine
Related
I am trying to parse Excel data to JSON to feed drop downs in HTML. I am having a hard time getting this to work. I have looked all over the web. I am new to javascript so i find it overwhelming.
There seems to be a lot of scripting and to make this work. If anyone can help and explain how to set this up i would be greatly appreciative.
Thanks All,
HAppleknocker
This article explained clearly how to make the JSON object from a Excel File. After getting the JSON object as a string you can use it to do anything.
In here used sheet js and sample javaScript code available on GitHub.
How to convert Excel data into JSON object using JavaScript
<script>
$(document).ready(function(){
$("#fileUploader").change(function(evt){
var selectedFile = evt.target.files[0]; //Get the ExcelFile
var reader = new FileReader();
reader.onload = function(event) {
var data = event.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
document.getElementById("jsonObject").innerHTML = json_object;
})
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsBinaryString(selectedFile);
});
});
</script>
Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});
I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible
I am only getting back the first result in the array, and want to retrieve all the available results.
function runForm(){
$("#stock_news").html("");
var stockSymbol = $("input").val();
//very long str
var newsStocks = "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Ffinance.yahoo.com
%2Fq%3Fs%3D"+stockSymbol+"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22yfi_headlines
%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa'&format=json&diagnostics=true&callback=";
//getJSON
$.getJSON(newsStocks, function(data) {
var headlines = data.query.results.a[0];
//newsStr
newsStr = "<h3 style='text-decoration:underline'>Current Headlines</h3><p><ol>
<li><a href='"+headlines.href+"'>"+headlines.content+
"</a></li></ol></p>";
$("#stock_news").html(newsStr);
});
You haven't given enough information, but I could guess that this var headlines = data.query.results.a[0]; is your issue. It would seem like the other results are there, but you're filtering them out. console.log(data) and console.log(data.query.results) and look at what all is in there. Otherwise, update your question with more information.
Update:
This is a very basic ajax call (with jQuery) and a for loop to loop through and use each result.
$.get('path/here', function(data) {
//if your data is an array
for (var i=0; i<data.length; ++i) {
var item = data[i];
console.log(item);
}
});
Here's a live demo (click), but I'm not going to use the ajax data since the path is not valid.
Here's the same example, but using $.each. I prefer the for loop...why use jQuery for something so simple?
$.get('path/here', function(data) {
$.each(data, function(item, index) {
console.log(index);
});
});
How do I access my data from outside the getJSON command?
//LOAD JSON
$.getJSON("users.js", function(data) {
numberOfPieces = data.users.length;
alert("Loaded "+numberOfPieces); // <------WORKS
});
//Select a piece
var pieceSelected = Math.floor(Math.random() * (numberOfPieces));
alert("pieceSelected: "+data.users[pieceSelected].Name); // <------RETURNS "data is not defined"
Thank you!
Your issue is that function parameters are scoped to that function and inaccessible outside of the function. By using a variable outside of the scope, things should work as expected.
var piecesData;
//LOAD JSON
$.getJSON("users.js", function(data) {
piecesData = data;
numberOfPieces = data.users.length;
alert("Loaded "+numberOfPieces); // <------WORKS
});
//Select a piece
var pieceSelected = Math.floor(Math.random() * (numberOfPieces));
alert("pieceSelected: "+ piecesData.users[pieceSelected].Name);