Parse 2-dimensional array retrieved as string from database - javascript

I am building an array of data that is being retrieved from the cells of a table. The resulting array looks something like this:
[["","","",""],["","9/2/14","","9/17/14"],["","","89ol",""],["","687k","","9-0["p/"],["","245g","245g","356h"],["","","",""],["","","4j6","467j"],["","","9/9/14",""]]
I'm saving the data to a MySQL database as a string in one field. I now need to retrieve that data and iterate through it to repopulate the table.
I'm getting the data to an $.ajax function as a string in the above format.
How can I get the individual cell data to populate the cells properly?
UPDATE:
Here's the php code I'm using to retrieve the data:
$queryGetUserTaskNotes = "SELECT userProgressNotes FROM userProgress WHERE userProgressUserID = $userID AND userProgressSiteID = $siteID and userProgressNotesTable = '" . $taskTableID . "'";
$resultGetUserTaskNotes = #mysqli_query($dbc,$queryGetUserTaskNotes);
if ($resultGetUserTaskNotes) {
$taskNotes = mysqli_fetch_assoc($resultGetUserTaskNotes);
echo $taskNotes['userProgressNotes'];
}
Here's how I'm getting the data from the php script
function GetTaskNotes(siteID,tableID) {
$.ajax({
url: 'script.php',
data: {getTaskNotes:'true', userID:userID, siteID:siteID, tableID:tableID},
success: function(data) {
console.log('GetTaskNotes data: ' + data);
}
});
}
As for what I've tried so far, I've been working with how to parse the string on the js side in the success function. JSON.parse(data) didn't work and frankly, I'm not sure what else to try.
Thanks!

Unless you have very special needs in terms of performance/logic, I would say it would be better to use a hash of name/value pairs (a.k.a an object) where the names in the hash correspond to actual fields in the database. That being said, lets say for the sake of argument that the arrays are populated by .push() calls, in which case a simple nested for loop should work:
'use strict';
var array = JSON.parse(string);
var cell, row, i, j;
var table = document.createElement('table');
for (i=0; i < array.length; ++i) {
row = document.createElement('tr');
for (j=0; j < array[i].length; ++j) {
cell = document.createElement('td');
cell.innerHTML = array[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.appendChild(table);
Where string is the string you get back from the DB when its time to repopulate.

I think the steps here for you are going to be:
In PHP, provide a URL that JS can do a GET against that will return the data. The way that is structured and looks will depend somewhat on what framework (if any) that you're using. Be sure to return that data as JSON using a built in PHP JSON encode method.
In JS, do a GET like so:
$.ajax({
url: 'your url here',
type: 'GET',
success: function(data) { console.log(data); }
});
In your success function, I assume you'll handle iterating over your object and inserting it into the DOM. I would look at jQuery's $.each() method for that. When it comes to "populating the cells properly", it'd be helpful to see your HTML and JS in a jsFiddle or something.
Good luck!
References:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jquery.each/

Related

Query multiple JSON tables inside javascript for loop

Codepen with working example.
I'm still new to javascript, so I could be going about this the wrong way. If you can suggest a better way for me to do this, I would greatly appreciate it; always love to learn a new, better way!
Here goes:
I use the array iD to generate the URL's of the 10 JSON tables I'm pulling data from.
var set = $('.set');
var iD = [
"od6",
"o9mpc0w",
"ol96q2e",
"olqcdyz",
"ojfsm09",
"oijguh3",
"obmuic4",
"oup920g",
"ohwlz67",
"omk1ruv"
];
function photoSet(){
var idLength = iD.length;
for (var i = 0; i < idLength; i++) {
Once I iterate through the array, I use an ajax call to query each one.
$.ajax({
url:'https://spreadsheets.google.com/feeds/cells/1TBjwQNVRMNzuyZRxr9yX-fUKWw6gpUX69o9PQc79COs/' + iD[i] + '/public/values?alt=json',
async: true,
dataType: 'jsonp',
success: photos});
After they're queried, I retrieve the data from the cells of each JSON table and use it as an image src to insert into the document.
function photos(results){
for(var a = 1; a <= 1; a++) {
var imageEntry = results.feed.entry[a].content.$t;
set.append('<li class="image"><img src="'+ imageEntry +'"/></li>');
console.log(imageEntry);
}
}
}
}
photoSet();
Here's the issue: I need to have the resulting images in the same order as the array iD
Every time the page loads, the images are displayed in a different order. I know it's doing this because the queries are coming in at slightly different times, thus resulting in a different order every page load.
Does it have something to do with storing the ajax calls in variables, then grabbing them one at a time? Do I need another callback? As the nesting gets more complex, I get more confused :/
I've been searching high and low for how to do this, but just can't seem to figure it out. It seems with each new discovery I make, a new problem arises. Such is the nature of code, I suppose. Thank you all for your help :)
Also, I saw this question, but am having trouble figuring out how to apply its answer to my code. If I do, I'll remove this question promptly.
You can add id to the building of the li-
set.append('<li class="image" id="sequnce"><img src="'+ imageEntry +'"/></li>');
e.g
<li class="image" id="1"><img src="d.gif"/></li>
<li class="image" id="4"><img src="d.gif"/></li>
<li class="image" id="3"><img src="d.gif"/></li>
And after you finish to retrieve all the data from the Json you can sort the li.
You can use this link How to sort LI's based on their ID
In our iD for loop we change the ajax to something like this...
var allResults = {}, successCount = 0;
$.ajax({
url: 'https://spreadsheets.google.com/feeds/cells/1TBjwQNVRMNzuyZRxr9yX-fUKWw6gpUX69o9PQc79COs/' + iD[i] + '/public/values?alt=json',
async: true,
dataType: 'jsonp',
success: function( results ) {
successCount++;
allResults[ iD[i] ] = photos( results );
if ( successCount == iD.length ) {
//All data received...
for (var i2 = 0; i2 < idLength; i2++) {
set.append( allResults[ iD[i2] ] )
}
}
}
});
Now instead of calling photos directly we call a anonymous (unnamed) function which keeps a track of successful ajax request count and stores the images HTML in new object allResults with key matching iD array. When success count is equal iD.length we know all requests have been made and al HTML is saved in allResults object. We then run a for loop like we did for ajax requests and populate data in sequence of iD array.
The photos function, doesn't immediately append html into set now but returns all data, it should look like this...
function photos(results){
returnString = '';
for(var a = 1; a <= 1; a++) {
var imageEntry = results.feed.entry[a].content.$t;
returnString += '<li class="image"><img src="'+ imageEntry +'"/></li>';
console.log(imageEntry);
}
return returnString;
}
Hope that helps...

Ajax + Django - combining form.serialize and stringified JSON object in "data" parameter

I am trying to pass stringified json parameter and serialized form into Django view like this:
JS:
var selected_items = legalEntitiesVendorAgreements_selectize.items;
var data = $form.serializeArray();
for (var i = 0; i < selected_items.length; ++i)
{
data.push({'legal_entity_own_id' : selected_items[i]});
}
View:
def my_view (request):
list_data = json.loads(request.body)
for x in list_data:
// Do smth with x['some_predefined_field']
Basically, I have two big questions here:
How do I combine $m_form and json_str in the data parameter
How does my Django view code change in the part of parsing the request parameter. Specifically, will json.loads(request.body) and the for cycle still be working, and will Django syntax my_form = MyForm(request.POST) still be valid
And don't know even when to start from. I've examined this, but I've got a bad feeling that $m_form + json_str is not the right way here. Help me please!
You're trying to mix and match form data and JSON here. You need to choose one, and convert the other into that format.
For example, you could add your form data into the obj before serializing:
form_data = $m_form.serializeArray();
json_obj["form_data"] = form_data;
json_str = JSON.stringify(json_obj);
and now your Django view can access the deserialized form data via list_data["form_data"].
Or, you could post your form in the standard way, with the JSON as a value inside that form:
form_data = $m_form.serialize();
form_data["json_data"] = json_obj;
$.post(url, form_data);
Now your Django view will get a standard POST dictionary, and you can access most of its elements as normal but specificially deserialize the json_data element.
form = MyForm(request.POST)
json_data = json.loads(request.POST["json_data"])
(the form should just ignore the additional field).
At last I got it working. Would like to share my solution:
jquery:
json_obj = [];
for (var i = 0; i < selected_items.length; ++i)
{
json_obj.push({'legal_entity_own_id' : selected_items[i]});
}
var data = $form.serialize() + '&json_data=' + JSON.stringify(json_obj);
$.post ('/create_vendor_agreement/' + vendor_id + '/', data);
View:
my_django_form = MyDjangoForm(request.POST) # As usual
list_data = json.loads(request.POST['json_data'])
for x in list_data:
do_something_with(x['legal_entity_own_id'])

Looping Through an Array of Arrays returned by JSON API Call

I am writing an App using Intel XDK, and I am using a Wordpress API to obtain user information. The url produces the following:
{"status":"ok","0":{"id":2,"username":"testshop","shopname":"shopname","url":"","displayname":"testshop","nickname":"Test Shop","avatar":"80","longitude":"54.5591894,-1.237610600000039","gender":"Menswear","mensCats":"Tech Geek| Indie Lad| Vintage Gent| Casual Bloke","womensCats":""},"1":{"id":3,"username":"testShop2","shopname":"","url":"","displayname":"testShop2","nickname":"Test Shop 2","avatar":"","longitude":"54.5576249,-1.2475360999999338","gender":"Womenswear","mensCats":"","womensCats":"Indie Babe| Vintage Queen"}}
I have another API call, which when called, only returns one array, and I can access this information fine, as I do not have to loop through. However, I am not sure how to loop through the above. Below is the code I use to get the JSON:
$.getJSON(url, function(json){
var name = json.nickname;
}
Could anyone help with the best way to iterate through the data.
Thank You
Since your code doesn't produce an array but an object then you can do something like this:
$.getJSON(url, function(json){
if(json.status === "ok")
{
var keys = Object.keys(json).filter(function(str){ return str !== "status" });
for(var i = 0 ; i < keys.length; i++)
{
console.log(json[keys[i]]);
}
}
}
JSFIDDLE.

Using values from JSON array

I have an AJAX returning JSON array from PHP.
I have the JSON array successfully returning to the AJAX request, and i am cycling through the results.
Q. How do i use the specific values from the array in this instance?
Currently i can alert the string of the results.
I wish to be able to use the values independently.
The array outputs in a string: {"btn_col_preset_id":"1","btn_col_preset_title":"Pink","btn_col_preset_bg":"#ff66ef","btn_col_preset_text":"#16f3ed"}
The js/json
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
//console.log(myObject[i]);
// alert(JSON.stringify(myObject[i]));
val1 = ???; // this is what i am trying to achieve
}
}
Updated
The full Ajax in which i am trying to get a single value based on key. This outputs empty alerts.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
beforeSend: function() {
},
success: function(data) {
var myObject = data;
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
//console.log(myObject[i]);
// alert(JSON.stringify(myObject[i]));
alert(myObject["btn_col_preset_id"]);
}
}
}
});
Either set
header('Content-type: application/json');
in your php which will tell the javascript to interpret the data as JSON.
Or use
JSON.parse();
in your javascript to convert the string to an object.
First of all, you need to parse the JSON-encoded string then you can use it as an object in Javascript
var data = JSON.parse(result_of_the_request), i;
for(i in data)
{
alert("The item '" + i + "' has a value of '" + data[i] + "'");
}
Note that, if you're using jQuery, there is an awesome shortcut to get the result of the resquest directly as a Javascript object. It's called $.getJSON().

