need direction regarding jquery and json - javascript

I have this url which is JSON webservice
http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2
I need to write a jquery function to access the JSON object from the above url.
I am not sure how to proceed with this task. Could someone help me out with starting out the jquery code?
Thanks
Inorder that the HTML appear I removed the "<" for each tag.
What I tried doing below is iterate over the items returned via the JSON object. However, I don't seem to get any result. Could some one point out my error in this regard.
body>
div id="para">
/div>
script>
$.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2',function(data) {
$.each(data.weatherObservations, function(i,item){
$("<p/>").attr("src", item.temperature).appendTo("#para");
if ( i == 3 ) return false;
});
});
/script>
/body>
Thank you.
Hi,
I now need to access another web service. I typed out the code on the exact same lines as above but I don't get any output. Could some one help in pointing my mistake?
jQuery(document).ready(function() {
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=75080&format=json&num_of_days=5&key=ac9c073a8e025308101307';
jQuery.getJSON(url, function(data) {
$.each(data.data.weather, function(i, item){
$("body").append("<p>"+item.date+"</p>");
if ( i == 3 ) return false;
});
});
});
Thanks!

It should be as easy as this:
<script type="text/javascript">
jQuery.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2', function(data) {
// The JSON object is now in the data variable --
// process it here; for example:
alert(data.weatherObservations[0].clouds);
});
</script>
Keep in mind, however, that your AJAX call must come from the same domain (ws.geonames.org), since most modern browsers do not allow cross-domain requests. The workaround is to use the JSON-P format instead of pure JSON.
... In response to rookie's edits to his original question, here is a more complete solution:
<html><head></head><body>
<div id="para"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
jQuery.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2', function(data) {
jQuery.each(data.weatherObservations, function(i,item){
jQuery("<p/>").html(item.temperature).appendTo("#para");
});
});
</script>
</body></html>

To help you read the content that's comes back, put it into http://jsbeautifier.org/ and it will format it so it is readable.
In addition to Mark's answer, you should verify the textStatus
http://jsfiddle.net/VC5c2/
var url = "http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2";
​jQuery.getJSON(url,function(data, textStatus) {
if (textStatus == "success") {
for (idx in data.weatherObservations) {
var wo = data.weatherObservations[idx];
console.log("Temperature at " + wo.stationName + ": " + wo.temperature);
}
}
});​

Searching for jquery json turned up this page first, which seems to be exactly what you need: jQuery.getJSON()

Related

How to display a json data from a existing url using ajax call

I Am new in working with json and jquery. I am trying to study the basics of json and jquery by working on some example. So I use existing json data in http://api.androidhive.info/contacts for my example. I want to display this data in my HTML page. My code is:
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked.");
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php
type: "GET",
dataType: 'json', // Choosing a JSON datatype
success: function (msg) {
alert("ajax worked.");
JsonpCallback(msg);
},
})
function JsonpCallback(json)
{
for (var i in json.contacts) {
$('#wines').append('contacts: ' + json.contacts[i] + '<br/>');
}
}
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get!</button>
</form>
<div id="wines">
<!-- Javascript will print data in here when we have finished the page -->
</div>
</body>
</html>
can any one please give me some brief introduction to JSON and how it's working ?
Thanks in advance.
You are iterating the JSON wrong, in your case since you are using jQuery (as mentioned) you can use the $.each(json, callback); helper fron jQuery, you can see the documentation here Jquery $.each documentation
For an example implementation I've created this JSFIDDLE LINK
for you. Have a great day ahead. Don't forget that JSON means
Javascript Object Notation
It's an object.
$.each(jsonData.contacts, function(k, v)
{
console.log(v.name);
$('#name').append('<li>'+v.name+'</li>');
});
jQuery
Am try to study the basics of json and jquery
Is a Javascript library with lots of very usefull methods. If you want to create a dynamic website it is very recommended to look into jQuery. There are many site with great explanation on what jQuery can do. As far as your example is concerned: There is an issue when passing variables/data from one framework to another or even when simply storing data. Here comes JSON.
JSON
Or JavaScript Object Notation (JSON) is used to solve exactly that problem. What is basically does is take all the desired data (array, variable, object, string etc.) and writes it in a human readable and for other frameworks readable fashion. I use JSON to store data in files when no database is available or when passing data from one framework to another (like JS <-> PHP).
Your example code
What happens here:
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked."); // not yet
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php --> this I don't know
type: "GET", // communication type
dataType: 'json', // Choosing a JSON datatype
success: function (msg) { // here, the whole content of the url is read, idealy it is in JSON format ofc
alert("ajax worked."); // hoorray
JsonpCallback(msg);
},
})
There is the serverside.php file that receives a GET command and returns HTML. All the HTML content is in JSON type (so no <stuff>, i.e. no actual HTML) and your success function returns that content in the msg variable. Typically you use something like
var obj = JSON.parse(text);
to convert the JSON data to Javascript variables. Read this here JSON in Javascript
JSONP
Now what if you want to do some domain crossing (as you suggested), then I strongly recommend to read this here What is JSONP all about? . It explains what JSONP is all about

