How to get JQuery to accept a JSON reply? - javascript

Here's some simple Javascript:
(function($){
var ajax_callback = function(data) { window.location.hash = data.h1; };
$('.clickable').live('click', function() {
$.post('server.fcgi', {}, ajax_callback, 'json');
}
);
})(jQuery);
The server is a c++ binary (yes, i know) that spits out (through fast_cgi) the string:
{"h1":"newhash"}.
The expected behavior is that the URL should change.
Instead, nothing happens and Firebug complains that 'data' is "null"!.
Any help would be greatly appreciated!
Will.
When the following code enters "ajax_callback", it says that "data" is "null"!.
But the server is a c++ binary that is confirmed to return the JSON string {"h1":"newhash"}.
Anyone have an idea why JQuery seems unable to accept the JSON data when calling the ajax_callback?

I did have similar problem as you have mentioned when using $.POST().
There are two things if you are using jquery $.post method. You need to add an extra bracket before defined data type ("JSON") as shown below. I don't know why but it works, it will return data.
$.post('server.fcgi', {}, ajax_callback,{}, 'json');
The second thing is that you will need to parse JSON data using $.parseJSON(data) in side the callback function.
One more thing to make sure that the url to fetch JSON, the page document type should be defined as JSON in the header.
I have given an example below.
$.post("url/path/here/to/json", {}, function(data){
if(data){ // just in case the called program had a problem
var obj = $.parseJSON(data);
.... do everything else using the Obj->
}
},{},"json");
This will work.
However I recommend to you to use another Jquery function specially implemented for JSON, that is called
$.getJSON();
Here is the url for more information
And I am suggesting you to use the following method instead of the one described by you.
$(document).ready(function(){
$('.clickable').live('click', function() {
$.getJSON('server.fcgi', function(data){
window.location.hash = data.h1;
});
}
);
});

Make sure the server also returns the correct HTTP headers before the payload. E.g.:
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: ...
...
{"h1":"bla"}
From your description, I could not quite make out if all it did was printf("{\"h1\":\"bla\"}"); or not.
To check the actual result, use a command line tool like HEAD, GET, wget, curl, or even nc. If you are not able to use one of those, you might get some clues from the Net panel in Firebug and the like.

Probably not the answer you want to hear, but I assume you're using jQuery 1.4.2? I noticed that this does work as expected in 1.3.2 so you might want to consider using that instead. :(

Related

Unable to load JSON (Javascript)

I'm trying to load a JSON file by link and then align data (like title, date etc) to variables so I can use them. Right now, I don't care about variables. I just want to alert() them but something seems like I'm doing it wrong, alert returns nothing!
I use JSfidle to run the code. The code is this:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json') ;
var JSON = JSON.parse(JSON_unparsed) ;
alert(JSON.feed.entry[0].title.$t) ;
The URL I want to parse is: http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json
and here you can see the JSON how is structured if that can help you:
You can use JSONP for this:
Update, for better understanding how to work with returned JSON.
var id, title;
$.ajax({
url: 'http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json',
jsonp: "callback",
dataType: "jsonp"
}).done(function(r){
// r is returned JSON
for(var i in r)
// for ex ID is this
id = r[i].id.$t;
// and title
title = r[i].title.$t;
// and so on, check the json, I mean check the browser console by hitting F12, below code will print the whole JSON
console.log(r[i]);
});
Codepen link: http://codepen.io/m-dehghani/pen/grXrrp?editors=0010
In addition to adeneo's reply, in your code, JSON_unparsed variable is holding something called (differed or promise object), this object might be holding the data inside it,but you are using the wrong way to pull it out. in order for you to get it out, you need to call (.done()) function, see the below:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json').done(function(json){
console.log(json);
console.log(json.feed.entry[0].title.$t);
});
aside from that, if you got an error with something like this:
XMLHttpRequest cannot load http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json&_=1459788714707. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.
it means that you are not allowed to call this API/URL from your current domain.
One more thing, if you are using getJSON method, there is no need to parse the returned data, jquery will parse it for you

$.getJSON - unable to catch response when using parameters in url

