strange behaviour with json object coming from ajax call in safari/webkit - javascript

I'm using jquery to make an AJAX POST call to a web service, and getting a JSON object back, which gives me back some html code that i want to append to a div, it works fine in firefox but the problem is that safari doesn't do the appending, here is the example:
$.ajax({
type: "POST",
url: "ConnMgr.asmx/Request",
data: JSON.stringify(objectToSend),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
$('#myDiv').empty();
$("#myDiv").append(response.d.htmlSnippet); //this doesn't work on safari but it does on FF
//$("#myDiv").append("<img src=\"image.png"/>")//this works in all browsers
//alert(response.d);//this works in all browsers
}
});
It seems that in safari, jquery doesn't like the idea of using a json object as an argument for append()
I've tried creating a copy of the variable before, inserting a delay, converting the variable to string before passing it, but the results are the same.
Many thanks

did you try response.d.htmlSnippet.ToString()

You mean something like this http://jsbin.com/elapa/ doesn't work for you in safari?

yes i did try using response.d.htmlSnippet.ToString() and it didn't help
finally i did a workaround by composing the htmlsnippet and then taking only one number from the coming JSON object, and this way it worked
safari debugging console didn't report any error

Not to be nitpicky, but isn't this block the same as
success: function(response) {
$('#myDiv').empty();
//this doesn't work on safari but it does on FF
//$("#myDiv").append("<img src=\"image.png"/>")//this works in all browsers
//alert(response.d);//this works in all browsers
$("#myDiv").append(response.d.htmlSnippet);
}
as this block because you can chain method calls in jQuery?
success: function(response) {
$('#myDiv').html(response.d.htmlSnippet);
}
Can you try doing something like this?
$('#myDiv').html( '' + response.d.htmlSnippet );
I don't know if it will work or not...but it's worth a try.
I think your code response.d.htmlSnippet.ToString() might not work.
It should be a lowercase "toString()".

There is a difference in JSON implementation between FF and others that I spotted once - others don't allow weird charactersto be passed. You would have to use entities.
Try seeing for sure what comes back - drop the whole response object to a firebug-alike console and see the content. alerting it might not be enough.

Related

IE8 jquery json response triggers download

I want IE8 to work with the following piece of jquery that returns ajax request as json:
$.ajax({
url: formAction,
type: 'post',
dataType: 'json',
data: form,
success: function(data) {
closeBlocker();
if (data.count != 0) {
$('#divid').toggle('slow');
} else {
$("#anotherdiv").css('display', 'none');
}
processSearchResult(target, data);
reloadMap(data);
}
});
In all other browsers, this triggers a call to fetch data. In IE8, however, this results in a dialog box popping up that asks users if they want to download a file. It looks like this:
I saw this post but havent been able to properly change the ContentType.
How can I do the same thing in IE8 without affecting other browsers? Thanks for your ideas!
I guess it's related to MIME type.
You have to tell browser to treat it as text/html. Then it will not try to download it, and will display it as text instead.
For this you can send Content-type = "text/html" in header.
Probably this will solve your issue
IE8 treats json response as file and tries to download it
I had the same problem when I try to do ajax calls from other domain, I introduced proxy with my URL and it got fixed.
Hope it helps.

How to get Twitter search results in Javascript

I would like to grab a list of the recent appearances of a hashtag, but this seems to be impossible to do in Javascript at the moment. I have seen a lot of code snippets around that read like:
function searchTwitter(query) {
$.ajax({
url: 'http://search.twitter.com/search.json?' + searchTerm,
dataType: 'jsonp',
success: function (data) {
//some code
}
});
}
However, this does not seem to work anymore. If I try to use it, I get an error in the console like so:
XMLHttpRequest cannot load http://search.twitter.com/search.json?q=%23twitter. Origin http://myserver.com is not allowed by Access-Control-Allow-Origin.
The same thing happens if I use $.getJson(). Is there a solution for this? A workaround? It seems as though they changed something and then suddenly no one's client-side code works anymore. I really would like to be able to grab the data using Ajax so I can update my page without having to reload the whole thing.
If I am missing something obvious, please let me know.
You can solve this by configurin apache to
Access-Control-Allow-Origin *
Or for some reasons which i do not understand it worked using jQuery.getJSON();
function searchTwitter(query) {
$.getJSON({
url: 'http://search.twitter.com/search.json?' + searchTerm,
success: function (data) {
//some code
}
});
}
http://api.jquery.com/jQuery.getJSON/

Javascript setInterval not working in IE7 and IE8

I am using the Javascript setInterval to keep polling the server for any updates and refresh the screen with the response from the server. I need to support >IE7, and other major browsers.
The setInterval function is getting fired in all the browsers except IE7 and IE8.
According to the suggestions I saw in other posts I have tried setting cache:false on the ajax requests as well as wrapping the setInterval call in an anonymous function. But none of the suggestions seem to work.
Following is the code I am using:
$(document).ready(function () {
setInterval(pollForServerUpdates, 30000);
});
function pollForServerUpdates() {
$.ajax({ url: $.url("Home/GetUpdates"),
type: "POST",
cache: false,
success: function (result) {
updateTabelWithCurrentStatus(result);
},
dataType: "json"
});
}
I am not sure if I am missing anything here. Any help is very much appreciated.
Thanks!
I am putting my comments above as the answer to this question. The issue was happening because "class" seems to be a reserved keyword in IE and causing an error. When creating the element, I wrapped the class keyword in quotes and all is well. Thanks Pointy for asking me to look at the console. #Spudley, thanks for the tip, I will be refactoring my code with your suggestion.

