Extract and read JSON Data from web API - javascript

What I'm working on is providing 1 line instant definitions of terms and perhaps one line answers to few logical questions. Suppose a user inputs "JavaScript" and JavaScript visits the url https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1, gets the item "Definition" (Look at the API link to understand, Definition is in the first line itself) and displays its value of Definition and alert the user with the required data.
Anyways my code currently is:
<html>
<head>
<title>Hi</title></head>
<body>
<input id="ddgAPI"><button>Search</button>
<div id="output"></div>
</body>
</html>
Please note that I've not put in the required JavaScript/jQuery code as I'm confused with this. Thank you :)

Because this is a cross-domain request you can only do this with a proxy or with JSONP. Fortunately DuckDuckGo supports JSONP, so you just need to ensure that you add a callback parameter to the URL request like:
https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1&callback=jsonp
... or use the appropriate jsonp parameter with jQuery's ajax method, something like:
$('#ddgAPI').on('keyup', function(e) {
if (e.which === '13') {
$.ajax({
type: 'GET',
url: 'https://api.duckduckgo.com/',
data: { q: $(this).val(), format: 'json', pretty: 1 },
jsonpCallback: 'jsonp',
dataType: 'jsonp'
}).then(function (data) {
console.log(data);
});
}
});

Use jQuery.ajax() to talk to the remote service. url should be https://api.duckduckgo.com. type should be GET. data should be:
var data = { q:'JavaScript', format:'json', pretty:1 };
jQuery will then compile everything into an AJAX request, send it to the server. Pass a function as success so you can do something with the result:
$.ajax({
url: "https://api.duckduckgo.com",
type: "GET",
data: { q:'JavaScript', format:'json', pretty:1 },
success: function(data) { $('#output').html(data); }
});

Related

Jquery: Probably a syntax Issue in ajax() method - Value not getting sent

I'm able to dump value of the variable message in console .
But im not able to send it off in POST Request.
AJAX call:
chat.throwmsg = function(message) {
if ($.trim(message).length != 0) {
console.log(message);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'throw', message: message} ,
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
}
}
This maybe due to wrong syntax, but I've tried both single and double quotes, and combination as well .
With a wild assumption, you are not having any error messages in developer console and chat.php has a post handler forthese parameters
Since your data is JSON, please change the code as this way and have a try..
var temp={ method: 'throw', message: message};
var param=JSON.stringify(temp);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: param ,
dataType: "json",
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
after reviewing the code I could not find any issues that restrict the data to be sent along with ajax request,if you are having any syntax errors you should have been warned prior the request initialization, however I recommend you to check the request header in the network tab of browser console and see your sending data along with the request if it's there you probably need to check the code of getting the post data in your server-side implementations

JQuery Ajax petition is modifiying given URL

I want to consume a API Rest aplication using JQuery Ajax. this is the code that I have:
var res=$('#myForm').attr('action');
console.log(res);
$.ajax({
url: res,
success: function (data) {
alert('success!!');
},
dataType: 'html'
});
The console.log sentence is printing the url correctly, I just copied and pasted it into the browser and its correct, it's something like this:
http://localhost/myproject/public/2
But then, the request gives a 404 error, and the URL that is requesting is this one:
http://localhost/localhost/myproject/public/2
So, why it's attaching another localhost line to the url? I just don't understand!
All you need is to get the part after localhost. For this, please use split method.
var res=$('#myForm').attr('action');
console.log(res);
$.ajax({
url: res.split('localhost')[1],
success: function (data) {
alert('success!!');
},
dataType: 'html'
});

jquery ajax : what is the actual request sent?

What is the actual url sent to the server when I use the jquery ajax? And how do I access that value? For example, consider the following code:
<script>
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: {name:'Smith',age:10},
success: function(data) {
...
}
beforeSend: function(){
console.log(url);
// what do I put here to see what is being sent
// I am expecting to see "response.php?name=Smith&age=10"
}
...
So essentially what variable holds "response.php?name=Smith&age=10".
Thanks.
No variable holds
response.php?name=Smith&age=10
because you aren't sending the data as a query string. This would happen if you issued a GET request, but doesn't with a POST request.
You're sending the data in the request body of an HTTP post. The data is the data that you assigned to the data parameter. You don't need to round-trip it through jQuery's ajax methods. You've got it already. It's:
{name:'Smith',age:10}
does jQuery's interpretation of your data really matter?
The settings object is fully populated when beforeSend is called:
beforeSend: function(jqXHR, settings) {
console.log(settings.url);
console.log(settings.data);
}
$.ajax({ type: "POST", ... }) will log
response.php
name=Smith&age=10
and type: "GET"
response.php?name=Smith&age=10
undefined

