Display JSON response array in Phonegap - json

very quick question
i have webservice which returns JSON array
I want to display that JSON array in phonegap app
how can i do that
so far i was trying this
but its not working
$(document).ready(function () {
$.jsonp({
url: 'getevents.php',
callbackParameter: 'callback',
success: function (data, status) {
//$('#your-tweets').append('<li>The feed loads fine');
$.each(data, function (i, item) {
var tweet = item.title;
$('#your-tweets').append('<li>' + tweet);
});
},
error: function () {
$('#your-tweets').append('<li>There was an error loading the feed');
}
});
});
And here is my index.html file
<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/data.js"></script>
<title>Hello World</title>
</head>
<body>
<ul id="your-tweets"></ul>
</body>
But with this code i am getting error that $.jsonp is not a function
If there are some tutorials available online than do provide me the link as well
I have tried this function as well
But somehow i cannot figure out where to pass the return array from the webservice
function readJSONData() {
$.getJSON("getevents.php",function(data){
if(data) {
var json_data;
$('#read-data').hide();
$('.demo-table').show();
$.each(data, function(i,event){
json_data = '<tr>'+
'<td valign="top">'+
'<div class="feed_title">'+event.title+'</div>'+
'<div>'+event.description+'</div>'+
'</td>'+
'</tr>';
$(json_data).appendTo('#demo-table-content');
});
} else {
json_data += '<tr>'+
'<td valign="top">No Tutorials Found</td>'+
'</tr>';
$(json_data).appendTo('#demo-table-content');
}
});
}
I can see in the firebug that on ajax request it returns the event array but on the page i get undefined instead of the data
thank you and really appreciate it

Use this prototype. And not event is an array so you have to check element in array i.e. data.event[index]
also you don't have any parameter data.event.desc so referring to that element will result undefined.
<html>
<body>
Get JSON Data
<div id="showdata"></div>
</body>
</html>
$(document).ready(function(){
//attach a jQuery live event to the button
$('#getdata-button').live('click', function(){
$.getJSON('http://dev.app.horsebuzz.com/dbconnection/getevents.php', function(data) {
//alert(data); //uncomment this for debug
//alert (data.item1+" "+data.item2+" "+data.item3); //further debug
for(var i=0;i<data.event.length;i++){
$('#showdata').html("<p>item1="+data.event[i].title+" item2="+data.event[i].start_date+" item3="+data.event[i].location+"</p>");
}
});
});
});

Related

Display ajax in html page

I'm using flask as a backend, and one of my endpoints is objectList, which returns data in this format:
[{name1:value1, name2:value2}, {name1:value3, name2:value4}]
In order to display this data on my html page, I'm using the following code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
$("#div1").html(result);
};
});
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
This doesn't display any data. What am I doing wrong and how can I fix this?
Edit: just a clarification, I want the data to load when the page loads, not on a button or a click
After our discussion, I find this code works properly
You have to close the parenthesis in the function ajax, and allow the access-control in the server side with this line
header("Access-Control-Allow-Origin: *");
// or replace the star with the server where you have the html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
// to verifiy the result
console.log(result);
var htmlOutput = '';
// the iteration of your result because you have many entries
$.each(result, function(i, item) {
htmlOutput += ''+
'<ul>'+
'<li>name1: '+item['name1']+'</li>'+
'<li>name2: '+item['name2']+'</li>'+
'</ul>';
});
$("#div1").html(htmlOutput);
}, error: function(jqXHR, textStatus, error) {
// to verifiy either there is an error or not
console.error(textStatus);
}
});
});
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>

Sorting with isotope from external json rendered with handlebars

