How can I get JSON from WebSQL - javascript

I have a little app, that uses WebSQL for data's storage.
I want to sync this data with web-server (PHP+MySQL)
My main problem that I have no idea how can I create a JSON from WebSQL to transfer it.
//view the result from DB on a web-page
$('body').html('<ul id="dataAllHere"></ul>')
mybase.init.getAll = function(){
var database = mybase.init.db;
database.transaction(function(tx){
tx.executeSql("SELECT * FROM table", [], function(tx,result){
for (var i=0; i < result.rows.length; i++) {
item = result.rows.item(i).item;
due_date = result.rows.item(i).due_date;
the_type = result.rows.item(i).the_type;
id = result.rows.item(i).ID;
showAll(item,due_date, the_type, id);
}
});
});
}
function showAll(item,due_date, the_type, id){
$('#dataAllHere').append('<li>'+item+' '+due_date+' '+the_type+' '+id+'</li>');
}
mybase.init.getAll();
I'm not really familiar with JSON and I'll be happy about any help and advice.

Basically you create an object/array and encode it to json, which looks the same, but string formatted. For your code:
var myJson = [];
for (var i=0; i < result.rows.length; i++) {
item = result.rows.item(i).item;
due_date = result.rows.item(i).due_date;
the_type = result.rows.item(i).the_type;
id = result.rows.item(i).ID;
showAll(item,due_date, the_type, id);
myJson.push({item: item, due_date: due_date, the_type: the_type, id: id});
}
$.ajax({
method: 'post',
data: myJson,
type: 'json',
url: 'target.php'
})

you can simplify the loop if you need to
just push every thing from the result to json.
for (var i=0; i < result.rows.length; i++) {
myJson.push(result.rows.item(i));
}

Related

How can I get nested json array data with varying key names and content inside?

I have a json array I am trying to get data out of. Here is what I am looking at currently:
I have below the jquery/javascript I used to generate this and give me this data that I can play with and the important part here is the nodes object below, this is what gets the different layouts:
var getPosts = function() {
$.ajax({
url: '/wp-json/posts?type=case-studies',
data: {
filter: {
'name': _last
}
},
success: function ( dataS ) {
//List some global variables here to fetch post data
// We use base as our global object to find resources we need
var base = dataS[0];
console.log(base);
var postContent = base.content;
var postTitle = base.title;
// Main Image ACF object
var featuredImage = base.meta.main_image;
// Gallery ACF object
var nodes = base.meta.work_content;
// Simple ACF object
//var textArea = base.meta.work_content[1];
var items = [];
for(var i = 0; i < nodes.length; i++)
{
var layout = nodes[i];
var layoutNames = layout.acf_fc_layout;
items.push( layout.acf_fc_layout['gallery']);
console.log(layout);
};
$('<div>', {
"class":'loaded',
html:items.join('')
}).appendTo(projectContainer);
},
cache: false
});
};
** edited here with json itself **
The json file here
The order these items comes in is very important and it cannot be manipulated and what I need to do is get each object and append into a container with each object using a different markup layout.
Each object has acf_fc_layout as its key that is different, my question is how can I differentiate the different data I get with that key and offer different markup for each one? I know that some will need further loops created to get images etc and I can do that. The other important thing to remember here is that there will be multiple of the same acf_fc_layout items but with different content inside them.
Cheers
var items = [];
var layoutNames = [];
for(var i = 0; i < nodes.length; i++)
{
var layout = nodes[i];
layoutNames.push(layout.acf_fc_layout);
console.log(layout);
};
//now loop on each layoutNames
$(layoutNames).each(function (){
for(var i = 0; i < nodes.length; i++)
{
var layout = nodes[i];
if(layout.acf_fc_layout==$(this).val())
//Perform Operation either image / video / page layout
console.log(layout);
};
})

retrieve value in unnamed json array url