AJAX call not working in WP based site

This is my first time calling AJAX from within jQuery so please bear with me here. I have a JSON file where I have formatted all of my data, and would like to simply call the JSON file and append some of the data to my HTML.
I should let everybody know that I am using Wordpress as a backbone for the site, though the PHP-based framework is not being utilized at all to my knowledge in this call, I did try and write out my URL to make sense within the jQuery. All of the id's in the slugArray array exist within my HTML.
OK! So:
JSON file can be seen here: http://bmgz.rtcgraphics.com/wp-content/themes/bmgz/data/whatwedo.json
jQuery:
var slugArray = [
'#project-management',
'#economic-incentives',
'#site-selection',
'#stakeholder-engagement-and-events',
'#lobbying-and-advocacy',
'#public-policy-and-issues-management',
'#digital-communications',
'#event-and-trade-show-materials',
'#presentation-and-print-design'
]
function getWWD(){
for (i=0; i<=slugArray.length; i++) {
var selection = slugArray[i];
$(selection).click(function(){
$.getJSON('wp-content/themes/bmgz/data/whatwedo.json', function(result){
alert("It works!");
var entry=result.whatwedo[0].id;
console.log(entry);
});
});
}
};
getWWD();
When I run this, I don't get anything, not even my alert. I was getting a 404 error when I typed in the URL wrong for the $.getJSON request, so I know the computer is reading it at least partly. Thanks guys! I appreciate any input!
Try with:
var slugArray = [
'#project-management',
'#economic-incentives',
'#site-selection',
'#stakeholder-engagement-and-events',
'#lobbying-and-advocacy',
'#public-policy-and-issues-management',
'#digital-communications',
'#event-and-trade-show-materials',
'#presentation-and-print-design'
]
function getWWD(){
for (i=0; i<=slugArray.length; i++) {
var selection = slugArray[i];
$(selection).click(function(){
$.getJSON('http://bmgz.rtcgraphics.com/wp-content/themes/bmgz/data/whatwedo.json', function(result){
alert("It works!");
var entry=result.whatwedo[0].id;
console.log(entry);
});
});
}
};
getWWD();

jQuery - $.post doesn't post to php

I am trying to use jQuery to post a variable to the same page using the following code
file.js
$('#sidebar-nav').on('click', 'li', function() {
var theID = $(this).attr('id');
$.post(location.href, {theID: theID});
});
file.php
<?php
if (isset($_POST['theID'])) {
// do something
}
?>
<html>
<!-- the rest of the page -->
</html>
UPDATED
But theID is not posted to the php file for some reason. My code inside the if statement won't execute. In addition, I used this exactly same method for other removeID in the same js and same php files, it's working well for removeID, but not theID.
And to clarify what location.href is in this situation; it is file.php.
Anyone can help me on this?
You have a syntax error on this line:
var theID = $(this).attr('id'));
// -----------------^
You need to remove the extra closing ). Or even better don't call two functions when the property can be accessed directly:
var theID = this.id;
Or better still, since theID is used in only one place get rid of that variable altogether:
$.post(location.href, {theID: this.id});
To send ajax request to the same page you can keep url parameter empty/removed
TRY
<script type="text/javascript">
$.post({
theID: theID,
success: function (data) {
alert("Data Loaded:");
}
});
</script>

