jQuery AJAX request failing in IE - json

The following AJAX call is failing in IE.
$.ajax({
url:"{{SITE_URL}}/content/twitter.json",
dataType:"json",
error:function(xhr, status, errorThrown) {
alert(errorThrown+'\n'+status+'\n'+xhr.statusText);
},
success:function(json) {
...Snip...
}
});
The error function returns
Undefined
parsererror
OK
No request is made to the server so I don't think its a problem with the JSON.
Fixed, See #1351389

Fixed, I changed the content-type from application/json; charset=utf8 to just plain application/json.
I hate IE :)
Also to avoid IE super-caching try this:
var d = new Date();
$.ajax({
url:"{{SITE_URL}}/content/twitter.json?_="+d.getTime(),
...Snip...
That way each request is a new url for IE to get :D

For the caching problem why don't you simple use the cache: false parameter?
$.ajax({
url: "yoururl",
cache: false,
....

is this a copy/paste? the one thing that gets me all the time is leaving the last ',' in an object constructor. that is, most browsers JS accept:
o = { a:1, b:2, c:3, };
but IE chokes on this because the comma after the last item. change it to:
o = { a:1, b:2, c:3 };
and it works.

In newer versions of internet explorer (IE7) it is necessary to write the next line before calling $.ajax, otherwise it would never call the function:
$.ajaxSetup({ cache: false }); //this line before $.ajax!!!
$.ajax({
//codes
//codes
//codes
});

IE caches AJAX requests really aggressively (more so than Firefox, anyway). You need to set the Cache-Control headers in the response appropriately if this is not right for your site.

One major problem with statically generated JSON and IE are the leading "commas", for examples this throws an error in IE:
{
"one":"hello",
"two":"hi",
}
Note the last comma.

What is the {{SITE_URL}} chunk giving is about. Try looking at the code in view source code of the browser. If the {{SITE _URL}} chunk has a trailing slash and that would make the request url:
http://modomain.com//content/twitter.json
Which could creep IE out?

IE: JSON not defined error resolved at
http://funkatron.com/site/comments/safely-parsing-json-in-javascript/
by using dataType: "json" and avoid parsing

Related

Edge animate: How to preload JSON information?

I get the JSON info to the EdgeAnimate Stage (creationComplete Action) by this code:
$.getJSON('myJsonLink', function(data) {
});
Problem: the composition get's the info, after the animation starts.
But the info needs to be loaded before animation.
it's very annoying problem for which I can't find the solution for days...
Can You help?
The getJSON fires an XMLHttpRequest in an asynchronous mode, which means a request is sent, then we move on to the next iteration in the flow.
You may need to make your request synchronous instead, but unfortunatelly, getJSON does not support synch mode as far as I know so you should use the low-level $.ajax() method with the async property set to false:
$.ajax({
dataType: "json",
url: "myJsonLink",
data: data,
async: false,
success: function () {}
});

jQuery and JSON vs IE - SCRIPT5007: Unable to get value of the property

I'm struggling to get this script working. It's basically a simple ajax call to retrieve data from a php which returns a JSON code.
function refreshWindows(){
if(AjaxPull && AjaxPull.readystate != 4){
AjaxPull.abort();
}
AjaxPull = $.ajax({
type: 'POST',
url: $path,
data: {
ajax: true,
mode: 'update',
to: Math.round(currentDate.getTime() / 1000),
from: Math.round(previousDate.getTime() / 1000)
},
dataType: "json",
success: function (data) {
alert(data); //that's for debug
$replies = data.Updates;
$.each($replies ,function(group,value) {
if (value!=''){
$("#group"+group+" .content").append(value);
$("#group"+group+" .content").stop().animate({ scrollTop: $("#group"+group+" .content")[0].scrollHeight }, 800);
if (!$("#group"+group+" .Window").is(':visible')) {
$("#group"+group+" .BottomBox").fadeTo('fast', 0.5).fadeTo('fast', 1.0);
}
}
});
previousDate = currentDate;
currentDate = new Date();
timeController.push( setTimeout(function(){refreshChatWindows();}, 500) );
}
});
}
The error I get in Internet Explorer is:
SCRIPT5007: Unable to get value of the property 'Updates': object is null or undefined
Everything works fine in Firefox and Google Chrome.
Initially my code was made using .get but someone suggested switching to the .ajax - well, it didn't help. I tried using .done(function(data){ but it didn't work either. I also tried sending all of the data in my URL opposite to the data property, it worked fine in FF, but IE still popped the same error. Finally I tried adding different headers to the PHP, like for example header('Content-Type: application/json'); but it didn't change anything. I run out of ideas / possible solutions I could fine on stackoverflow, so any help would be appreciated.
In IE I went to Developer Tools, network tab and tried to see if everything works - yes, the request is being sent correctly with all the data, and a response I receive is correct JSON, just as it is in Firefox:
{"Updates":{"1":"","2":"","3":"","5":"","6":"","7":"","8":""},"time":{"from":"1367489761","to":"1367489761"}}
which gets me really confused, cause I'd have thought that Undefined error might happen only because something is not being sent back in IE for whatever reason, but clearly: It's not the case. I get my JSON back. Only IE for some unknown reason still thinks that data is undefined.
Ok, I found a solution finally.
Basically:
Remove any headers sent by PHP script. Especially: Content-type headers. (luckily - seems like sessions still can be used)
Use }).done(function ( data ) { instead of success: function (data) {
and that's all. Suddenly it started to work. It's very weird. Seems like the shotgun tactic (randomly changing bits of code till it works) is actually a valid way of solving problems. hehehe
I have a similar json call that returns data that looks like this:
{"GetTombstoneDataRestResult":{"AlphaSort":"Arai Junichi","Classification":"A&D Design Object"...etc
In other words, a lot like your json data. To reference it in jQuery, I use the callback name.
$.ajax({
type: "GET",
dataType: "jsonp",
url: url,
success: function (result) {
$('#screenshot').append('<p><strong>Title: ' +
result.GetTombstoneDataRestResult.Title + '</strong><br />Year: ' +
result.GetTombstoneDataRestResult.Dated + '<br />Artist: ' +
result.GetTombstoneDataRestResult.DisplayName + '</p>');
}
});
Looks like you want to try this too:
var replies = data;
$.each(replies.Updates ,function(group,value) {
You have a character called ​ in your JSON.
See a description here:
What's HTML character code 8203?
It's right before your colon here "time"​:
Can you clean your output and validate the JSON and try again?

MVC 3 jQuery UI autocomplete not displaying the results

I have searched many times and find examples which match my code structure perfect. Yet I am not getting the results from my ajax to display on the input box.
I get results from the POST that have been evaulated with firebug and everything looks great.
Here is the javascript im using.
<script type="text/javascript" language="javascript">
$(function () {
$("input.FamousPerson-List").autocomplete({
source: function (request, response) {
$.ajax({
url: "/FamousPeople/FPPAutoComplete",
type: "POST",
dataType: "json",
data: {
searchText: request.term,
maxResults: 12
},
success: function (data) {
response($.map(data, function (item) {
return {
value: item.DisplayName
}
}))
}
});
}
});
});
Here is a link of the actual code I am using on the web.AutoCompleteTesting Type just about any letter in one of the boxes below to invoke it.
Thanks.
If you look closely at the request being sent up, you'll notice that a callback parameter is being added. Weird, right? Since you're doing a local AJAX post, not a cross-domain (JSONP) one.
I noticed that your project includes jQuery Validate. According to this answer to a question dealing with a similar problem (performing a JSONP request instead of a normal JSON request even though you asked for one), it's a known issue in jQuery validate.
Judging by the other answer, you can change your version of jQuery or perhaps use a patched version of jQuery validate (found here).

jQuery $.ajax() is firing the server request but never gets response on google chrome only

I tested this on firefox and ie and worked. But when testing on chrome, I see in the firebug console that the request never loads.
This is the test page: http://gotune.to/index2.php
And here is the function + $.ajax() request.
function getProgress(id) {
$.ajax({
type: 'POST',
cache: false,
url: "getprogress.php",
//Pass our upload identifier as a parameter.
data: {uid: id},
success: function (d) {
//Get the output as an integer.
var progress = parseInt(d, 10);
//If upload progress is not 100, change bar percentage and update again.
if (progress != '100') {
$('#ProgressBar').css('width', progress + '%');
//We aren't done, update again.
getProgress(id);
}
}
});
}
UPDATE
Tried with
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus+" - "+errorThrown);
}
But still not working.
After a web research for this issue if found this:
Turns out it's a bug, in any webkit
based browser all ajax is essentially
blocked until the file upload is
complete. to bypass this you have to
dynamically create an iframe and run
the ajax requests from within it.
So is a problem of the webkit browsers, thanks #ifaour for your time.
THE BUG REPORT CAN BE FOUND HERE: https://bugs.webkit.org/show_bug.cgi?id=23933

Using jQuery.getJSON in Chrome Extension

I need to do a cross-domain request in a chrome extension. I know I can it via message passing but I'd rather stick to just jQuery idioms (so my javascript can also work as a <script src="">).
I do the normal:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
but in the error console I see:
Uncaught ReferenceError: jsonp1271044791817 is not defined
Is jQuery not inserting the callback function correctly into the document? What can I do to make this work?
(If I paste the code into a chrome console, it works fine, but if I put it as the page.js in an extension is when the problem appears.)
Alas, none of these worked, so I ended up doing the communication via the background.html.
background.html
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script>
function onRequest(request, sender, callback) {
if (request.action == 'getJSON') {
$.getJSON(request.url, callback);
}
}
chrome.extension.onRequest.addListener(onRequest);
</script>
javascripts/page.js
chrome_getJSON = function(url, callback) {
console.log("sending RPC");
chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}
$(function(){
// use chrome_getJSON instead of $.getJSON
});
If you specify "api.flickr.com" in your manifest.json file you will not need to use the JSONP callback, script injection style of cross domain request.
For example:
"permissions": ["http://api.flickr.com"],
This should work beautifully in you code. I would remove the querystring parameter "&jsoncallback" as there is no JSONP work needed.
The reason why your current code is not working is your code is injecting into pages DOM, content scripts have access to the DOM but no access to javascript context, so there is no method to call on callback.
My impressions it that this fails because the jQuery callback function is being created within the 'isolated world' of the Chrome extension and is inaccessible when the response comes back:
http://code.google.com/chrome/extensions/content_scripts.html#execution-environment
I'm using Prototype and jQuery for various reasons, but my quick fix should be easy to parse:
// Add the callback function to the page
s = new Element('script').update("function boom(e){console.log(e);}");
$$('body')[0].insert(s);
// Tell jQuery which method to call in the response
function shrink_link(oldLink, callback){
jQuery.ajax({
type: "POST",
url: "http://api.awe.sm/url.json",
data: {
v: 3,
url: oldLink,
key: "5c8b1a212434c2153c2f2c2f2c765a36140add243bf6eae876345f8fd11045d9",
tool: "mKU7uN",
channel: "twitter"
},
dataType: "jsonp",
jsonpCallback: callback
});
}
// And make it so.
shrink_link('http://www.google.com', "boom");
Alternatively you can try using the extension XHR capability:
http://code.google.com/chrome/extensions/xhr.html
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
}
}
xhr.send();
The syntax is a little off. There's no need for the callback( bit. This works flawlessly. Tested in the javascript console of Chrome on this StackOverflow page (which includes jQuery):
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
As many of you will know, Google Chrome doesn't support any of the handy GM_ functions at the moment.
As such, it is impossible to do cross site AJAX requests due to various sandbox restrictions (even using great tools like James Padolsey's Cross Domain Request Script)
I needed a way for users to know when my Greasemonkey script had been updated in Chrome (since Chrome doesn't do that either...). I came up with a solution which is documented here (and in use in my Lighthouse++ script) and worth a read for those of you wanting to version check your scripts:
http://blog.bandit.co.nz/post/1048347342/version-check-chrome-greasemonkey-script