I'm struggling to retrieve some value on a json in this url:
http://go-gadget.googlecode.com/svn/trunk/test.json
the url data looks like this:
[
{
"key":{
"parentKey":{
"kind":"user",
"id":0,
"name":"test 1"
},
"kind":"smsgateway",
"id":5707702298738688
},
"propertyMap":{
"content":"test1 content",
"date":"Dec 12, 2013 2:58:57 PM",
"user":"test1"
}
}]
By ignoring the "key", I want to access the value of "propertyMap" object (content,date and user) using javascript code.
I have tried this code but it couldn't get the result:
var url = "http://go-gadget.googlecode.com/svn/trunk/test.json";
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
var content = json[i].propertyMap.content;
console.log('content : ', content);
var user = json[i].propertyMap.user;
console.log('user: ', user);
var date = json[i].propertyMap.date;
console.log('date : ', date);
}
});
(unsuccessful code here http://jsfiddle.net/KkWdN/)
considering this json can't be change, is there any mistake I've made from the code above or there's any other technique to get the result?
I just learn to use javascript and json for 1 month so response with an example is really appreciated.
--edited: I change [].length to json.length, now I'm looking for the answer to access the url
That would be something like :
$.getJSON("http://go-gadget.googlecode.com/svn/trunk/test.json", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.content;
var user = map.user;
var date = map.date;
$('#date').text(date);
$('#nohp').text(user);
$('#content').text(content);
}
});
But the request fails, as no 'Access-Control-Allow-Origin' header is present on the requested resource, so you're being stopped by the same origin policy
What do you think [].length; would evaluate to .
It is 0 , so it would never go inside the for loop.
Other than that you code looks ok.
Replace your for loop as below
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
Also you seem to be accessing a API as part of the different domain.
So you need to use CORS or JSONP to get this working if you want to retrieve data from a different domain.
Change:
for (var i = 0; i < [].length; i = i + 1) {
to
for (var i = 0; i < json.length; i = i + 1) {
DEMO here.
How about using something like the following
In your case, say the object is myObj, I would get the value like this
var content = fetchValue(myObj, [0, "propertyMap", "content"], "");
var date = fetchValue(myObj, [0, "propertyMap", "date"], new Date());
var user = fetchValue(myObj, [0, "propertyMap", "user"], "");
Just to make sure that we send a default value in case we do not get the desired ojbect. The beauty of this approach is that now you do not have to worry about array or objects nested in the structure. The fetchValue function could be something like below.
function fetchValue(object, propertyChain, defaultValue){
var returnValue;
try{
returnValue = object;
forEach(propertyChain, function(element){
returnValue = returnValue[element];
});
}catch(err){
return defaultValue;
}
if(returnValue == undefined) {
returnValue = defaultValue;
}
return returnValue;
}
Adding the forEach function
function forEach(array, action){
for(var x in array)
action(array[x]);
}

First Time Ajax request getting two url different elements

var memberURL;
var memberAva;
var memberName;
var members = data.find('.userdata');
for (var j = 0; j < members.length; j++) {
membername = $(members[j]).find('.username').text();
memberURL = $(members[j]).find('.username').attr('href');
}
memberAva = $('#advanced-profile-right img:eq[0]');
$.ajax({
url:"/viewonline",
type:"GET",
data: {memberURL, memberName}, //What should i do here?
success: function() {
$.ajax({
url: memberURL,
type:"GET",
data: memberAva
}).done(function() {
$('.user_info_on').append('<div class="on_name"><img src="' + memberAva + '"/></div>');
}
});
});
What I am trying to get from the first ajax request is the members URL and the Members name- then on success make another ajax request to the Members URL (each) and get the Members Avatar. Then on done post the data that is retrieved. Code is not working, and not sure what I should do?
I tried posting on two .get()s though I guess this is the only way? Anyways anyone have suggestions and tips for me?
The .get() that works-
$(function () {
$.get('/viewonline', function (data) {
data = $(data);
var members = data.find('.userdata');
for (var j = 0; j < members.length; j++) {
var membername = $(members[j]).find('.username').text();
var memberURL = $(members[j]).find('.username').attr('href');
});
$('.user_info_on').append('<div class="on_name"><img src=""/></div>'); //In between source of image would be memberAva from the other .get() request.
}
}, 'html');
});

