get value customize of output json_encode() by jQuery.? - javascript

I insert data with json_encode() in database, want get just values name_units on row units in database. how is it?
This is output database in code php(by json_encode()):
my_table=>units=>name_units
[{"name":"jack","units":[{"name_units":"salam","price_units":"74,554","checkbox_units":["minibar","mobleman"]},{"name_units":"mokhles","price_units":"4,851,269","checkbox_units":["mobleman","tv"]},{"name_units":"fadat","price_units":"85,642","checkbox_units":["minibar","mobleman","tv"]}]}]
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: 'url',
data: dataObj,
cache: false,
success: function(data) {
/////////////////////*HERE/////////////////////
$.each(data, function(a, b) {
//alert(b.units[name_units]);
$('<p id="' + b.units[name_units] + '">' + b.units[name_units] + '</p>').appendTo('.class');
});
/////////////////////HERE*/////////////////////
};
})

Try this:
$.each(data, function(a, b) {
$.each(b.units, function(c, d){
$('<p id="' + d.name_units + '">' + d.name_units + '</p>').appendTo('.class');
});
});
Also, its a good idea to use jQuery templates for this scenario

units is an array, therefore you need to reference an item in the array or loop through all items in that array. b.units[0].name_units
Edit: like i said, you would have to loop through them.
$.each(b.units,function(i,unit){
alert(unit.name_units);
});
you could also use a for loop if you would prefer.

Related

How to iterate through json arrays

I'm stuck in a script here, not sure how to get it to print in the div I set up. I imagine it's something related to how I'm handling the response.
The response in chrome devtools looks like this:
{
"[\"record one\", \"/description\"]": 0
}
I've attempted to use both each and map to iterate the data out but so far not going anywhere. I'm brand new to js and jquery, so the script is mostly from reading and examples.
Maybe some kind of nested loop? Here is my code -
$(function() {
return $('#myslider').slider({
range: true,
min: 0,
max: 20,
values: [1, 20],
stop: function(event, ui) {
var max, min;
min = ui.values[0];
max = ui.values[1];
$('#range').text(min + ' - ' + max);
$.ajax({
url: '/dir_scan',
type: 'get',
data: {
min: min,
max: max
},
dataType: 'json',
success: function(response) {
var albums;
albums = response;
$.each(albums, function(index, obj) {
var albumname, artist, li_tag;
li_tag = '';
albumname = obj.AlbumName;
artist = obj.Artist;
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
}
});
}
});
});
As Will said in the comments, the JSON looks off.
But, you're on the right track of using .each, as it looks that you're returning an array of objects.
Here's an example of what to do:
var li_tag = '';
$.each(albums, function(index, obj) {
var albumname = obj.AlbumName;
var artist = obj.Artist
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
Additionally, 'albums' should be set to the returned response of the success function. You're potentially creating a bunch of headache to try and decipher from the window.location; especially since the json example looks malformed. And, any work done with the data returned from the ajax call, should occur in the success function.
Here is how iteration worked for this situation. Comments in code -
success: function(response) {
var albums;
// side issue - but I had to clear the div to get a complete refresh
$('#result').empty();
albums = response;
$.each(albums, function(key, value) {
var albumname, li_tag, path;
li_tag = '';
// I found I had to do this parseJSON call otherwise
// I had no correct key/value pair, even though I had set dataType
// to JSON
albumname = jQuery.parseJSON(key);
path = albumname[1];
li_tag += '<li ><a href=/album' + encodeURI(albumname[1]) + '>' + albumname[0] + '</a href></li>';
$('#result').append($(li_tag));
return console.log;
});
Actually, value in the code is just the index number, but I had the actual key/value pair separated by commas, so again the parseJSON seemed to be the only way it would work. This, despite trying things like split and substr. Hope my answer is clear if not I can edit.

Access Field Values from JSON serialized django object

I have a problem which is proving to be harder to find an answer for than I imagined. I am using AJAX to update the select options based on a response from another select box. I am able to correctly retrieve the right list of objects, serialized as json, but I can't access any of the field values of the object.
View:
def choose_group(request):
team_id = request.POST['team_id']
groups = WorkoutGroup.objects.filter(team_id=team_id)
data = serializers.serialize('json', groups)
return HttpResponse(data, content_type='application/json')
Javascript/jQuery:
$('#team').on('change', function(){
var team_id = $(this).val();
$.ajax({
type: 'POST',
url: '/create_workout/choose_group/',
dataType: 'json',
async: true,
data: { csrfmiddlewaretoken:'{{ csrf_token }}', team_id: team_id },
success: function(data) {
var groups = $('#group');
$(groups).children().not(':first').remove();
if (data.length >= 1){
$.each(data, function(group){
$(groups).append('<option value=' + group['fields']['id'] + '>' + group['fields']['group_name'] + '</option>');
});
}
}
});
})
I get an error with all the ways I've tried to access the fields of each object (such as the id and group_name of the objects, as defined in the model). The error is 'cannot read property of undefined'.
EDIT:
I have also tried just creating a ValueQuerySet and dumping it using simplejson, but I still cannot access any fields within, just 'undefined'. Also, if I alert through each group, I get just the index of the iteration within the group list.
New View:
def choose_group(request):
team_id = request.POST['team_id']
groups = WorkoutGroup.objects.filter(team_id=team_id).values('id','group_name')
#data = serializers.serialize('json', groups)
return HttpResponse(simplejson.dumps(list(groups)), content_type='application/json')
and my Javascript now looks like this:
$('#team').on('change', function(){
var team_id = $(this).val();
$.ajax({
type: 'POST',
url: '/create_workout/choose_group/',
dataType: 'json',
async: true,
data: { csrfmiddlewaretoken:'{{ csrf_token }}', team_id: team_id },
success: function(groups_list) {
var groups = $('#group');
$(groups).children().not(':first').remove();
if (groups_list.length >= 1){
//json = JSON.parse(data);
$.each(groups_list, function(group){
alert(group)
$(groups).append('<option value=' + group.pk + '>' + group.fields.group_name + '</option>');
});
}
}
});
})
Accessing the serialized django object
To access the serialized django object you need to first parse the data variable like this:
var obj = JSON.parse(data);
And then you can access the fields of each object Individually like this:
// for the first object
obj[0]['fields']['id'] // or obj[0].fields.id
obj[0]['fields']['group_name'] // or obj[0].fields.group_name
// for the second object
obj[1]['fields']['id'] // or obj[1].fields.id
obj[1]['fields']['group_name'] // or obj[1].fields.group_name
// and so on...
In your case you can do this:
$.each(obj, function(index){ // for each object
$(groups).append('<option value=' + obj[index]['fields']['id'] + '>'+ obj[index]['fields']['group_name'] + '</option>');
});

Skip duplicate items while rendering page from json

I'm rendering page using ajax and json. Structure of my json is {"status":"ok","rewards":[{"id":201,"points":500},{"id":202,"points":500}]
How do i make ajax loading data only once one if 'points' duplicates in any of hashes?
E.g. i have json with few hashes in which 'points' have same value
Here is my code
$("#page").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/file.json",
dataType: "json",
error: function (data, tex
tStatus){
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var seen = {};
$.each(data.rewards, function(key, val){
lis += "<div class = 'reward-ui ui-block-" + String.fromCharCode(97 + key%3) + "'><a href ='#' class ='ui-link-inherit'>" + val.points + "</a></div>";
});
$(".ui-grid-b").html(lis);
});
//$('.even-odd').listview('refresh');
})
});
Add a local array which will store all the items used. Push into this array in $.each function and before doing lis += " " check if the value already exists in the temp array.
Other than that you could try server side sorting before retrieving data ... like suggested above.

