Read json in JQuery - javascript

I have this file json where I have, for each event (when), some reaction (do):
{"title":"Building blocks",
"date":"'1452786221'",
"scenes":[
[{
"when":{"event":"init"},
"goto":""
},
{
"when":{"event":"e_dTou","position":"up"},
"do":[
{"action":"a_dME","position":"open"},
{"action":"a_dME","position":"close"}
],
"goto":""
}
]
]}
I read this json from the file manifest.json with an ajax call so the data returned is text already parsed.
url = "json/manifest.json";
$.ajax({
type: "POST",
url: url,
success: function(data) {
console.log(data.scenes.when);
},
error: function() {
alert("Call" + url + " failed...");
}
});
With my code on console I have undefined . I want to read every data of this json in JQuery and write it on console. How can I do it? Thank you in advance.

You can use $.getJSON
Example:
$.getJSON( "url/to/file.json", function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( key + ': ' + val );
});
console.log( 'items: ', items );
});

try like that:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

I will give you some hint as my json is
{
$id: "1",
UserId: 1089,
Name: "abc",
Email: "xyz#web.com",
Password: "&*&*",
Phone: "9000000000",
Gender: "M",
AvatarName: "Jellyfish.jpg",
AvatarPath: "c:/folder",
CreatedAt: "2015-12-09T13:19:57.68",
ModifiedAt: "2016-01-11T15:16:25.297",
DOB: "05/06/1993"
}
and i fetched like that,
$(document).ready(function() {
$("#btn").on("click", function(a) {
var e = $("input#Email").val();
$.getJSON("http://192.168.0.1:24402/api/user/showbyemail?Email=" + e, function(a) {
$("input#Email").val(""), $("img#a").hide();
var e = a.AvatarPath;
$("#stage").html('<img id="a" src="'+ e + '" height="200" width="400">'),
$("img#a").hide(),
$("img#a").show(1e3),
$("#stage").append("<p> Name: " + a.Name + "</p>"),
$("#stage").append("<p>Phone : " + a.Phone + "</p>"),
$("#stage").append("<p> Gender: " + a.Gender + "</p>"),
$("#stage").append("<p> Email: " + a.Email + "</p>"),
$("#stage").append("<p> Password: " + a.Password + "</p>")
})
}), $(document).keypress(function(a) {
13 == a.which && $("#btn").click()
})
});
it may help you buddy

Ok, I have solved the problem. First I iterate three time the json and I put its content into trigger_json array.
$.each( data, function( key, val ) {
json.push(val);
});
$.each( json[2], function( key, val ) {
scenes.push(val);
});
$.each( scenes[0], function( key, val ) {
trigger_json.push(val);
});
Next to use the content of the array (when, do, goto, e..) I iterate trigger_json in this way:
for(i=0; i<trigger_json.length; i++)
{
// Use for example trigger_json[i].when.event
for(j=0; j<trigger_json[i].do.length; j++)
{
// Use for example trigger_json[i].do[j].action
}
}

Related

How to remove the text "undefined" that is appearing in the autocomplete search field?

I have a autocomplete search. If there are no results that corresponds to the search it appears the message "No results.".
And its working the message "No results" if the user introduce 3 letters that don't correspond to any result.
However it appears "undefiend" above the message "No results". Do you know how to remove that "undefiend" text?
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
$("#search").catcomplete({
source: "{{ URL::to('autocomplete-search') }}",
minLength: 3,
response: function(event, ui){
if (!ui.content.length) {
var noResult = { value:"", label:"No results." };
ui.content.push(noResult);
}
},
select: function(event, ui) {
if(ui.item.category=="Conferences"){
window.location.href = ui.item.url;
}
else{
$.get(ui.item.url, function(result) {
var newConferences = '';
var placeholder = "{{route('conferences.show', ['id' => '1', 'slug' => 'demo-slug'])}}";
$.each(result, function(index, conference) {
var url = placeholder.replace(1, conference.id).replace('demo-slug', conference.slug);
newConferences += '<div>\n' +
' <div class="card box-shaddow">\n' +
' <div class="card-body">\n' +
' <h5>'+conference.name+'</h5>\n' +
' </div>\n' +
' </div></div>';
});
$('#conferences').html(newConferences);
}, 'json');
}
}
});
You may replace the condition if ( item.category != currentCategory ) with the condition if ( item.category && item.category != currentCategory )
So that when the item doesn't have any category (which is your case : 'undefined') it doesn't append a useless line to your html.

Retrieve data from 3rd party website by ajax in laravel

