SQLike - understanding the basics - javascript

I'm trying to use the query engine
SQLike and am struggling with the basic concept.
The JSON I'm using as my data source comes from my PHP code, like so:
var placesJSON=<? echo json_encode($arrPlaces) ?>;
Here's a sample JSON:
var placesJSON=[{"id":"100","name":"Martinique","type":"CTRY"},{"id":"101","name":"Mauritania","type":"CTRY"},{"id":"102","name":"Mauritius","type":"CTRY"},{"id":"103","name":"Mexico","type":"CTRY"},{"id":"799","name":"Northern Mexico","type":"SUBCTRY"},{"id":"800","name":"Southern Mexico","type":"SUBCTRY"},{"id":"951","name":"Central Mexico","type":"SUBCTRY"},{"id":"104","name":"Micronesia, Federated States","type":"CTRY"},{"id":"105","name":"Moldova","type":"CTRY"}];
I understand (via this reference) that I first need to unpack my JSON like so:
var placesData = SQLike.q(
{
Unpack: placesJSON,
Columns: ['id','name','type']
}
)
And the next step would be to query the results like so:
var selectedPlaces = SQLike.q(
{
Select: ['*'],
From: placesData,
OrderBy: ['name','|desc|']
}
Lastly, to display the results in the browser I should use something like:
document.getElementById("myDiv").innerHTML=selectedPlaces[0].name
This doesn't work. The error I get is: selectedPlaces[0].name is undefined.
I'm pretty sure I'm missing out on something very simple. Any hints?

"Unpack" converts an array of arrays, like [["John", "Peterson", 38, 28000], ["Vicki", "Smith", 43, 89000]] into an array of objects. Since your Json is already in this format, there's no need to unpack it.

Related

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

Issue with i18n parsing

I am getting JSON fro backend, which I need to parse on UI.
For all the keys from the JSON, I have to translate them and show on UI.
Eg:
i18n.t('key') will give me translated value.
But for some keys like 'name', 'date'
Eg:
i18n.t('name')
translation is giving following output
"key 'translation:name (en-US)' returned a object instead of string."
Could you please help me how to deal with this scenerio.
If you have for example following JSON from your service
{
"i18n": {
"name": "translation1",
"name2": "translation2"
}
}
You can just use it as following
var mytranslation = getTranslationsFromService();
console.log(mytranslation.i18n.name) //result: translation1
console.log(mytranslation.i18n.name2) //result: translation2
var getTranslationsFromService = function() {
//Get result from service, where the result looks like the JSON above.
}
I hope I could help.
Kind regards.

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Passing an array of ints with node-soap

I'm using node-soap with a service and everything works but I need to send an array of ints and I find that I can only send the first one because I can't find the correct way to build a JS object to represent this array.
I've been looking at similar questions but I couldn't find the answer to my question.
I need to generate a XML property like the following one:
<ns1:ArrayOfInts>
<!--Zero or more repetitions:-->
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:ArrayOfInts>
by passing an object that contains the array:
soapObject = {
somefields,
"ns1:ArrayOfInts": {
Something goes here
},
};
Any idea how to create the JS object?
I had the same problem and used $xml property to add raw XML to the request and attributes to set the arr namespace:
var fields = [2904, 3089, 4531];
soapObject.arrayOfInts = {
attributes: {
'xmlns:arr': 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'
},
$xml: fields.map(function(value) {
return '<arr:int>' + value + '</arr:int>';
}).join('')
};
This code will generate the following request:
<ns1:arrayOfInts xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:arrayOfInts>

Getting started with extJS

I don't get what I'm doing wrong.
I'm trying to populate a form from a JSON string from the server and it doesn't work. I get nothing at all back. I examine the object and it's undefined. I've been beating my head against the wall for 3 days now. I need a simple example that works and I'll build from there.
Here's the simple example that I've been trying to use:
var messages = new Ext.data.JsonStore({
url: '/user/' + user_id,
method: 'GET',
root: 'user',
fields: [
{name: 'user_id'},
{name: 'first_name'}
],
listeners: {
load: messagesLoaded
}
});
messages.load();
function messagesLoaded(messages) {
console.log(messages);
}
Here's my JSON string:
{"success":"true","user":{"user_id":"2","first_name":"Test","last_name":"Test","email":null,"password":null,"city_id":"6379","birth_date":"2009-06-09","gender":"F","created_on":"2009-06-01 17:21:07","updated_on":"2009-06-14 17:20:14","active":"Y","cuisine_id":null}}
I really don't see what I'm doing wrong, but my JSON string isn't loading. Thanks!
Ok so you're almost there, but one problem. The root ("user" in this case) has to be an array. Even if it's an array with only 1 object. Ext.data.JsonReader (the default reader for a Ext.data.JsonStore) only accepts an array of results.
So your javascript looks just fine, but the JSON object returned by the server needs to look more like this.
{
"success":"true",
"user": [{
"user_id":"2",
"first_name":"Test",
"last_name":"Test",
"email":null,
"password":null,
"city_id":"6379",
"birth_date":"2009-06-09",
"gender":"F",
"created_on":"2009-06-01 17:21:07",
"updated_on":"2009-06-14 17:20:14",
"active":"Y",
"cuisine_id":null
}]
}
One more thing, consoloe.logging your store object will produce something like [Object] in Firebug... not too useful. You should either console.dir it, or log your actual data instead.
One comment about loading your form, once you get past loading your JSON (even though this example does not show that). Make sure your form is actually rendered before trying to load it with data, e.g. if trying to use something like form.loadRecord. Otherwise you'll end up with an empty form and no errors.

Categories

Resources