How can I list my twitter followers list in WinJS.UI.ListView

I want to list all my twitter followers in my WinJS.UI.ListView.
WinJS.xhr({
url: "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=" + twitterusername,
responseType: "json"
}).then(
function (xhr) {
var json = JSON.parse(xhr.responseText);
var a = [];
a = json.ids;
//
// now what next?
//
},
function (error) {
myListView.textContent = error;
}
);
I get all my twitter follores id by json.ids.
But next how to find their screen names and prifile pictures and main thing how to bind them with my ListView control. Becouse I had bind simple my static data into ListView but for this example i have no idea.
You have to make another call for each ids to api.twitter.com/1/users/show.json?user_id=json.ids[i].
After you receive all callbacks, you have to create an array with objects that have title, text and picture properties. After that simply bind it with you list.
The following code is an exemple (not tested, don't know if it's functional, but it should point you in the right direction)
var followersCallback = function(xhr){
var json = JSON.parse(xhr.responseText);
var promises = [];
// make promises for each user id (call to twitter to get picture/name/description)
for (var i = 0; i < json.ids.length; i++){
var promise = WinJS.xhr({
url: "https://api.twitter.com/1/users/show.json?user_id=" + json.ids[i],
responseType: "json"
});
promises.push(promise);
}
var dataArray = [];
// join those promises
WinJs.Promise.join(promises)
.then(function(args){
//when you get callback from all those promises
for (var j = 0; j < args.length; j++){
//not sure if parse is needed
args[j]=JSON.parse(args[j].responseText);
//populate your data array
var obj = {};
obj.title = args[j].name;
obj.picture = args[j].profile_image_url;
obj.text = args[j].description;
dataArray.push(obj);
}
//bind your data to the list
var dataList = new WinJS.Binding.List(dataArray);
});
};
WinJS.xhr({
url: "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=" + twitterusername,
responseType: "json"
}).then(
followersCallback,
function (error) {
myListView.textContent = error;
}
);

Use a FOR loop within an AJAX call

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:
I never used the for loop in JS, but seems familiar anyway.
The way the loop is made, obviously wont work:
for (i=0;i<required.length;i++) {
var required[i] = $('#'+required[i]).attr('value');
This will create the variables i want, how to use them?
HOPEFULLY, you guys can help me!!! Thank you very much!
required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];
function ajaxrequest() {
for (i = 0; i < required.length; i++) {
var required[i] = $('#' + required[i]).attr('value');
var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: dataString,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.
jQuery:
required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];
function ajaxrequest() {
var params = {}; // initialize object
//loop through input array
for (var i=0; i < required.length; i++) {
// set the key/property (input element) for your object
var ele = required[i];
// add the property to the object and set the value
params[ele] = $('#' + ele).val();
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: params,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}
Demo: http://jsfiddle.net/kPR69/
What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;
var obj = {};
$('.save').each(function () {
var key = $(this).attr('id');
var val = $(this).val();
if (typeof (val) == "undefined")
val = "''"
obj[key] = val;
}
Then send obj as the data property of your AJAX call....
There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.
I would suggest using pre-written library, a few I included below.
http://jquery.malsup.com/form/#validation
https://github.com/posabsolute/jQuery-Validation-Engine
Otherwise the follow would get you close. You may need to covert the array into a string.
var required = ['nome','sobrenome'];
function ajaxrequest() {
var values;
for (i = 0; i < required.length; i++) {
var values[i] = $('#' + required[i]).attr('value');
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: values,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}

Categories

Resources