How do i parse Google's suggestqueries JSON response? - javascript

Before the following URL gave a JSON output:
http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=Query
now it outputs the following:
window.google.ac.h(["Query",[["query",0],["query optimization",0],["query in access 2013",0],["query processing and optimization",0],["query optimization in dbms",0],["querying microsoft sql server 2012",0],["query in access 2010",0],["query letter",0],["querying microsoft sql server 2012 tutorial",0],["query access",0]],{"k":1,"q":"4-l7QUSZEiiQKaSq-yXfrtfHpd0"}])
Curious as to how i can parse this into JSON

That's JSONP.
If you were to call this using JSONP technique (adding <script> tag to your page with the src= attribute set to the URL) then you would need to declare the function window.google.ac.h before making the JSONP call to process the result.
If you were to call this using ajax or on the server then you have two options:
declare the funciton window.google.ac.h to process the result then eval the response. (Because, that's what adding a <script> tag does, it evals the javascript file in your page. So you're basically just emulating JSONP)
function window.google.ac.h (json) {
// process your response here
}
var s = document.createElement('script');
s.src = 'http://suggestqueries.google.com/complete/search?' +
'client=youtube&ds=yt&q=Query';
document.body.appendChild(s);
alternatively, if you receive the response via other means:
function window.google.ac.h (json) {
// process your response here
}
eval(response);
Remove the outer window.google.ac.h( .. and .. ) from the response then parse it as JSON.
var json = response.replace(/^.*?\(/,'').replace(/\)$/,'');

Related

How can I store js output in php?

I want to store my javascript output in PHP. I mean, my js code is:
function loadCurrentUser () {
var url = APIPATH + 'load_current_user.php' ;
var result = $.ajax({
type : "GET" ,
url : url,
async : false
}). responseText ;
var resultJSON = processJSONResult(result);
}
What I want is to store the output I received (in json format) to my variable $json (in php). How can I do that?
based on the comments above it cannot be done as you think. But if you insist on getting response date to a php variable you will have to make another ajax call as ajax call occur at client side and php runs in your server not on the browser #briosheje had explained it nicely. may be what you need is session variable ($_SESSION['index']) to store your response data

Cross domain jquery ajax (Jsonp): Uncaught SyntaxError: Unexpected token : (colon)

