Alert does not display in JSON callback - javascript

I'm sure there is a simple explanation to this. I am having problems understanding why the following alert does not display in my javascript:
<script>
theURL = "gb.json?callback=?";
$.getJSON(theURL, null, function(data) {
alert('in json proc');
});
</script>
the file gb.json is in the same folder as the html containing the script. When I run it in Firebug it gets a return code of 200 OK and I see the contents of gb.json.
This must be something very simple that I'm missing. The alert should display, shouldn't it?

It seems your server is returning regular JSON, not JSONP. Just pass the URL directly, without the added callback query string:
$.getJSON('gb.json', function(data) {
alert('in json proc');
});

Related

How do I doa Jquery.get on a JS file without executing it?

So I'm trying to make an Ajax request to pull down a js file, just to check the version number recorded inside its comments. However, if I run a jQuery.get, and the file pulled down is a javascript it automatically executes it, when I DON'T want the JS to be executed, I just want to read it and look at parts of the text of the script. How do I alter this:
jQuery.get("somefile.js", function(data) { console.log("Do stuff here.") });
So that I can run that success handler WITHOUT first executing somefile.js?
Set the dataType argument to $.get() to "text" to tell jQuery that the data is a string and it should not guess the type.
$.get("file", function(data) { alert(data) }, "text");
See here: Jquery get javascript file without running

$('body').html() gave blank content from response data that come from $jQuery.post in Firefox

I got this javascript code in a JSP:
$('#myForm').submit(function(event) {
event.preventDefault();
var act = $('#myForm').attr('action') + '&act=' + $('#submitBtn').val();
var dataStr = $("#myForm").serialize();
$.post(act, dataStr, function(data, status) {
$('body').html(data);
});
return false;
});
The facts:
I'm using jquery v1.3.x (and I can't replace with newer version because of company policy).
The jsp is in a pop-up window.
There is a submit button with id=submitBtn
When the submit button is clicked, it will execute above code and send the data into struts action.
The action url:
someAction.do?someParam=blabla&someNo=213354345&mode=POP&act=Update Your Data
(note: I had replaced some sensitive data, but the argument pattern is same)
The problem is at this line:
$('body').html(data);
It produces Error: NS_ERROR_FAILURE: Failure in error console. I heard it's related with cross domain request, but my application is at localhost, how could it happened?
In IE 8, it successfully replaced the current page content with the data value (which is html string). But in firefox (v22), it gave blank page, I checked with right click -> View Source, it's really empty. Then I checked with firebug, the response data indeed contains the result html page string. If I debug with alert(data); before the $('body').html() call, it also show the html string.
So the $.post() function successfully returns the response data but it seems the $('body').html() function failed to render the data.
So what is actually happened? I'm really have no clue.
What is the solution for this?
UPDATE:
I checked the error console, I got this error after submitted the page:
Error: NS_ERROR_FAILURE: Failure
Source File: http://localhost:8080/myapp/script/jquery.js
Line: 19
UPDATE 2:
I debug the java code, I found out that the input html tag in the JSP that has indexed array name like this:
myItem[0].name
myItem[1].name
...
were not successfully submitted to the ActionForm class. I investigated the source of problem might come from a 3rd party javascript library.
try something like this
$.post(act, dataStr, function(data) {
document.body.innerHTML = data;
});

$.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()

How to get JQuery to accept a JSON reply?

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. :(

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