How to pass cakephp formhelper input values to ajax via jquery?

I am still new to cakephp, and my attempt is to retrieve the FormHelper's value and pass it via $.ajax() call in jquery. However, by cakephp convention, the name of each field generated by FormHelper will be in the format of data[Model][field]. Now, I want to submit $_POST data in form of cakephp array format. However, I couldn't find a way to do so, because I couldn't find a way to turn name and value attribute into a passable array format.
My attempt was to turn everything into string and try to create a json array. However, I failed to do so, and this method doesn't seem convincing to me too.
function submitEdit(sendurl, formid){
var dataset = [];
$('form#'+ formid + ' > input,select').each(function(){
dataset.push($(this).attr('name') + ':' + $(this).val());
});
alert(dataset);
$.ajax({
type: 'POST',
data: '{' + dataset + ']',
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});
}
Therefore, how do I pass this as data[Model][field] array to the sendurl controller?
Something like
$.ajax({
type: 'POST',
data: {
Model: {
foo: $('#ModelFoo').val(),
bar: $('#ModelBar').val()
}
},
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});

How to access an object's contents in javascript?

When I do
$.each(result, function(i, n){
alert("key: " + i + ", Value: " + n );
});
then for each iteration I see
key: 276, Value: {"owners":["he"],"users":["he","m"],"end":"07/06-2011","groups":[],"type":"in"}
How do I access the values of owners, users, end, groups, and type for each iteration?
In Perl would I have done
foreach my $key (keys %result) {
print $result{$key}{owners};
print $result{$key}{users};
...
}
Update
I get result from JSON like so
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { "cwis" : id },
// ...
success: function(result){
if (result.error) {
alert('result.error: ' + result.error);
} else {
$.each(result, function(i, n){
alert( "key: " + i + ", Value: " + n );
});
}
}
});
Update 2
It seams that the problem is the server side is not sending prober JSON.
This is the server side script that generate the JSON string.
!/usr/bin/perl -T
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw(:standard);
use JSON;
use utf8;
use strict;
use warnings;
my $cgi = CGI->new;
$cgi->charset('UTF-8');
my $json_string = qq{{"error" : "The user do not have any activities."}};
my $json = JSON->new->allow_nonref;
$json = $json->utf8;
# #a and $act is now available
my $data;
foreach my $id (#a) {
$data->{$id} = $json->encode(\%{$act->{$id}});
}
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
document.write(result[key].owners);
document.write(result[key].users);
UPDATE:
Apparently my comment on the question was the answer:
I'm no CGI expert but it looks like
you are double encoding your data into
JSON. Once with
my $json = JSON->new->allow_nonref; $json = $json->utf8;
and then again with
$data->{$id} = $json->encode(\%{$act->{$id}}) .
in $.each callbacks, this points to the current element, so
$.each(result, function(i, n){
alert(this.users);
});
n.owners or n['owners']
n.users or n['users']
etc.
In a loop...
$.each(result, function(k,v) {
console.log("key: " + k + ", value: " + v );
$.each(v, function(k,v)) {
console.log("key: " + k + ", value: " + v );
});
});
you can access them like this:
n.owners
or
n['owners']
or you can use another cycle :
$.each(result, function(i, n){
if (typeof(n)=='object') {
$.each(n, function(k, v){
alert('n.'+k+' = ' + v);
});
}
});
edit:
jsFiddle Example
Example 2
edit2: to avoid getting undefined make a simple check whether the key i is equal to "Value", so it's value will be an object

Categories