Can't seem to get Isotope sort to work :(
On the client side of a webpage I'm displaying data which comes from an external json with a template using handlebars.js.
I want the users to be able to sort, filter and search the data that is displayed. I've seen that with Isotope can this be achieve successfully. I did manage to get filtering to work.
However I'm stuck with sorting in targeting the class of the object with the getSortData option which value comes from the json.
Example of the JSON structure with the price:
Here is the code trying to sort by price, first my menu:
<ul id="sort">
<li>original order</li>
<li>number</li>
</ul>
Then my handlebars template, where I want to reach the p.class = number:
<div id="mcContainer"></div>
<script id="mcTemplate" type="text/x-handlebars-template">
{{#each this}} {{#annoncer}}
<article class="mc_item {{category}} {{year}}">
<a data-single href="{{id}}">
<h3>{{brand}} {{model}}</h3>
<img src={{images.0.small}} />
<h4 class="mc_aar">ÅR: {{year}}, {{km}} km</h4>
<p>{{category}}</p>
<p class="mc_pris number">{{price}},-</p>
<hr>
</a>
</article>
{{/annoncer}} {{/each}}
</script>
And my javascript file:
(function ($) {
"use strict";
// javascript code here. i.e.: $(document).ready( function(){} );
$(document).ready(function ($) {
var $container = $('#mcContainer');
$.ajax({
url: "http://diegovega.dk/kea/2semester/json-eks/json-eks.json",
method: "GET",
dataType: 'json',
success: function (response) {
var template = $('#mcTemplate').html();
var renderer = Handlebars.compile(template);
var result = response;
$('#mcContainer').html(renderer(result));
runIsotope();
}
});
function runIsotope() {
var $items = $('.mc_item');
$items.isotope({})
$items.isotope('reloadItems')
.isotope({
itemSelector: '.mc_item',
layoutMode: 'fitRows',
fitRows: {
gutter: 20
},
getSortData: {
number: '.number parseInt'
},
});
// Sort based on price
$('#sort').on('click', function () {
if ($(this).hasClass('checked')) {
$(this).removeClass('checked');
.isotope({
sortBy: 'original-order'
});
} else {
$('#sort').removeClass('checked');
var sortValue = $(this).attr('data-sort-value');
console.log($(this).attr('data-sort-value'));
.isotope({
sortBy: sortValue
});
$(this).addClass('checked');
}
});
} //RUN ISOTOPE
}); // END DOCUMENT READY
})(jQuery); // END use strict
Any help is greatly appreciated :)
Initialize Isotope on the container, not the items
Use data-sort attribute on the links click

Query CSV file with google visualization query

I am trying to query a csv file with google visualization query but every time I am getting 'Error in query: 404 file not found' error and am not able to resolve it.
any pointers / suggestions / thought would be highly appreciated.
Note - the csv file exists on my local server and if click on link http://localhost:35802/test.csv it downloaded the file for me
here is my code --
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
function initialize() {
//var opts = { sendMethod: 'auto' };
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('csv?url=http://localhost:35802/test.csv');
// Optional request to return only column C and the sum of column B, grouped by C members.
query.setQuery('select * ');
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response)
{
if (response.isError())
{
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
//alert(response);
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, { height: 400 });
}
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
here is my csv file content --
A,B,C
1,2,3
4,5,6
Thanks a lot #WhiteHat for the pointers.. finally I got it working...:)
the culprit was the google library that I was loading.
Initially I was loading --
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
which was not working for me...
I was able to run my code by changing this library to
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
for anyone who needs a working sample here it is --
please change the path to csv file
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
// var query = new google.visualization.Query('http://www.gstatic.com/external_hosted/gstatic/charts/static/data.csv',
// { csvColumns: ['string', 'number'], csvHasHeader: true });
var opt = { sendMethod: 'xhr' }; //{ csvColumns: ['string', 'number'], csvHasHeader: true, sendMethod: auto });
//var query = new google.visualization.Query('http://local:6572/data.csv', opt);
var query = new google.visualization.Query('http://localhost:6572/data.csv');
query.setQuery('select *');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' +
response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('csv'));
chart.draw(data, { legend: { position: 'none'} });
}
</script>
</head>
<body>
<div id="csv" style="width: 900px; height: 500px;"></div>
</body>
</html>

JavaScript runtime error: Unable to get property 'nodeType' of undefined or null reference

