Print an element array in jquery - php

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));
}
});
});

Related

JSON syntax with AJAX call and jquery each loop

I have an AJAX call that returns the data from PHP
echo json_encode( $json_response);
and the result is as follows
[{"name":"Sprouts.......}]
I then loop through it with JQUERY
$.each($.parseJSON(data), function(i, obj) {
var name = (obj.name);
var address = (obj.address);
});
This works perfectly fine, but I am trying to add a name (child) to it so that I can have other children. I used the following
json_encode(array('storedata' => $json_response))
to add the name storedata which returns
{"storedata":[{"name":"Sprouts....
I have tried looping through with
$.each($.parseJSON(data.storedata), function(i, obj) {
var name = (obj.name);
var address = (obj.address);
});
but something is wrong with the syntax because the data.storedata is undefined.
What is the correct syntax and/or correct way to do this. Thank you for any and all help.
The problem is that you are trying to access storedata before parsing the string into an object, so you need to replace $.parseJSON(data.storedata) with $.parseJSON(data).storedata:
$.each($.parseJSON(data).storedata, function(i, obj) {
var name = (obj.name);
var address = (obj.address);
});

Processing json where the number of json array is dynamic

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]);
}
}

Get response array from jquery ajax to php

I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.
// selector de campaƱa en reporte de clientes mas activos
$(document).ready(function(){
$('.selector-camp').change(function(){
var campaing = $('.selector-camp').val();
$.post( "../campanas/test", { 'camp': campaing },
function( data ) {
alert( data.result );
}, "json");
});
});
As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do
function( data )
{
createTable(data.result); //pass your json array to JS function
}, "json");
//here i create js function
function createTable(array)
{
var array = JSON.parse(array); //decoding from json format
//So if i have numbers in array like [1, 2, 3, 4] and want
//to create row with them something like this should be done
var table = document.createElement("table"); //create table
var tr = document.createElement("tr"); //create row
for(var i=0; i<array.length; i++)
{
var td = document.createElement("td");
td.innerHTML = array[i];
tr.appendChild(td);
//for each array element creates cell and appends to row
}
table.appendChild(tr);
//Then you can have some empty div and append table to it
var div = //your empty div
div.appendChild(table);
}
Please check below php prototype code as per your requirement.
From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.
<?php
test();
function test(){
$camp = htmlspecialchars($_POST['camp']);
isset($camp)&&!empty($camp)?
$data = array('test_key'=>'test_value');
echo json_encode($data);
}
?>

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);
}

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