jQuery: Yahoo Autocomplete/Autosuggest - javascript

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.

Related

Getting json on cross domain with jsonp using jquery

I have a very simple $.ajax call that is suppose to get the json data from a given url. Currently the url does get called and the data does get returned, however the localHsonpCallback function doesn't seem to get fired.
Here is my code.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
}
function localJsonpCallback(json) {
console.log("Fired");
if (!json.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
So as mentioned above for some reason the localJsonpCallback doesn't seem to get fired at all.
Also I should mention that in my Chrome Dev tools the request link ends up looking like this for reason
http://localhost/api/users?callback=localJsonpCallback&_=1429708885454
Any help in this question would be greatly appreciated.
Thank you.
Try the callback method as an anonymous function directly inside the parameter list.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: function(data){
console.log("Fired");
if (!data.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
});
}
If youre not appending the callback onto the url you can set the jsonp oprion to false and then, as you are doing, set the callback in the options.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "localJsonpCallback"
});
}
Since javascript is sequential its also a good idea to define your functions before theyre called. ie - define your callback function before your ajax call.
http://api.jquery.com/jQuery.ajax/
jsonp
Type:
String Override the callback function name in a JSONP request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
Maybe this piece of code it will help solve your problem:
$.ajax({
type: 'GET',
url: 'http://localhost/api/users',
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
//your code here
};
This either a server side problem that the callback parameter is not used properly or the parameter name callback does not exist for the server side they are looking for something different.
You said the result is returning, what is the format? JSONP must return a script block not pure data so be sure the result is in below format.
{callbackFunctionName}({hugeDataFromServer});
Basically it is script that calls your function.
if it is not the server side that means it is more likely they are using a different name for callback parameter e.g. cb , _callback etc

Extract and read JSON Data from web API

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); }
});

How do i read simple json result with jquery and how to post new

I built a WCF service which produces JSON. I want to make an external website which uses this webservice. For now I am executing the WCF service over LAN by IIS, so I can connect to the service by going to http://myownaddress/blabla.svc/
I tried to learn some json and to get some results from my service.
For example if I want to use this method:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/{id}")]
string JSONData(string id);
I'll go to http://myownaddress/blabla.svc/json/123
And as result I get:
{"JSONDataResult":"You requested product 123"}
Now I have tried to receive this result with the JQuery statement getJSON. But I don't see any results.
My question is how can I get this simple data?
And secondly how can I post data(with javascript) back on to the wcf service is it also possible with json?
-edit-:
I have now updated my code and put this into my document ready function which is located between the <head> <script> .... on my page:
$.getJSON(
'http://myownaddress/blabla.svc',
function(data)
{
alert(data.JSONDataResult);
});
But this won't give the alert with the result. It doesn't even give an alert.. Besides that, in the function I need to give a parameter of id, so for example 123 (look in text above) don't I need to put that in the function also?
To get data use getJSON():
$.getJSON(
'http://myownaddress/blabla.svc/',
function(data) {
alert(data.JSONDataResult);
}
);
To post data you can use this:
$.post('http://myownaddress/postservice.svc', function(data) {
$('.result').html(data);
});
or this (if you need more control):
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You can also use the ajax for getting the data instead of the getJSON method .
UPDATE:
try using ajax method as it gives you more control:
$.ajax({
type: 'GET',
url: "http://myownaddress/blabla.svc/json/123",
success: function(data){alert(data)},
dataType: "json",
complete: function(data){alert(data)},
error: function(jqXHR, textStatus, errorThrown){alert(errorThrown)}
});
Also, if you use firefox, check out firebug extension, it will help you greatly.
If you use chrome then use chrome developer tools.
In order for your to get the json data from a WCF service that is outside your website using Jquery you need to use JSONP.
You can perform the call as shown below:
$.ajax({
url: "http://myownaddress/blabla.svc/",
dataType: "jsonp",
type: "GET",
timeout: 10000,
data: null,
jsonpCallback: "MyCallback",
success: function (data, textStatus, jqXHR) {
alert(action.toLowerCase());
},
error: function (jqXHR, textStatus, errorThrown) {alert('error is:' + errorThrown);
},
complete: function (jqXHR, textStatus) {alert('complete');
}
});
JSONP is used when you want to perform a cross domain calls using Javascript.
Also your WCF service should be compatible to handle JSONP calls by injecting the results to the response stream using the callBack method specified in the URL.
Do you have your code like this ?
$.getJSON(
'http://myownaddress/blabla.svc/',
function(result) {
alert(result.JSONDataResult);
}
);
Remember getJSON will not immediately return you the data, you have to make use of the result in a callback function.
Why did you change your url?
$.getJSON(
'h t t p://myownaddress/blabla.svc' ==> 'h t t p://myownaddress/blabla.svc/123',
function(data)
{
alert(data.JSONDataResult);
});

jQuery $.getJSON not working

I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});

Access json data from php

I have a problem accessing JSON data. I'm new to JSON and jquery so there is probably a easy solution to it and I would be glad to find out.
My jQuery:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
}
);
currentPage.php:
$returnArray['left'] = 'test_left';
$returnArray['right'] = 'test_right';
$returnArray['numLeft'][] = 1;
$returnArray['numRight'][] = 2;
$returnArray['numRight'][] = 3;
print json_encode($returnArray);
I tried to access the data like this:
data.left
data['left']
but it returns blank, how is the best way to access the data in the HTML-file?
I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
},
"json"
);
Provide the datatype you expect to get as parameter to the .post() method (in your case json):
$.post("currentPage.php",{'currentPage': 1},
function(data){
$("body").append(data);
},
'json' // <-- add the expected datatype
);
I think the default is to treat the result as HTML. Read the documentation.
jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.
dataType The type of data expected from the server.
In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:
"json": Evaluates the response as JSON
and returns a JavaScript object. In
jQuery 1.4 the JSON data is parsed in
a strict manner; any malformed JSON is
rejected and a parse error is thrown.
(See json.org for more information on
proper JSON formatting.)
You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.
$.ajax({
url: "currentPage.php",
data: {
'currentPage': 1
},
dataType: "json",
type: "post",
success: function(data) {
$("body").append(data);
}
});

Categories

Resources