Processing json where the number of json array is dynamic - php

I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?

You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.

Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);

To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>

success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}

Related

JQuery for-loop with variable

I have a table out of different MySQL data. I want to highlight cells with the same ID in it on hover. I did that with a simple jQuery, the script is almost working but you see I've got the var nr and want the integer i to be added to the class string. What is my mistake, why isn't it working? If you change the var nr = '.id_' + i; to a static variable like var nr = '.id_2'; it is working.
for (i = 0; i < 10; i++) {
var nr = '.id_' + i;
var bgcol = $(nr).css('backgroundColor');
$(nr).hover(
function(){
$(nr).css({"background":"yellow"});
},function(){
$(nr).css({"background":bgcol});
});
}
http://jsfiddle.net/Nkdny/210/
Solution, thanks to Karl-André Gagnon: http://jsfiddle.net/Nkdny/215 Look in the comments for details.
You're missing an echo in front of your php statement.
<?php echo $amount; ?>

Print an element array in jquery

I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});

jQuery Looping JSON Data

I have created APIs to retrieve data from my server and then I get the data with json format like this :
{
"items": [
{
"2013-03-28": 1771,
"2013-03-29": 1585,
"2013-03-30": 1582,
"2013-03-31": 1476,
"2013-04-01": 2070,
"2013-04-02": 2058,
"2013-04-03": 1981,
"2013-04-04": 1857,
"2013-04-05": 1806,
"2013-04-06": 1677,
"2013-04-07": 1654,
"2013-04-08": 2192,
"2013-04-09": 2028,
"2013-04-10": 1974,
"2013-04-11": 1954,
"2013-04-12": 1813,
"2013-04-13": 1503,
"2013-04-14": 1454,
"2013-04-15": 1957,
"2013-04-16": 1395
}
]
}
How do I looping with my json data dynamically using jQuery?
My code :
<html>
<head></head>
<body>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url: "myurl.php",
cache: false,
dataType: "jsonp",
success:function(data){
if(data==''){
alert('Fail');
}else{
alert('Success');
}
}
})
});
</script>
</body>
</html>
How do I modify my jQuery to get data dynamically following the date that the data will change every day as in the example I wrote above data??
Thanks before...
There are a few things to consider with your example data, but in your case, the following will do the trick:
var importantObject = data.items[0];
for(var item in importantObject ){
var theDate = item;//the KEY
var theNumber = importantObject[item];//the VALUE
}
Here is a working example
But what does all this mean?...
First of all, we need to get the object that we want to work with, this is the list of dates/numbers found between a { } (which means an object) - an array is defined as [ ]. With the example given, this is achieved like so:
var importantObject = data.items[0];
because items is an array, and the object we want is the first item in that array.
Then we can use the foreach technique, which effectively iterates all properties of an object. In this example, the properties are the date values:
for(var item in importantObject ){ ... }
Because we are iterating the properties, item will be the property value (i.e. the date bit), so item is the date value:
var theDate = item;//the KEY
Finally we get the number part. We can access the value of any given object property by using the string value of the property index (relative to the object), like so:
var theNumber = importantObject[item];//the VALUE
If you already know which date you want the value for, then you can access it directly like so:
var myValue = data.items[0]["2013-04-16"];//myValue will be 1395 in this example
Using jQuery.each() loop through the items
$.each(data.items[0], function (key, value) {
console.log(key + ": " + value);
var date = key;
var number = value;
});
DEMO HERE
You can use the jQuery each function to do this. For example like this:
$.each(data, function(k, v) {
// Access items here
});
Where k is the key and v is the value of the item currently processed.
//get your detail info.
var detail = data.items[0];
$.each(detail, function(key, val) {
console.log(key + ": " + val);
}

php jquery json multiple value

i am learning on how to parse json using jquery
PHP
foreach($cars as $car)
{
$output['carID'][] = $car->carID;
$output['carName'][] = $car->carName;
}
echo jsonEncode($output);
JSON
{"carID":["1","2"],"carName":["BMW","Mercedez Benz"]}
My javascript
$.getJSON('/cars.php', { carID: carID }, function(data) {
$.each(data, function(i,item) {
for(j=0; j < item[item.carName]; j++) {
console.log(item[item.carName][j]);
}
});
});
I think my code is entirely wrong because its not working.
how can i get the value inside of ["1","2"] ?
Thanks for the help.
It's not the "value of 1" that you're looking for. It's the value at index 0, which happens to be "1".
["1","2"] is the value of carID, and it is an array.
Try accessing it this way:
alert(item.carID[0]); // will alert "1"
alert(item.carID[1]); // will alert "2"
As I know, array indexes start from "0" in many languages, so you need something like this to get array values in your code;
var data = {"carID":["1","2"],"carName":["BMW","Mercedez Benz"]};
$.each(data.carID, function(key, val){
var i = 0, id;
while(id = val[i++]) console.log(id);
});
// or just simply use
console.log(data.carID[0]);

jQuery Splitting of 2 values

I am trying to split the values of an array i'm generating through an autosuggest.
The output of the values are as such:
[
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]
I want to extract the values 12 & 11 and store as a variable so I can save these to a database through php. This is what I have tried so far and to no success:
<script type="text/javascript">
var arr = $(".as-values").val().split(",");
var category_1=arr[0];
var category_2=arr[1];
var category_3=arr[2];
</script>
I only have 3 categories as I have set a limit on the amount they can add (3).
Many thanks in advance.
That looks like json. Why not just access it as a native JS structure?
var json = $(".as-values").val();
data = jquery.parseJSON(json)
alert(data[0].name); // solid fuel fire installers
The array is an array of objects, not strings, so why not treat them as such?
<script type="text/javascript">
var arr = $(".as-values").val();
var category_1=arr[0].value;
var category_2=arr[1].value;
var category_3=arr[2].value;
</script>
Not sure what you're trying to do. Does this sound like it?
var values = '[{"value":"12","name":"Solid Fuel Fire Installers"},{"value":"11","name":"Oil Engineers & Boiler Fitters"}]';
values = $.parseJSON(values);
var submitValues = {};
$.each( values, callback(i, element){
submitValues[element.value] = element.name;
});
The string you're trying to use is valid json so you should be able to just decode the string with native functions in js that would be JSON.parse(json_string, reviver) in php you would use json_decode($json).
Decoding the string will give you an object/array you should be able to work with easily.
(This is what you want right?)
Is your question how to access an element by value of its property? You could do this:
var elements = [
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]; // Retrieve however you want
var element;
for(var i = 0; element = elements[i]; i++) {
if(element.value == 11) {
// It's number 11, for example
}
}
Of course you should probably put that in a function:
function findByProperty(elements, property, value) {
var i, element;
for(i = 0; element = elements[i]; i++) {
if(element[property] === value) return element;
}
return null;
}
// ... define 'elements' as before
var numberEleven = findByProperty(elements, 'value', "11");
Since you already have an array of a valid json you dont need to parse it. Just try this.
var arr = [
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]
var category_1=arr[0].name;
var category_2=arr[1].name;

Categories