XML to javascript array with jQuery

I am new to XML and AJAX and am only a newcomer to Javascript and jQuery. Among other job duties I design our website. A deadline is very near, and the only way I can think of to do this project well is with AJAX. I have a document full of XML objects such as this one repeating:
<item>
<subject></subject>
<date></date>
<thumb></thumb>
</item>
I want to create an array of all elements and their child elements. I've been reading jQuery tutorials on AJAX for hours and don't even know where to start because they all assume a certain level of javascript proficiency. If someone could show me the easiest way to loop through all elements and put their children into an array, I'd appreciate it tons.
Using jQuery, $.ajax() your XML file, and on success pass retrieved data with each, like:
var tmpSubject, tmpDate, tmpThumb;
$.ajax({
url: '/your_file.xml',
type: 'GET',
dataType: 'xml',
success: function(returnedXMLResponse){
$('item', returnedXMLResponse).each(function(){
tmpSubject = $('subject', this).text();
tmpDate = $('date', this).text();
tmpThumb = $('thumb', this).text();
//Here you can do anything you want with those temporary
//variables, e.g. put them in some place in your html document
//or store them in an associative array
})
}
});
I wrote this.. pretty simple way to take a welformed XML response/string and parse it with jquery and then convert to array.
var response = '<?xml version="1.0" encoding="UTF-8"?><root><node1>something</node1></root>'
var xmlDoc = $.parseXML( response );
var myArray = getXMLToArray(xmlDoc);
alert(myArray['root']['node1']);
//Pop up window displaying the text "something"
function getXMLToArray(xmlDoc){
var thisArray = new Array();
//Check XML doc
if($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner array
var NextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = $(xmlDoc).find(this.nodeName).text();
}
});
}
return thisArray;
}
Hope this helps!!
If you are using jQuery then parseXML will suck an entire xml doc into a usable data structure.
I added to your script Troublesum
function getXMLToArray(xmlDoc){
var thisArray = new Array();
//Check XML doc
if($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner array
var NextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = [];
$(xmlDoc).children(this.nodeName).each(function(){
thisArray[this.nodeName].push($(this).text());
});
}
});
}
return thisArray;
}
It now also supports many children with same name in XML. f.e
XML being
<countries>
<NL>
<borders>
<country>Germany</country>
<country>Belgium</country>
countries.NL.borders[1] will give Germany.

Categories

Resources