I tried running an application with knockoutjs script included with jquery and my own js file that has a ViewModel actual binding to the controls.
I am getting the exception every time i run the application.
Is this the issue in my system, or the Visual Studio? I even tried running the html file alone in the browser, i couldn't see any exceptions but it stopped me from performing all other functionalists that are expected to be done from knockoutjs.
Please help me in this regard
This is my full code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/knockout-2.2.0.js"></script>
<script type="text/javascript"> // Here's my data model
debugger;
function viewModel() {
this.day = ko.observable('24');
this.month = ko.observable('02');
this.year = ko.observable('2012');
this.fullDate = ko.computed(function () {
return this.day() + "/" + this.month() + "/" + this.year();
}, this);
};
ko.applyBindings(new viewModel());
</script>
</head>
<body>
<p>Day:
<input data-bind="value: day" /></p>
<p>Month:
<input data-bind="value: month" /></p>
<p>Year:
<input data-bind="value: year" /></p>
<p>The current date is <span data-bind="text: fullDate"></span></p>
</body>
</html>
You called applyBindings before browser rendered html. You have to move script tag to the bottom of the page or put your code to document ready handler:
<script type="text/javascript">
$(function(){
debugger;
function viewModel() {
this.day = ko.observable('24');
this.month = ko.observable('02');
this.year = ko.observable('2012');
this.fullDate = ko.computed(function () {
return this.day() + "/" + this.month() + "/" + this.year();
}, this);
};
ko.applyBindings(new viewModel());
});
</script>

view data and manipulate date from json using jquery or ajax

First of All i'm a beginner in jquery and ajax,
what i'm trying to do is view a sample from a whole json file in the link
http://soap.madarat.jo/Services/BusinessApplication1-DomainService1.svc/json/gettasks
and what is the possibility of editing the sample,
<!DOCTYPE HTML>
<html>
<head>
<title>json test</title>
<script src="js/json2.js" type="text/javascript"></script>
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script src="jtip.js" type="text/javascript"></script>
<script type="text/javascript">
function query() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://soap.madarat.jo/Services/BusinessApplication1- DomainService1.svc/json/gettasks", false);
xmlhttp.send();
var results = JSON.parse(xmlhttp.responseText);
var html = '<ol>';
alert(results.GetTasksResult);
if (results.GetTasksResult != null) {
var title;
alert(results);
for (var i = 0; i < results.GetTasksResult.RootResults.length; i++ ) {
entity = results.GetTasksResult.RootResults[i];
html += '<li>'+entity.DoctorID +' by <b>'+ entity.TaskNote +'</b></li> <br><br> ';
}
document.getElementById('results').innerHTML = html;
}
}
</script>
</head>
<body>
<button type="button" onclick="query()">jquery</button>
<div id="results" />
</body>
</html>
but nothing happens when i click the button,
why is this happening
thank you
You're not using your requester object correctly. All you did is issue a request but didn't wait for its reply. This code works asynchronously but you thought it's synchronous that's why you started processing data bfore you even got it.
Use jQuery to make an Ajax request
$.ajax({
type: "GET",
url: "http://soap.madarat.jo/Services/BusinessApplication1-DomainService1.svc/json/gettasks",
success: function(data, status, xhr){
data = data + "" == data ? $.parseJSON(data) : data;
var el = $("#results").append("<ol></ol>").children("ol").first();
if (data.GetTaskResult) {
$.each(data.GetTaskResult.RootResult, function() {
el.append("<li>" + this.DoctorID + " by <b>" + this.Tasknote + "</b></li>");
});
}
}
});
This may have bugs but it shoudl roughly do the same as your code.
Additionally, you son't need to add json2 library, and I don't know about your jtip.
Best tip I can give you
Try to first get acquainted with libraries you're using. In your case that would be jQuery. It makes it much simpler for you to write browser independent Ajax code. You haven't used even one bit of it even though it's there. Learn it, use it. It shouldn't take you a day to get through all its docs to see how to use it and why it's wise to do so.
jQuery documentation