Using values from JSON array - javascript

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().

Related

how do i get values from multidimensionnal table in javascript?

i have an array of urls. I insert into it values like this :
var replacementArray=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
This is an example of one such URL array:
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
I have to compare the shorturl of this array with a string. If the strings match then i retrieve the url. Here is my first attempt at doing this :
var chaine="xfm1";//this is an example
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j][shorturl]==chaine){
var url= replacementArray[url];
}
This seems to not be working. Why is that?
Associative arrays with arbitrary keys don't exist in javascript
You can have data that works as an associative array, but then you need to use an object to store the keys.
The example data you provided is not valid JS. It is an object of arrays instead of being an array of objects. For your function to work as expected, the data
needs to be in the following format:
[
{
url: 'tuto.com',
shorturl: 'xfm1'
},
{
url: 'youtube.com',
shorturl: 'xfm2'
},
// etc...
]
The [] is for creating an array, which will have numeric indexes only.
The {} creates objects that can store key-value pairs like an associative array in other languages.
So in your function you can loop through the array indexes by incrementing i and access the values associated with your keys using replacementArray[i].shorturl or replacementArray[i]['shorturl'] (notice the string) - the way you do it is up to your preference, they both work the same.
Hope this helps!
var arr=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
insert(arr,"google.com", "xfm.io1");
insert(arr,"gogle.com", "xfm.io2");
insert(arr,"gole.com", "xfm.io3");
function getUrl(yourVariable){ //chaine
for(var j=0;j<arr.length;j++)
if (arr[j].shorturl == chaine){
return arr[j].url;
}
return null;//not found yourVariable
}
var chaine= "xfm.io1"; //your Short URL
console.log(getUrl(chaine)); //testing the function
First of all you given: (which is not an acceptable data structure)
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
which must be like this: (array of objects)
replacementArray:[
{url:"tuto.com", shorturl:"xfm1"},
{url:"youtube.com", shorturl:"xfm2"},
{url:"google.com",shorturl:"xfm3"}]
Then to get shortUrl code will be like
function getUrl(yourVariable){ //chaine
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j].shorturl == chaine){
return replacementArray[j].url;
}
return null;//not found yourVariable
}
Read over these corrections/suggestions:
As others have mentioned, you should create an array of objects, instead of an object with arrays
Reference the property 'shorturl' either using array syntax (i.e. replacementArray[j]['shorturl']) or dot notation (i.e. replacementArray[j].shorturl). If you use array syntax then the property needs to be in a string literal (unless you create a variable to represent the field - e.g. var shorturl = 'shorturl';).
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var url; //declare url here so it won't be undefined if no url is found in the array
for (var j = 0; j < replacementArray.length; j++) {
if (replacementArray[j]['shorturl'] == chaine) {
//need to reference replacementArray[j] instead of replacementArray['url']
url = replacementArray[j]['url'];
}
}
console.log('url: ',url);
Consider using Array.prototype.find() or a similar functional-style method (e.g. filter() if you wanted to find multiple values) to determine the site with the matching shorturl value. That way you don't have to worry about creating and incrementing the iterator variable (i.e. j) and using it to reference elements in the array. For more information, try these exercises about functional programming in JS.
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var foundSite = replacementArray.find(function(site) {
return (site.shorturl == chaine);
});
if (foundSite) { //if we did find a matching site
var url = foundSite.url;
console.log('url: ',url);
}
Try this in your 'for' loop:
if(replacementArray[j].shorturl == chaine){
// Do stuff here...
}
With [shorturl], you are accessing a property name based on the value of shorturl, which is not defined.

How to extract a single value from an array

I am very new to JavaScript so forgive me if this is a dumb question:
I have this Ajax call:
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
console.log('success', data)
}
});
The value "data" produces an array:
success [{"price":"120.00"}]
What I need, is to extract the value of price (the 120) and use it later in an addition.
How do I get this value out?
You can do:
var price = data[0]['price'];
or:
var price = data[0].price;
Either of these work like this: you are accessing the first value in your array named data, and then the field in that value named "price". Assigning it to a variable isn't necessary.
However, you would probably want to do this inside a loop, iterating over all values of data so that, in the case the first element of data isn't what you want, you can still catch it. For example:
data.forEach(function(i) {
console.log(data[i].price);
//do stuff with the value here
});
data has an array of objects with a price property. Access the first object in the array and parse it's price as a number:
parseFloat(data[0].price);
Test it,
You must parse JSON string before using it!
var data = JSON.parse('[{"price":"120.00"}]');
var Price = data[0].price; // 120.00
//OR IF it's Single And not Array
var Price = data.price; // 120.00
Since your response is an array, access the first position, and then access the object property:
data[0].price; //"120.00"
var result = {},
sum = 0;
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
result = data[0];
}
});
sum = parseFloat(result.price) + 2.25;

Parse 2-dimensional array retrieved as string from database

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/

How to insert a json object into an unordered list

I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.
This is what is the json object is created from:
[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]
Literally all i want to do is put this into a to show up on a web page.
My current code:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
$('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
//$('#myList').html("<li>obj[2].period</li>");
});
}
This successfully prints out the list with Triassic then Jurrasic.
I would prefer to do this in Jquery but javascript is okay.
Thank You.
You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
var inner = '';
for(i=0; i < obj.length; i++) {
inner += "<li>"+obj[i].period+"</li>";
}
$('#myList').html(inner);
});
}
I'm sure there's a cleaner way using jQuery but that should work
If you're want to use the jQuery syntax, process like this:
var listElement = '';
$.each(obj, function(index, value) {
listElement += '<li>' + data[obj].period + '</li>';
})
$('#myList').html(listElement);

jQuery AJAX, array not getting serialized

I'm trying to post a multidimensional array using jQuery. I have verified that immediately before sending the array, it contains the contents it is supposed to (by checking specific elements and alerting them).
However, when I send the request, it's sending this:
Array
(
[undefined] =>
)
Here's the whole thing...
var mainArray = new Array();
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = new Array();
var id = $(this).attr("id");
subArray["id"] = id;
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
// This displays what I would expect
alert(mainArray[0]['id']);
alert(mainArray[1]['id']);
alert(mainArray[2]['id']);
alert(mainArray[3]['id']);
// This doesn't work
$.ajax({
type: 'post',
url: 'test2.php',
data: mainArray,
success: function(data) {
$("#test").html(data);
}
});
Any ideas? My understanding is that jQuery is supposed to serialize the array automatically?
Your code is totally wrong!
At first, give your 2-dimensional array some name for example items (or whatever you want). Second, you can't use Array for creating hash (theoretically you can but it's bad and jQuery doesn't understand this), you have to use object literals {} instead of Array, use Array only with numeric keys (use literals [] for creating array instead of new Array). Your code:
var mainArray = [];
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = {};
subArray["id"] = $(this).attr("id");
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
$.ajax({
type: 'post',
url: 'test2.php',
data: { items: mainArray },
success: function(data) {
$("#test").html(data);
}
});
P.S.: you can use $.param (convert js objects into query string) to figure out your mistakes
Stringyfy the data before you send it to the server
Also it's a better practice to send the data as a Map..
Instead of this
data: mainArray,
Try
data: { 'arr': JSON.stringify(mainArray) },

Categories

Resources