IE8 XHTML returned in jQuery ajax call issue

I'm having an issue I cannot resolve through trying lots of different methods!!
Works in Chrome, FF, IE9 but not IE8 or IE7
Overview
I have a page, that Ajax's in the whole HTML from a local .aspx of which reads a photobucket XML feed puts into an HTML list and returns.
http://custommodsuk.com/Gallery.aspx
I've done it this way so the page ranking isn't penilised by Google speed rankings, as the server would be going off and making the call.
The code
$.ajax({
type: "GET",
url: ajaxURL,
dataType:'html',
success: function (feedHTML) {
var galleryList = $(feedHTML).find('#galleryList').find('.listItem');
var noItems = galleryList.length;
console.log(feedHTML.type);
galleryList.each(function (index) {
...
});
}
});
What I've tried
As you can see the console.log(),
the type is undefined, the feedHTML.length shows no. of characters. And from what I gather is generally treated as a string.
It is the JQuery not being able to turn the response into a jQuery object, and I can't traverse it. Therefore the each won't cycle.
I've seen lots of people with the same/similar issue on SO, but no answers, partly due to crap code examples.
Photobuckets RSS feed is malformed.
<p>CustomModsUK posted a photo</a></p>
This tripped up IE8. If you ever have problems like this in the future, check the validity of the HTML!!!

jQuery ajax method with dataType 'json' incorrectly parsing json data

I'm having some inexplicable behaviour using jQuery 1.4.2, and I'm beginning to think that it might be a safari problem, not a jQuery one. Let me explain.
I began simply enough by using .getJSON like this:
$.getJSON("/challenge/results", form_data, function(data){
//I know console.log is bad news, just a simplification.
console.log('data', data);
}
And the log gave me something along the lines of
>locations: Array (1)
While I was expecting an array of size 2. So I had a look at the json in the response:
{"locations":
[{"customer_id":2,"editable":true,"id":971,"latitude":43.659208,"longitude":-79.407501,"max_zoom":25,"min_zoom":9,"name":"test"},
{"customer_id":3,"editable":true,"id":974,"latitude":36.746944,"longitude":-107.970899,"max_zoom":25,"min_zoom":9,"name":"test2"}]}
I've simplified this considerably for the sake of clarity, but as far as I can tell, the json received is perfectly valid (generated programmatically through rails). [Update: JSONLint confirms this hypothesis.]
I was surprised by this, so I converted my request to a $.ajax request to see if there was some subtle difference between them (since then, looking in the source of jQuery I see that $.getJSON simply calls $.ajax).
$.ajax({
url:"/challenge/results",
dataType: 'json',
data: form_data,
cache:false,
success: function(data, textStatus){
console.log("data!", data, textStatus);
});
But alas! The same response:
locations: Array (1) success
At this point, I must admit - I was getting a bit silly, so I thought I would try something completely bound to fail:
$.ajax({
url:"/challenge/results",
dataType: 'text',
data: form_data,
cache:false,
success: function(data, textStatus){
console.log("Parsed:!", $.parseJSON(data), textStatus);
});
Much to my surprise my console read:
locations: Array (2) success
I was stumped. At this point I dug in my heels and took a long hard look at the jQuery source (1.4.2). I suppose unsurprisingly, the ajax function seems not to handle the json parsing itself (although, I must admit, I can't be sure).
I'm totally at a loss for why this could be happening - any help is appreciated.
Perhaps I missed something, but I notice that your JSON is an object that has a single property ("locations") with an array as it's value. Have you tried:
$.getJSON("/challenge/results", form_data, function(data){
//I know console.log is bad news, just a simplification.
console.log('data', data.locations);
}
try this:
// Enables for all serialization
jQuery.ajaxSettings.traditional = true;
// Enables for a single serialization
jQuery.param( stuff, true );
// Enables for a single Ajax requeset
$.ajax({ data: stuff, traditional: true });
hey,your problem seems like to be have something to do with the nested param serialization.just as what the jQuery 1.4 release note say:
Query 1.4 adds support for nested param serialization in jQuery.param, using the approach popularized by PHP, and supported by Ruby on Rails. For instance, {foo: ["bar", "baz"]} will be serialized as “foo[]=bar&foo[]=baz”.
In jQuery 1.3, {foo: ["bar", "baz"]} was serialized as “foo=bar&foo=baz”. However, there was no way to encode a single-element Array using this approach. If you need the old behavior, you can turn it back on by setting the traditional Ajax setting (globally via jQuery.ajaxSettings.traditional or on a case-by-case basis via the traditional flag).
The Webkit inspector's debugger should be used instead of console logging, which can show the object in a future state. This was the cause of this problem as the list was being trimmed in code after the console.log line, which resulted in the unexpected behaviour.

Categories

Resources