I have been struggling since yesterday with the following piece of code.
function findLocation(){
alert(1);
$.getJSON( "http://www.omc4web.com/geoip/geoip.php",
{ip: "127.0.0.1",
callingurl: "www.thissite.com" },
function( result ){
alert(2);
$.each(result, function(i, field)
{
alert(i);
if(i=="country")
{
country_code = field;
}
});
})
}
It does not seem to want to get beyond the calling of the php script. The returned data is {"country":"US","store":"US"} but the function does not seem to want to process it and I never get to alert(2). I have placed monitors in the php script and I can see that it does indeed get called with the correct parameters and it does return the data expected.
if you call http://www.omc4web.com/geoip/geoip.php?ip=127.0.0.1&callingurl=www.thissite.com from your browser you will see that data is returned.
The same piece of code calling a URL with no parameters behaves correctly, but not with the above setup.
My few remaining hairs would appreciate some help on this.
additional info:
header('Content-type: application/json'); set on php script
tried it on chrome and firefox
no errors show up on firebug just a blank response screen
running script from localhost, but if its a cross domain issue, why am I able to make a similar call (without params) to amazon? $.getJSON("http://freegeoip.net/json/",function(result){ works fine as does the popular flickr example.
I am using <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Thanks in advance
Ossi
I think it's a cross domain issue. I guess you're able to use freegeoip.net because you're using JSONP. Try looking at the jQuery documentation to learn how to use JSONP: jQuery.getJSON()

Incorrect JSON data format

I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.

How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});

jsonp request not working in firefox

I am trying a straightforward remote json call with jquery. I am trying to use the reddit api. http://api.reddit.com. This returns a valid json object.
If I call a local file (which is what is returned from the website saved to my local disk) things work fine.
$(document).ready(function() {
$.getJSON("js/reddit.json", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
If I then try to convert it to a remote call:
$(document).ready(function() {
$.getJSON("http://api.reddit.com", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
it will work fine in Safari, but not Firefox. This is expect as Firefox doesnt do remote calls due to security or something. Fine.
In the jquery docs they say to do it like this (jsonp):
$(document).ready(function() {
$.getJSON("http://api.reddit.com?jsoncallback=?", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
however it now stops working on both safari and firefox. The request is made but what is return from the server appears to be ignored.
Is this a problem with the code I am writing or with something the server is returning? How can I diagnose this problem?
EDIT Changed the address to the real one.
JSONP is something that needs to be supported on the server. I can't find the documentation, but it appears that, if Reddit supports JSONP, it's not with the jsoncallback query variable.
What JSONP does, is wrap the JSON text with a JavaScript Function call, this allows the JSON text to be processed by any function you've already defined in your code. This function does need to be available from the Global scope, however. It appears that the JQuery getJSON method generates a function name for you, and assigns it to the jsoncallback query string variable.
The URL you are pointing to (www.redit.com...) is not returning JSON! Not sure where the JSON syndication from reddit comes but you might want to start with the example from the docs:
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function (data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#redditbox");
if ( i == 4 ) return false;
});
});
});
(apologies for formatting)
EDIT Now I re read your post, I see you intended to go to api.reddit.com unfortunately you haven't got the right parameter name for the json callback parameter. You might need to further consult the reddit documentation to see if they support JSONP and what the name of the callback param should be.
I'm not sure about reddit.com, but for sites that don't support the JSONP idiom you can still create a proxy technique (on the backend) that would return the reddit JSON, and then you would just make an ajax request to that that.
So if you called http://mydomain.com/proxy.php?url=http://api.reddit.com:
<?php
$url = $_GET["url"];
print_r(file_get_contents($url));
?>
http://api.reddit.com/ returns JSON, but doesn't appear to be JSONP-friendly. You can verify this, if you have GET, via
% GET http://api.reddit.com/?callback=foo
which dumps a stream of JSON without the JSONP wrapper.
http://code.reddit.com/browser/r2/r2/controllers/api.py (line 84) shows the code looking for 'callback' (not 'jsoncallback'). That may be a good starting point for digging through Reddit's code to see what the trick is.

Categories