I have the following HTML and subsequent jQuery which appends the related HTML elements after the JSON request has been retrieved.
This implementation works in Google Chrome + Android browser + Safari, but is not populating the data in Firefox or Internet Explorer 9.
** Works in Chrome, Android browser, Firefox 4 ... does not work in Firefox 3.x and IE.
Static HTML:
<header class=line>
<div class="unit size3of4">
<h2 class="fullname"></h2>
<h4 class="nickname"></h4>
</div>
</header>
The jQuery code:
<script>
function load_user_info() {
var content_url = 'rest.api.url.com';
$.getJSON(content_url, {id:'11xx1122xx11'}, function(data){
console.log(data);
$.each(data, function(key, value) {
if (key == "fullname") {$('.fullname').append(value);}
else if (key == "nickname") {$('.nickname').append(value);}
});
});
}
load_user_info();
</script>
Slightly confused about the behavior between browsers. I can guarantee the JSON request is returning two variables: fullname & nickname and have confirmed this
In Firefox using the FireBug plugin I see the results of console.log(data).
In Chrome I see the results of the console.log(data) and the successful display of the fullname & nickname in the HTML after the JSON request.
Using jQuery 1.6.1 if it helps ...
JSON Output:
{"fullname":"johnny fartburger", "nickname":"jf"}
I'm slightly perplexed by what you're doing. I think the following code:
$.each(data, function (key, value) {
if (key == "fullname") {
$('.fullname').append(value);
} else if (key == "nickname") {
$('.nickname').append(value);
}
});
could be more easily represented by this:
$('.fullname').append(data.fullname);
$('.nickname').append(data.nickname);
I don't know if this will solve your problem, but it would certainly be an improvement.
The resulting problem was from the actual JSON data not being retrieved in IE. Hours and hours of search turned up the problem was that XDomainRequest is not natively supported by jQuery, specifically in a $.getJSON request
http://bugs.jquery.com/ticket/8283
In the end, I wrote a try {} catch {} statement that checks to see if $.browser.msie and if it is, do not use $.getJSON to retrieve the results, rather:
if ($.browser.msie) {
var xdr = new XDomainRequest();
xdr.open('GET', url);
xdr.onload = function() {
var data = $.parseJSON(this.responseText);
show_data(data);
}
xdr.send();
} else {
$.getJSON(url, function(data){
show_data(data);
});
}
So ... conclusion append does work in IE (7/8/9) and Firefox (3/4) but not when the AJAX results aren't being returned. Thanks everyone for your help and insight.
.append(value) is not very safe (for example if value="div").
You should use .html(value)
And what does data contain? I think .append is used to append elements. If data is plain text, that might not work (haven't tried it actually). Chrome uses a different engine and may convert the text to a textnode in the DOM.
Use .text() or .html() to set the contents of an element.
as an alternative with appendTo, try to use .text() too
.append() takes a HTML string as a parameter to append to the existing content. You probably want to replace the element's text, use .text() or .html() instead, depending on the contents of the value variable.
Related
I am currently developing a single page application, using phonegap. What i am trying to realize is to initially parse a xml file and store the content for further usage.
At the moment everything works fine but there is one major problem:
Within my xml file there is a a tag which contains html formatted text content. For example:
<textfield> <h1>Title</h1> Content </textfield>
What i currently do is to load my xml file via jQuery ajax call and then use the html() method to retrieve my textfield html:
this.description = $(Obj).find("textfield").html();
On Google Chrome, Firefox and Android this works fine. The html is stored an can later be appended to my objects. However on Safari and therefore on Iphone devices the html() does not work. Now i am looking for a workaround. I certainly do not want to use text() because my formatting will be ignored.
EDIT: My ajax call:
$.ajax({
type: "GET",
url: Controller.baseURL+"/"+name+".xml",
async: false,
timeout:3000,
dataType: "xml",
success: function (data) {
alert("succ");
xml = data;
},
error: function () {
alert('error!');
}
});
Maybe someone can help me.
Thanks in advance
var parser = new DOMParser();
var parsed = parser.parseFromString(yourXMLStringLoadedViaAjax, 'text/xml');
var textfieldConetent = parsed.querySelector('textfield').innerHTML;
After a few hours of search I finally found my answer here:
https://stackoverflow.com/a/25789924/3566334
It seems that
In IE 9, 10 and 11, Safari 7.0 and Opera 12, the nodes in doc have neither an innerHTML field nor an xml field
I followed the advice of using XML Serializer and it works like a charm!
I'm using ajax to get some data then based on the data use html() to put it on the page.
In IE, the data returned is empty (it's html). It still triggers the success function, but the html is not there. I've set the dataType: "text" but still doesn't work.
Any ideas?
Thanks!
EDIT:
Here's the exact code:
$('#frm').submit(function(event){
event.preventDefault();
var self = this;
z = $('#zipcode');
if(z.val() != '' && z.val().length == 5) {
var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
return false;
}
} else {
return false;
}
$.ajax({
url: "/ajax/zip",
type: 'GET',
async: false,
dataType: 'html',
data: {zipcode: $('.zip_field').val()},
success: function(data) {
if(data == 'false'){
error($(".zip_field"));
return false;
}else{
self.submit();
$('.container').empty().append(data);
}
}
});
})
It's submitting a zip code. On submit, it checks to make sure it's a number and 5 digits in length. If that passes, it goes to the ajax and checks to make sure it's a valid zip code (database check), if that fails it returns 'false' as text, if it's good then it returns some html.
It works in Firefox and Chrome, but not in IE. When it's good, it submits the form but the data returned alerts empty and is appended as empty space.
demo: https://so.lucafilosofi.com/jquery-ajax-return-data-empty-in-ie/
your code don't work simply because it is buggy, it have nothing to do with IE.
it should be something like below.
$('#frm').submit(function (e) {
e.preventDefault(); // this one already act as return false...
var form = $(this);
// why you have .zip_field & #zip_code ?
var zip_code = $.trim($('#zip_code').val());
var valid = (zip_code.length === 5 && !isNaN(zip_code)) ? true : false;
if (valid) {
$.get('/ajax/zip', {
zipcode: zip_code
}, function (data) {
if (data == 'false') {
alert('error!');
} else {
//if you submit the form here
//form.submit(); then the line below
//is totally useless
$('.container').html(data);
//.empty().append() is = .html()
}
});
}
});
NOTE: the fact that chrome and firefox don't display errors dosn't mean that errors are not there; internet-explorer simply tend to display errors everytime it run through malformed code etc. Also i strongly doubt that your code work really as expected since it is not so good as you may think. I guess the problem is in your code and have nothing to do with jQuery itself or it's ajax function or dataType.
One thing could be that this URL is cached by the browser. If you obtain a 304 status your response's text it will be empty. Check your HTTP cache headers, and adjust them properly. You could also trying to use POST (only GET are cached).
Also, have a look to Content-Length if is properly set.
If nothing of above works, inspect the network's call will give to you (and us) some additional details, try the IE's dev tools.
You could also try to have the same request using XMLHttpRequest's object directly (assuming you're using IE>6).
I have same problem in IE and Google Chrome
$.ajax is not working in this browser because of security reason.
so if you want to run explicitely
for chrome run chrome with
chrome.exe --disable-web-security
and in IE you need to change setting from Menu>Tools>internet Options
Some versions of IE will not ~repair~ invalid HTML in XHR requests and simply discard it; I've been bitten by this before.
Make sure the HTML returned is valid for the doctype IE thinks you're using (use the developer tools in IE to see), and check your HTML with a validator tool. Obviously, it will complain about missing <html>, <head>, etc, but ignores those and focus on the other errors. once you've fixed those, it should start working.
Also, aSeptik's answer is full of good tips to improve your code.
I have a javascript which receives info from a servlet using jQuery:
$.get("authenticate", {badge:$('input#badge').val()}, function(data) {
console.log("xml: "+data);
displayInfoReturn(data);
});
When I process the result in Safari, everything works great:
function displayInfoReturn(data) {
if (/load/.test(data)) { // ...process string
}
}
But the 'if' always returns false in firefox (haven't tried it yet in IE or Chrome). I also tried using indexOf != -1 and search != -1. Nothing works!
One curious thing I noticed however is when I print data to console:
console.log ("received... "+data);
it comes back with "received... [object XMLDocument]". So apparently it's not treating my data as a string. I tried data.toString() but that doesn't work either. So how can I get firefox to play fair here?
What does your servlet return? An application/xml document or just text/plain? What have you set in response.setContentType()? You seem to be expecting XML and Firefox seems to be telling that it's really an XML document, but yet you're treating it as text/plain with that regex .test(). I'm not sure about Safari, but it look like that it has overridden a toString() on the XML document object so that it returns the whole XML string so that your regex by coincidence works fine.
Without knowing the exact XML document it's hard to tell how exactly to fix it. If it's for example
<data>
<action>load</action>
</data>
Then you can check the presence of load value in the <action> tag using jQuery's own XML parsing facilities as follows:
function displayInfoReturn(data) {
if ($(data).find('action').text() == 'load') {
// ...
}
}
See also:
Easy XML consumption with jQuery
I have a page where I need to add a drag and drop functionality to certain elements. When the drop event occurs, it makes an ajax call to a php function and then refreshes the contents of a div. I'm using jQuery with jQueryUI for the drag and drop, and CakePHP as a PHP framework (not sure if this is relevant).
Everything is working just fine in Firefox, Safari and even IE, but in Opera or Chrome the contents of the div isn't refreshed (although the action from the PHP function is executed).
So, here is the code:
jQuery('#lists div').
filter(function() {return this.id.match(/item[\d]+_[\d]+/);}).
each(function() { jQuery(this).draggable( {axis: 'y'}); });
jQuery('#lists div').
filter(function() {
return this.id.match(/list[\d]+/);}).
each(function() {
jQuery(this).droppable({
drop: function(event, ui) {
dropID = jQuery(event.target).attr('id');
dragID = jQuery(ui.draggable).attr('id');
itemID = dragID.substr(dragID.lastIndexOf('_') + 1);
oldListID = dragID.substr(4).replace(/_[\d]+/g, '');
newListID = drop.substr(4);
jQuery.ajax({
url: "/lists/itemToList/"+itemID+"/"+oldListID+
"/"+newListID,
type: "POST",
success: function (data) {
jQuery('#lists').html(data);}
});
}
});
});
Basically, the success function isn't executed, but if I try to see the errorThrown (on the error event) it is "undefined"
Try something like this:
jQuery.ajax({
url: "/lists/itemToList/"+itemID+"/"+oldListID+
"/"+newListID,
type: "POST",
success: function (data) {
jQuery('#lists').html(data);
}
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
It will show you what http response are you getting for your request. I had the same problem some time ago. My script worked great in Firefox and Chrome, but it didn't do anything in Opera and IE. I checked it and the problem was, that the php backend was returning 404 (I still don't know how did it work under Chrome and FF).
I know it's been a long time since I've posted the question, but here is what I found to be the solution, in case somebody else needs it: the problem was not the in javascript but with CakePHP: the html that was added on success contained an ajax form (rendered using $ajax->form()). $ajax->form() needed the $data variable from the controller to be an array, but for some reason it wasn't, and this broke the rendering of the form, and Opera and Chrome didn't like this. So the solution was to simply add
$this->data = array();
to the itemToList() function in my controller.
I don't see anything in the code that would cause a cross browser issue. My feeling is that it's a problem doesn't lie in the code at all, but in the rendering of the div and/or its contents in Chrome and Opera (i.e. a CSS problem or something along those lines where the innerHTML of the div is updated, but because of styling or positioning you don't get the visual result you were looking for).
Have you checked using Dragonfly or some other developer tool to verify that the contents of the target element are in fact unchanged after a successful request? Along those lines have you tried stepping through the code execution in the problem browsers? You could also try adding a error handler to the JQuery.ajax options to see if there is some problem with the request itself, although I don't believe that is where the problem lies.
EDIT: I didn't see that last bit below the code block. So you have verified that the success handler isn't being executed. You said that you did try and implement an error handler for the request and got some undefined result, but I don't see it in the code. Could you post the code for the error handler and describe what in the error is undefined?
I think he means, that alert(errorThrown) is showing 'undefined'.
I'm working on a Drupal 6 module where I use jquery (and more specifically, the $.ajax method) to retrieve a RSS feed from Yahoo's weather API. I decided against using the JFeed library because I need access to the elements with "yweather" prefix (and I couldn't find a way of accessing them via JFeed). I decided to use the $.ajax method and parse the XML response instead. The JavaScript code below works fine in Firefox and IE but does not work in Safari (or Chrome FWIW):
function parseXml(xml) {
var atmosphere = xml.getElementsByTagName("yweather:atmosphere");
var humidity = atmosphere[0].getAttribute("humidity");
$('#weatherFeed').html("Humidity: " + humidity);
$('#weatherFeed').append(
"<div style=\"text-align: center;margin-left: auto; margin-right: auto;\">" +
city + ", " + state + "</div>");
}
function getData(){
$.ajax({
type: 'GET',
url: 'proxy.php?url=http://weather.yahooapis.com/forecastrss&p=94041',
dataType: 'xml',
success: function(xml) {
parseXml(xml);
}
});
}
if(Drupal.jsEnabled) {
$(function() {
getData();
setInterval("getData()", 30000);
});
}
When I check the error console in Safari I see the following error message: TypeError: Result of expression 'atmosphere[0]' [undefined] is not an object. Is there an issue with using getElementsByTagName in Safari? Should I be accessing the object that's returned by getElementsByTagName differently?
Maybe just treating the the XML as data and using jQuery selectors to pull out what you want would work.
$(xml).find("yweather:atmosphere").attr("humidity") - you might need to use filter instead of find - what do you think?
I had the exact same problem, but came across the answer here:
http://reference.sitepoint.com/javascript/Document/getElementsByTagName
It has to do with the yweather namespace. Use getElementByTagNameNS function instead.
var atmosphere = xml.getElementsByTagName("yweather:atmosphere");
becomes
var atmosphere = xml.getElementsByTagNameNS("http://xml.weather.yahoo.com/ns/rss/1.0","atmosphere");
function reference:
http://reference.sitepoint.com/javascript/Document/getElementsByTagNameNS
Have you tried atmosphere[1] instead of 0 for Chrome and Safari?