I've been trying to pull data from the steam api, and have had no luck because I always get the above error. Here is the code I am using:
var steamurl = "https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?key=[keyomitted]&account_id=38440257&Matches_Requested=10";
function populate_api(){
var json;
$.ajax({
'url': steamurl,
'dataType': "jsonp",
'success': function (data) {
alert('success');
json = data;
}
});
}
I omitted my API key.
I have looked at many other posts, and cannot figure out where the problem is. I have tried using Jsonp, regular json, I have also tried using "&callback=?" after steamurl, but to no avail.
The solution for this is to add a local proxy that your jQuery code will call. Your proxy will be server side code (PHP, Python, Ruby, etc) that forwards the query on to Valve and then returns it to your jQuery call. You will, however, have to use one of their supported formats (of which JSONP is not one).
A high level view of what you'll be doing:
Create PHP file that accepts the parameters jQuery will be passing. In this case, it looks like account ID and matches you want to receive. Do not pass the API key, this should be stored in the PHP file
In PHP, build your steamurl using the stored API key, and the two passed values
Issue a call to the Valve servers using this steamurl and retrieve the results.
Return this response to your ajax call
Your PHP will look something like this (and should include more error checking since I am just taking the $_GET values as gospel:
$matches = $_GET['matches'];
$acct = $_GET['accountid'];
$APIKEY = <YOURKEYHERE>;
$steamurl = "https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?key=$APIKEY&account_id=$acct&Matches_Requested=$matches&format=json";
$json_object= file_get_contents($steamurl);
header('Content-Type: application/json');
echo $json_object;
Now you can use jQuery to parse this JSON response.

Can someone explain me how to do a JSONP call like I'm five? [duplicate]

This question already has answers here:
What are the differences between JSON and JSONP?
(8 answers)
Closed 9 years ago.
I already have a .json object in a server. It is correct and has no syntax errors (valid json). I want to call this object through JSONP because it resides in a server different from my app's.
I think I understand how to achieve it client-wise, but I have no idea what to do in relation to the server part. I am having errors all the time when following the info already on the web. Any help?
JSONP is basically a "hack" to allow sites to load data and ignore the same-origin policy. It works by appending a <script> tag to your page.
The de facto way is to send a callback in your request. The server would then take that name and generate a JS file that calls that function with the data.
Using jQuery, you can make a JSONP call by simply appending ?callback=? to your URL when doing $.getJSON.
Example:
$.getJSON('http://YourSite.com/path/to/json.php?callback=?', function(data){
console.log(data); // this will be parsed for you
});
Or, you can use the full $.ajax method:
$.ajax({
url: 'http://YourSite.com/path/to/json.php',
dataType: 'jsonp', // this tells jQuery to add "callback=?" for you
success: function(data){
console.log(data); // this will be parsed for you
}
});
Instead of makning an AJAX call, jQuery will actually append:
<script src="http://YourSite.com/path/to/json.php?callback=jQuery12345"></script>
to your page (note: jQuery12345 will be randomly generated).
Then on your server, you need to respond with a valid JavaScript file. It should contain a call to the callback function passed in the query string. Something like this:
jQuery12345({your: ['json', 'data']});
An example in PHP (adapt to whatever server-side language you use) could be:
$array = ['a' => 1, 'b' => 2,'c' => 3];
$callback = $_GET['callback'];
header('Content-type: text/javascript');
echo "{$callback}(".json_encode($array).");";
That's all there is to it. See the Wikipedia page on JSONP for more info: http://en.wikipedia.org/wiki/JSONP
JSONP has nothing to do with JSON. Here's a simple (but useless) example:
The client makes a script element: <script src="http://example.com/foo.js>. This causes the browser to fetch foo.js from example.com.
The server hears the request for foo.js. The server serves the contents of foo.js to the client (suppose it's just alert(1)).
The client gets the contents of foo.js and runs those contents as a script. (So, the client does alert(1).)
How is this useful? Well, you can pass arguments with your request to foo.js:
The client does <script src="http://example.com/foo.js?arg=123>
The server hears a request for foo.js?arg=123. The server does something with that arg value -- let's suppose it multiplies it by 2 (but it could do something useful, like look up the username for the user with uid 123). The server then sends back the script content alert(246).
**The client runs the script from the server and alerts 246.
Okay, this is great if I want the client to alert stuff, but how can I do something useful? There's just one last leap we have to make: provide the name of a client function as an argument:
The client defines a function myFunc as: function myFunc(a) { alert(a) }
The client does <script src="http://example.com/foo.js?callback=myFunc&arg=123>
The server hears the request for foo.js?callback=myFunc&arg=123, and its server-side scripting knows it should use the callback argument as the name of the function called in foo.js. The server sends back the script content myFunc(246).
The client runs myFunc(246). Here, we've specified myFunc to just alert its argument, but you could have it do anything you like.
That's how JSONP works. The client provides arguments to the server in a script URL, including the name of a client-side function, and the server sends back a script (not JSON!) for the client to run. Of course, the resulting script can contain JSON in it, like myFunc({ 'foo' : 5 }), but ultimately, that JSON is just part of the script content.

I dont get any data from the getJSON function

I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}
A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.
The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).
Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.

jQuery: using $.getJSON to get localization from aprs.fi

I want to use JSON to get localization coordinates from http://aprs.fi/page/api. I found example at http://api.jquery.com/jQuery.getJSON :
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "cat",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
</script>
When $.getJSON succed, it runs function(data), it puts 4 images on website. I paste this code in my html file and it works, so I changed it to get JSON data from aprs.fi:
<script>
$.getJSON("http://api.aprs.fi/api/get?name=OH7RDA&what=loc&apikey=_key_&format=json",
function(data)
{
alert("Anything");
});
};
</script>
Maybe my query is wrong, but even "Anything" doesn't print on my screen. I have no idea how to change it to make it works.
Just because a service can return JSON-formatted results does not mean that you can access it via JSONP. The site has to explicitly recognize such a request so that the response works as a JSONP response. (That is, the response must take the form of a function call, with the JSON return data passed as the argument to the function.)
The XHRs that getJSON is using are subject to same-origin-policy in web browsers; you can point XHR only to from only the exactly same server, port, protocol combination as the web page they are used in. If your web page runs on http://example.org:5625 it can only point XHR requests to http://example.org:5625/some-path-here.
The workaround is called JSONP where the resource is loaded as a tag. However, the service in question needs to be aware of it. You can tell if it is because after appending the callback parameter it should show something like
callbackname({"the": "respose", "goes": "here"});
that is, a function call to the named callback. However, if I understood correctly, the service you are using does not support JSONP. Then your only option is to make a serverside script that works as a proxy.

Categories