How to get json data from url with Cordova? - javascript

I started to develop an app with Cordova for android and I'm now searching around google for a solution(Whitelist) to get the JSON data from the URL.But I cannot find a simple tutorial. Most of the tutorials I found are not so beginner friendly. I'm thinking about trying to get the JSON data with pure javascript, but I think it's not a good idea. Are there some simple tips or tutorial that can solve this problem? I love to hear from you!

Like this? Assuming that hello.php returns your JSON data.
$.ajax({
url: "yourwebsite.com/hello.php",
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getdata(arr);
},
error: function () {
validationMsg();
}
});
function _getdata(arr){
//your JSON resuls are now in arr. Do what you need with the array.
}

This example could be very helpful.
You should try ajax calls in order to fetch data from the server, jQuery makes it very easy. Here is the function used in the example that loads the data from the server :
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
I hope it help.

fetch('/echo/json', {
method: 'get'
}).then((JSONresponse) => {
// do whatever you want with your
// JSONresponse here
})

Related

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

Extract Feefo JSON array into Javascript, display as HTML list

I'm learning Javascript and JSON at the moment but really confused by it all.
I'm trying to extract data from a JSON array, I've got to this point
$(function(){
var $reviews = $('#reviews');
$.ajax({
type: 'GET',
url: "https://api.feefo.com/api/10/reviews/all?merchant_identifier=pub-insurance-4u-co-uk&fields=reviews.service.rating.rating,reviews.service.review,reviews.customer.display_name",
success: function(reviews) {
$.each(reviews, function(i, review) {
$reviews.append('<li>name: '+ review.display_name +', review: '+ review.review + ', rating: '+ review.rating + '</li>');
});
}
});
});
I can't seem to get much further at the moment. I've read about JSON.parse(), perhaps that is what I need. Any help / advice GREATLY appreciated thanks!
$(function(){
var $reviews = $('#reviews');
$.ajax({
type: 'GET',
url: "https://api.feefo.com/api/10/reviews/all?merchant_identifier=pub-insurance-4u-co-uk&fields=reviews.service.rating.rating,reviews.service.review,reviews.customer.display_name",
success: function(reviews) {
//console.log(reviews);
$.each(reviews.reviews, function(i, review) {
$reviews.append('<li>name: '+ review.customer.display_name +', review: '+ review.service.review + ', rating: '+ review.service.rating.rating + '</li>');
});
}
});
});
It is helpful to log the object and take a look at it in the console. Then you can see the structure and print what you like.
That's what I did :)
Here is a screenshot:
And here is the fiddle:
Fiddle

how to print or echo JSON.stringify data i php

i am trying to fetch google contact list using contact api. i got the result and its showing in chrome and firefox console. i want to print the data in php. on the same page
<script type="text/javascript">
function auth() {
var config = {
'client_id': 'xxxxxxxxxxxxxxxxxxxxx',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
//alert(JSON.stringify(data));
// display all your data in console
console.log(JSON.stringify(data));
}
});
}
</script>
i tried ajax but not worked. is there any best way to do it. JSON.stringify(data) is a array
You have nothing to do with PHP here. You are receiving a callback from $.ajax and the only way to show that data on ur page is to use JavaScript/jQuery.
See example below on how to parse $.ajax callback and .append() the data to some element on ur page:
<div id="contacts"></div>
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
$.each(data.feed.entry,function(){
$('#contacts').append('<div>Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t + '</div>');
console.log('Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t);
});
}
});
}
Note: if You need to parse ur data with PHP then You have to use curl.

Undefined is not a function (AJAX, PHP, jQuery)

I am very new to jQuery and AJAX so I apologise if I am being stupid.
I am receiving an error in my AJAX jQuery script.
I am retrieving data via AJAX get to display dynamically on my page.
The JSON file returns an array which must be iterated and displayed in a DIV for each item.
The JSON is:
[{"id":1,
"user_id":14,
"title":"The Title",
"thumbnail":"image.jpg",
"summary":"summary of post",
"content":"content info here",
"category":"Graphic Design",
"sub_category":"Adobe Photoshop",
"views":0,
"published":0,
"created_at":"2015-04-16 00:09:57",
"updated_at":"2015-04-16 00:09:57"}, {and so on...}]
The jQuery is:
function retrieveTutorials()
{
$.ajax({
type: "GET",
url: "/tutorials/retrieve",
dataType: "json",
success: function(data){
var tutorial = ('')
$.each(data, function(){
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
});
$("#generated-content").empty().append(tutorial);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
The error I am currently receiving is "Uncaught TypeError: undefined is not a function" which refers to the following section
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
Any ideas as to where I am going wrong?
I have used very similar code before which worked fine
try this
var tutorial = $('<div></div>');
You should select any DOM Element and assign it to tutorial variable, something like this:
var tutorial = $('someCSSselector');
There is an error because you are calling .append() on (''). .append() is a jQuery function, but ('') is an empty string, not a jQuery object.
You can do this:
var tutorial = $('<div>');
...
$("#generated-content").empty().append(tutorial.html());
You should define your div object first, and you can keep generatedbox class when defining it. Then, you can omit the div that you had in the appended content.
var tutorial = $('<div class="generatedbox">')
$.each(data, function(){
tutorial.append($('<img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p>'))
});

accessing variables outside ajax

I have the following code:
var src, flickrImages = [];
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
// undefined returned here for flickrImages
map.setZoom(13);
map.setCenter(new google.maps.LatLng(xmlLat,xmlLng));
infowindow.setContent('<strong>' + xmlTitle + '</strong><br>' + xmlExcerpt + '<br><br>' + flickrImages.join(''));
infowindow.open(map,this);
I am trying to access flickrImages variable outside the ajax so I am able to put it inside a infowindow for google maps. Unfortunately outside the ajax it returns undefined.
I tried moving the flickr things into the ajax but unfortunately it then loses some of the other information such as xmlTitle and xmlExcerpt.
Any help is much appreciated.
Thanks in advance,
Dave.
The reason why flickrImages is undefined where your comment is, is because the call to $.ajax is asynchronous, which means it does not block until your request completes.
That's why there is a success function that gets "called back" when the underlying HTTP request completes. So, you need to handle your flickrImages variable from your success function, or alternatively, from your success function, pass flickrImages to some other function which does your processing.
The ajax call is asynchronous, so it won't wait around for an answer - it will just go ahead and run the rest of the script. Passing async:false in the settings (see http://api.jquery.com/jQuery.ajax/) should solve your problem, though it will make it a lot slower as the script will have to wait for the ajax call to return.
It would be neater for the rest of the script to be called from the success callback as you tried to do - how is it that xmlTitle and xmlExcerpt are unavailable there?
Define a global variable outside of your ajax call and assign it a value
var myData
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
myData = data
myFunction()
}
});
As said by Karl Agius a "The ajax call is asynchronous". For this you just have to add
async: false,
to your ajax request. Here is you code looks after adding this:
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
async: false,
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
But its not a good practice to stop asynchronous in ajax call. But will work for you. Use Ajax callback on success instead (check here).
Here is another option. You create a function that return an ajax call like this.
function flickrImages (){
return $.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json"
});
}
Then on your code somewhere, you call this function an retrieve the success or in my case the .done() function like this
var result= flickrImages ();
flickrImages = [];
result.done(function(data){
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
});
console.log (flickrImages);

Categories