Using JSONP with flaskr and javascript

I'm using Flaskr to generate data via a RESTful API. My call looks like:
http get localhost:5000/v1.0/dataset dataset_id==f7e7510b3c1c4337be339446ca000d22
and returns something like:
{"sites": "a"}
Now I'm tring to fetch this data with my web app. I first ran into a cross-domain error, but after some reading, found out that I could by-pass that error by using jsonp. Basically copying a piece of code I found here, I put this together (I'm new to JavaScript):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
(function($) {
var url = 'http://localhost:5000/v1.0/dataset?dataset_id=f7e7510b3c1c4337be339446ca000d22&callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
$('#data').html('the error was thrown');
}
});
})(jQuery);
</script>
</head>
<body>
<div id = 'data'></div>
<p> place holder </p>
</body>
and accordingly changed my python response to look like:
"jsonCallback({\"sites\":\"a\"});"
If this helps, my flaskr return line is the following:
return callback_function + '({"sites":"a"});'
I'm fairly confident my python side of the problem is good, but I'm not well versed enough in JS to determine where the error is coming from. My goal is to simply display my data on the page.
I'm not sure what's not working with your code. Because you haven't written any error message or what happens when your code runs.
Any way the following script does a JSONP request to http://jsonplaceholder.typicode.com/users/1/todos service and returns one todo item. I have used this only to have a service that returns some data.
If you are going to the developer console in your browser to network and click on the request to the rest service you'll see under response that jQuery is adding a callback to the JSON so you don't need to add it in your URL.
See the following screenshot. (The screenshot is from Firefox.)
I have added a working ajax example below. If you prefer jsFiddle, you'll find the same example here.
(function ($) {
//var url = 'http://localhost:5000/v1.0/dataset?dataset_id=f7e7510b3c1c4337be339446ca000d22';
var url = 'http://jsonplaceholder.typicode.com/todos/1'; // dummy url
var jsonCallback = function (data) {
console.log(data);
$('#data').html(JSON.stringify(data, null, 2));
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>

jQuery: Yahoo Autocomplete/Autosuggest

I'm trying to retrieve yahoo autocomplete.
Yahoo's JSON url is this: http://ff.search.yahoo.com/gossip?output=fxjson&command=query
So I have:
$("selector").autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ff.search.yahoo.com/gossip",
dataType: "jsonp",
data: {
"output" : "fxjson",
"command" : request.term
},
success: function( data ) {
response(data[1])
}
})
}
});
And here is an example: http://jsfiddle.net/yQbdb/
Can someone spot a mistake or what I'm I doing wrong? It should work.
Thanks
Setting output to jsonp works for me.
See example query for the structure of the output.
The explanation is below.
Code is HERE.
$("#wd6450").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ff.search.yahoo.com/gossip",
dataType: "jsonp",
data: {
"output": "jsonp",
"command": request.term
},
success: function(data) {
var suggestions = [];
// for each element in the data.gossip.results array ...
$.each(data.gossip.results, function(i, val) {
// .. push the value of the key inside our array
suggestions.push(val.key);
});
// call response with our collected values
response(suggestions);
}
});
}
});
Explanation:
By using dataType: "jsonp" jQuery expects the output format to be in JSONP. When you make a call from your code using output: "fxjson" the URL looks like this but as you can see the output is not a valid JSONP, because the callback was not called.
On the other hand when you specify output: "jsonp" the query looks like this and as you can see the output is a valid JSONP - the callback was called.
You linked a Amazon example in the comments. $.ajax() call there will try to URL like this. Output from Amazon's webservice is valid JSONP, because callback is called with all the data.
So the result is: Yahoo webservices will return format in JSONP if you provide ?output=jsonp parameter in the URL by configuring $.ajax() with output: "jsonp". Amazon's webservice returns this format by default without any extra parameters. This is webservice specific configuration and must be consulted with its documentation or other related resourcers.
Information about JSONP available HERE.

Categories

Resources