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.
Related
I'm trying to take the result of my console log and put it in a div. The console log bit works, but not putting it in a div. According to the online tutorials it should be something like this:
<div id="number">Test</div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
var data;
$.ajax({
type: 'POST',
dataType: 'json',
url: 'report.php',
data: data,
success: function (data) {
console.log(data.report.data[0].breakdown[0].counts);
$('#number').innerHTML = data.report.data[0].breakdown[0].counts;
}
});
});
</script>
However I get no log errors, it just doesn't update the text.
use
$('#number').html(data.report.data[0].breakdown[0].counts)
instead of .innerHTML
Since you using jQuery Selector $, you need to use $('#number').html("text or something").
Or maybe you can do document.querySelectorAll("#number").innerHTML = "text or somthing" if you want to use Vanila Javascript.
$('#number') is a jquery object, .innerHTML works on a DOM object - they are not the same thing.
Either convert $('#number') to DOM, with:
$('#number')[0].innerHTML = data.report.data[0].breakdown[0].counts;
Or use jquery method:
$('#number').html(data.report.data[0].breakdown[0].counts);
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
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
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()
I'm getting an ajax output success data.
Where the data contains some html text and a script.
But the script is not executing, how can I execute the script.
Let's say Ajax response obj is
<div>something....</div><script>alert("test");</script>
the above code is my Ajax response.The div is getting rendered, but the alert is not working.
Assuming you are not using JSON or jQuery, or any other library, and your AJAX call returns some HTML and/or javascript which is being added to your existing document (eg. using innerHTML), any javascript returned using AJAX will not execute in the browser - except for events on elements in the HTML.
So if your AJAX call returns <input type="button" value="Click me" onclick="alert('hello');" />, the js alert will work ok, but if your AJAX call returns <script type="text/javascript">alert('hello');</script> it will not execute. In that case, you would have to parse the result to extract the javascript and execute it, using a function such as this:
function extract_and_execute_js(output_to_parse)
{
if(output_to_parse != '')
{
var script = "";
output_to_parse = output_to_parse.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){if (output_to_parse !== null) script += arguments[1] + '\n';return '';});
if(script)
{
if (window.execScript)
{
window.execScript(script);
}
else
{
window.setTimeout(script, 0);
}
}
}
}
If you are retrieving the JSON formatted result from AJAX call, you can just use eval to execute the javascript.
Assume, if the result json is formed like this
var res = '{"Data": "<something>",
"script": "alert(something)"}';
var out = eval("(" + res + ")");
var data = out.data;
eval(out.script);
Interestingly enough, I use jQuery and using the html() function was enough to get the JavaScript to execute. So more or less I had nothing special to do.
There is a simplified version:
var myform = $('form#form-id');
$.post(myform.attr('action'), myform.serialize(), function(response) {
$('#some-id').html(response.message);
}
In my case the code kicked in automatically so I did not need any other of the solutions proposed here.
Not sure if you are using a library, but with Prototype I had to set
evalScripts: true
before JavaScript would be eval-ed. See here for more info:
http://www.sergiopereira.com/articles/prototype.js.html#UsingAjaxRequest
Using jQuery here is a simple bit of code:
$.ajax({
type: "POST",
url: "getData.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result);
}
});
But, to actually use the results of the variable result I ended up using a javascript library, from http://www.json.org/js.html, I did:
success: function(result) {
var myData = JSON.parse(result.d);
There are probably better approaches, but this was simple, and worked for me, so I just use this. Later, when the project is in production I may go back and clean this up, but that is after I get everything working.