How do I get JSON and push it into HTML with jQuery?

I have HTML pages and I have decided to populate them using JSON generated from an API (api.example.com).
The thing is that I have never used jQuery. What are the basics to pull the information using jQuery and then to fill the HTML with that JSON data, like name, surname, messages?
Should I put the JavaScript codes athe end of the HTML pages (right before )?
Or, is there easy way?
Really depends on what the json looks likes comming back.
First Get your data using ajax.
var incomingData; //Incoming Data Variable
$.ajax("http://yourURL.goes.here", {
type: "GET",
dataType: "json",
success: function(data) {
incomingData = data;
},
error: function(req, status, err) {
//console.error("Something went wrong! Status: %s (%s)", status, err);
}
});
Now you will have your data in the incomingData variable.
I'd console.log the data, so you can view it, but accessing the parts would be done through DOT notation:
incomingData.name;
incomingData.phone;
Usually you'll get an array of objects when you return JSON, so you may need to loop through.
for(var i = 0; i < incomingData.length; i++) {
console.log(incomingData[i]);
$('.yourClass').append(incomingData[i].name + '<br />');
}
The above will take the value of the 'name' property and append it to your <div class="yourclass"></div> in your html. It will also console log that object your iterating through in the console so you should be able to see all of its properties. Confusing at first, but a necessary JS skill. :)
As far as where to put it your code, best practices is before the closing body tag. Make sure your code is running after jquery has been loaded. Make a main.js file and include it right before your body closing tag:
<body>
...
All of your HTML
...
<script src="jquery.js"></script>
<script src="yourfile.js"></script>
</body>

Retrieving data using JSON-P

I am a newbie to javascript. I am experimenting with the below code for retrieving cross site data.
How can I do this code work, e.g. I want each family member is alerted to the screen.
Thank you for your help.
The code is amended like this and the alert says [object Object], do you know what this means??:
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// LOOP THROUGH EACH FAMILY MEMBER AND DO STUFF!
alert(mValue)
});
}
});
</script>
</head>
<body>
</body>
</html>
you don't want to wrap the oData with jQuery in your $.each
so, instead of
$.each($(oData['ops:patent-family']['ops:family-member']),
you want:
$.each(oData['ops:patent-family']['ops:family-member'],
Also - you have to go down a level with the returned json (there is a first 'ops:world-patent-data' level), which will look something more like:
if(oData['ops:world-patent-data'] &&
oData['ops:world-patent-data']['ops:patent-family'] &&
oData['ops:world-patent-data']['ops:patent-family']['ops:family-member']){
$.each(oData['ops:world-patent-data']['ops:patent-family']['ops:family-member'],
function(iIndex, mValue) {
// LOOP THROUGH EACH FAMILY MEMBER AND DO STUFF!
console.log(iIndex, mValue)
});
}
Another completely different way to do this is by using jquery deferreds syntax and using .pipe to transform the data - might be a bit cleaner than the if
var sUrl = "http://ops.epo.org/2.6.2/rest-services/family/publication/docdb/EP.1000000.A1/.js?callback=?";
$.getJSON(sUrl)
.pipe(function(data){
try{
return data['ops:world-patent-data']['ops:patent-family']['ops:family-member'];
} catch(e){
return [];
}
})
.then(function(members){
$.each(members, function(iIndex, mValue){
console.log(iIndex, mValue)
})
})
You'll need to do inline script creation:
function myCallback(response) {
// Your stuff goes here.
}
var script = document.createElement("script");
script.src = "http://ops.epo.org/2.6.2/rest-services/family/publication/docdb/EP.1000000.A1/.js?callback=myCallback";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
jQuery's $.ajax method allows you to specify a dataType for the request. If you specify JSONP, it will create the callback for you so you don't have to worry about that.
It goes like this:
$.ajax(url, {
dataType: 'jsonp',
success: function(data) {
// do stuff with data here
}
});​
Here's a JSFiddle demonstrating that with the data you needed:
http://jsfiddle.net/PPVX3/
Right now it's logging the data to the console, if you're using Chrome or Firefox you can use the developer tools to see the console log.

Categories

Resources