I have ajax in my cart page where i get destination info of the user and return shipping options to them in order to calculate their shipping cost.
So far everything works except I'm not sure how to loop returned data from my 3rd party website.
Here is what I need:
I need Loop trough this data and get marked information in drop-down.
Red: as my option group.
Orange - Green - Purple: as my option. LIKE:
OKE - 48.000 - 5-7 Days
network result
console result
Codes
This is my ajax code for that:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
// $('#des').empty();
// $('#des').append(
// '<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
// );
$.each(data.data, function(key, value) {
console.log(value);
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
Thanks.
SOLVED
I retrieved my data with code below:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<optgroup label="' + value['code'] + '" /><option id="postchoose" class="form-control" value="'+ value['code'] +'">'+ value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option></optgroup>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
there is only 1 issue i'm facing I would like to be done and that's grouping results with <optgroup> as you see in my screenshot below my <optgroup> in looping for each one of my options.
How can I fix this?

How to replace appendto to something else to update the data

I am listing AJAX data in cards using the below code. It works well, but if I run it with setinterval with other function with some condition, if that becomes true it calls the below function to update the listed data.
It append all the new data to the existing listing data and duplicates it. I know this is because I am using the appendTo function, I tried to replace it with HTML but that did not work, it didn't list the data at all.
I want to update the data when this function is called again, rather than appending data. What should I use for this? Thanks.
function orderlist() {
return $.getJSON( "/restaurant/order/list/100/1",
function( orderdata )
{
var items = [];
$.each( orderdata, function( key, val ) {
var $o_on = val.ordernumber;
var $o_odate = val.bizorderdate;
var $o_userid = val.userid;
var $o_tnumber = val.tablenumber;
var $o_a = "<div class='card' id="+$o_on+">"
+ "<div class='title'>"
+ "Order No." + $o_on + "</div>"
+ "Date & Time: " + $o_odate + " </br>"
+ "User: " + $o_userid + " </br>"
+ "Table No: " + $o_tnumber + " </br>"
+ "</div>";
items.push($o_a);
})
$( "<div/>",
{
"class": "row",
html: items.join( "" )
}).appendTo( "#list_of_orders" );
});
}
Use empty() to clear out the list and then append your new stuff.
$('#list_of_orders').empty().append($( "<div/>",
{
"class": "row",
"html": items.join( "" )
}

loop a recieved json string to get values by jquery

I'm trying to parse data returned from $.post().
[{"id":"1","text":"USD"},
{"id":"2","text":"CNY"},
{"id":"3","text":"PHP"},
{"id":"4","text":"AUD"},
{"id":"5","text":"SGD"},
{"id":"6","text":"JPY"}]
using this approach Jquery, looping over a json array
I did something like this:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$.each(data,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it gives me the error:
Uncaught TypeError: Cannot use 'in' operator to search for '120' in [{"id":"2","text":"CNY"},{"id":"3","text":"PHP"},{"id":"4","text":"AUD"},{"id":"5","text":"SGD"},{"id":"6","text":"JPY"}]
I also tried:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$(data).each(function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it also gives me the error:
Uncaught Error: Syntax error, unrecognized expression: [{"id":"1","text":"USD"},{"id":"6","text":"JPY"}]
How should I be doing this?
Your data comes in the form of array so you need to loop through each index and then fetch the values. So you can replace this :-
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
with :-
$.each( obj, function( key) {
console.log( obj[key].id + ':' + obj[key].text);
});
or you can do this :-
$.each( obj, function( key, value ) {
console.log( value.id + ':' + value.text);
});
key is the index of array. It will return 0,1,2..
I think the argument passed to your success callback function is of type string. Change it to:
function(data) {
var parsedData = JSON.parse(data);
$(this).html();
$.each(parsedData ,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
function(data) {
var value = JSON.parse(data);
$.each(value ,function(idx, obj) {
console.log("id : "+obj.id+" "+text:"+obj.text);
});
}
try this
$.post(base_url+'cgame/currency',{ gameID: gameID },
function(data) {
$(this).html(); //<-- becareful $(this) might not be the element you think it is
$.each(data,function(idx, obj) {
console.log( "id : " + obj.id);
console.log( "text: " + obj.text);
});
},'JSON');

How to list values in Jquery

I have a JSON data which is sent to getJSON method. JSON data is
[{"Name":"P1","Description":"D1","Attribute":"E,S","Value":"EV,SV"}]
and getJSON method
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});
I would like to get the alert as
E : EV
S : SV
The code here is assuming you have the pair in order. The idea is split the attribute and value, then select the value with same index to alert.
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
var attrs = v.Attribute.split(",");
var values = v.Value.split(",");
for(var i = 0; i < attrs.length ; i++)
{
alert(attrs[i] + " : " + values[i]);
}
});
});
});
try this
$.getJSON(url, { Name: 'P1' }, function (data) {
var aSplit=data[0].Attribute.split(',');
var vSplit=data[0].Value.split(',');
alert(aSplit[0] + ' : ' + vSplit[0]);
alert(aSplit[1] + ' : ' + vSplit[1]);
});
If data is coming as string, then you need to eval(data) to get a javascript object.
Try :
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
data = eval('('+data+')');
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});

Categories