The script below queries a PHP service that returns a JSON response. Buttons are created for each returned record, allowing the user to delete that record from the database. A link is also created below to refresh the data.
This all works fine in IE, Chrome, Safari...IE (tried 8 & 9), however, is having a strange issue.
When the page loads, I am able to refresh the data by clicking the 'refresh' link. After this, clicking has no effect UNLESS I open the same page in a different IE window, click the link in the new window, and return to the original window. The 'refresh' link then works on the new window ONE time. It then turns into a vicous cycle.
Your help is appreciated!
function getNew(){
$('#new').remove();
$.getJSON('service.php', function(data) {
var items = [];
items.push('<tr><th>EmplId</th><th>ExternalID</th><th>Name</th></tr>');
$.each(data, function(key, val) {
var indiv = val.toString().split(",");
items.push('<tr>');
var id = indiv[0];
$.each(indiv, function(index, value) {
items.push('<td align="center" id="' + index + '">' + value + '</td>');
});
items.push('<td class="updateButton" align="center" onclick=\'return update("'+id+'")\'>Update</td>');
});
items.push('<tr><td class="refreshButton" align="center" onclick=\'return getNew();\'>Refresh </td></tr>');
$('<table/>', {
'id': 'new',
html: items.join('')
}).appendTo('body');
});
}
function update (emplID){
$.ajax({
url: "service.php?emplID="+emplID,
context: document.body,
success: function(){
$('#new').remove();
getNew();
}
});
}
I have tried using .live and I get the same results.
$(".refreshButton").live("click" , function() {
getNew();
$.ajax({
url: "Service.php?emplID=",
context: document.body,
success: function(){
$('#new').remove();
getNew(); }
});
});
I have disabled the cache still to no avail. The ONLY way to make the link work is to open the same page in a separate window, click the link, and return to the original window. Is there any solution to this?
$(".refreshButton").live( "click" , function() {
getNewStudents();
$.ajax({
url: "studentService.php?emplID=",
cache: false,
context: document.body,
success: function(){
$('#newStudents').remove();
getNewStudents();
}
});
});
Thanks for your suggestions. I fixed the tr, but it seems that the solution was to use
$.ajaxSetup({ cache: false });
It seems all versions of IE treat ajax calls as normal web requests (cacheable), whereas other browsers consider ajax calls as non-cacheable.
Learned something new today, thanks guys!
Maybe it's because of cache, have you tried to clear your cache and try again? this may help http://kb.iu.edu/data/ahic.html#ie8
Perhaps IE is choking on the malformed HTML that getNew is generating; note that in your .each loop, you are not closing the tr element. Also, if you're getting a JavaScript error, JS execution may stop, so make sure your browser isn't configured such that it ignores JS errors. Check the error console.
Related
I've been trying to solve this problem for hours now maybe anyone of you could help me.
Right now my Code looks like this:
$('.clickable').on('click', function() {
var id = $(this).attr('data-packages');
id = "'" + id + "'";
$.ajax({
url: "show.php",
data: {
type: "showSFM",
data: id,
user: username
},
type: "POST",
success: function(data) {
$('#main').html(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Everything is working fine but I was asking myself If it is possible to use $('#main').html(data) on a new Window. Right now if I click an Element the current window is showing the result but I want a new tab to pop up with the result.
I was trying things like this:
success: function(data) {
var url = location.href;
var window = window.open(url);
window.document.getElementById('main').innerHTML = data;
}
The result I'm getting is that the window opens on the main page. Looks like window.open(url) works just fine but the line below does nothing.
The reason this likely doesn't work is due to the fact that you use:
window.document.getElementById('main')
The window might already be opened by the line before, but is most likely not loaded and doesn't contain an element with id main yet (since making a HTTP(S) request takes time). This could be solved by moving the filling of main element into a callback.
window.addEventListener('load', function () {
window.document.getElementById('main').innerHTML = data;
}, { once: true });
You can send the data you need for the request in the URL and then on the new page, you can send the AJAX request again, and getting the data you need for it from the URL.
$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").html("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").html(data_aj);
}
});
I really have tried everything but can't figure out whats wrong. If I use alert(data_aj); it gives the desired output and just works fine but HTML(data_aj) just doesnt loads into a <ul> element #list using .html(). Can anyone tell me why?
Have you tried putting your code in a document ready, as your alert will fire fine but if your dom is not loaded then you cannot append to it. Also use .append() for lists not html
$(document).ready(function() {
$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").append("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").append(data_aj);
}
});
});
Listen up...
$.get() is a shorthand for $.ajax().
So when you do this
$.get(uri, function(data){
//Your functionality
});
You're really doing this
$.ajax({
url: uri,
type: "GET",
success: function(data) {
//Your functionality
}
});
By default this returns the page as HTML. Or rather, by default, it first checks the MIME-type on the page, and if none is found, it returns HTML. As you are requesting a .txt file it will interpret it as a simple textfile. If you want to tell it what you would like to return (HTML), you can either do it in the MIME-type on the server page, or you could use $.getJSON().
An easy way to solve this is thus doing:
$.get(uri, function(data) {
//Your functionality
},
"html");
Which is the same as doing:
$.ajax({
url: uri,
type: "GET",
dataType: "HTML",
success: function(data) {
//Your functionality
}
});
Also it is not a good idea to use html() because you are replacing the existing html inside of your ul element every time you want to add an additional new node.
Try making use of:
$('#list').append('<li>' + data_aj + '</li>');
Basically you can just append the <li> to the <ul> itself.
Lastly make sure your dom has already been loaded by placing all your JQuery code into the
$(document).ready(function() {
//Your code...
});
Otherwise if your HTML is not fully loaded yet, your list might not exist yet so there is no way for JQuery to put some values into unexisting HTML.
New to JQuery but want to use it to prefetch html pages in the background (about four # about 4kb each) but I am not quite sure I am doing this right.
Here is the code I have come up with:
$(document).ready(function() {
var my_url;
$('[rel=prefetch][href$=.html]')
.each(function() {
my_url = $(this).attr('href')
$.ajax({
url: my_url,
dataType: 'text',
headers:{'X-Moz': 'prefetch'}
});
});
});
Basically, I have some links with 'rel=prefetch' in the head of the document and the code snippet above is inserted when the browser is not Firefox. My application renders things differently when the 'X-Moz: prefetch' header is detected so this is sent here as it is needed.
The code is supposed to just get the html and cache without processing scripts which I believe 'dataType: text' should take care of.
Will appreciate some eyes on this and suggestions. Queries are:
Is the code above valid? If not what is the fix?
What do I need to change to limit the selector's scope to the < head > ... < /head > section?
$(document).ready(function() {
$('[rel=prefetch][href$=.html]')
.each(function() {
var my_url = $(this).attr('href')
$.ajax({
url: my_url,
dataType: 'text',
headers:{'X-Moz': 'prefetch'}
});
});
});
Got it working. The issue was because the jquery snippet was not running when I linked to JQuery using the google api. When I serve it directly from my site, in which case all the js is combined into one file, it works.
I noticed this when I used the developer tool in Safari.
The full code is:
(function ($) {
$(document).ready(function() {
var this_browser, my_url;
// Prefetch pages for non Firefox browsers
this_browser = new Browser();
if ( this_browser.getBrowserName() != this_browser.BROWSER_FIREFOX ) {
// Asynchronously prefetch html as text strings
// I.E., do not process scripts in incoming html
// See: http://ernstdehaan.blogspot.com/2009/08/prefetching-files-using-jquery.html
$('link[rel="prefetch"][href$=".html"]')
.each(function() {
my_url = $(this).attr('href');
$.ajax({
url: my_url,
dataType: 'text',
headers: {'X-Moz': 'prefetch'}
});
});
}
});
}(jQuery));
Safari alerted me that the "(jQuery)" bit was generating an error.
It turned out that this was because the code was fired before JQuery was loaded.
Also forgot to mention that
$('head link[rel="prefetch"][href$=".html"]')
Limits the selector.
I have also removed the browser detection and just use this for all browsers.
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 new to JQuery and web development in general. I'm trying to load some data from an XML file and build an unordered list. I've got that part working, now I'm trying to use the TreeView plugin so I can collapse/expand the data. The data is loaded like this:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "solutions.xml",
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == "string") {
// Work around IE6 lameness
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
list = ""
$(xml).find("Group").each(function() {
group = $(this).attr("name");
list += "<li><span>" + group + "</span><ul>";
$(this).find("Solution").each(function() {
solution = $(this).attr("name");
list += "<li><span>" + solution + "</span></li>";
});
list += "</ul></li>";
});
$("#groups").html(list);
},
error: function(x) {
alert("Error processing solutions.xml.");
}
});
$("#groups").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
});
and the HTML looks like this:
<html>
...
<body>
<ul id="groups">
</ul>
</body>
</html>
The unordered list shows correctly, but the little [+] and [-] signs don't show up and the sections aren't collapsible/expandable. If I get rid of my Ajax loading and insert an unordered list inside of #groups manually it works as expected.
What am I doing wrong? Is there any other plugins or Javascript libs that could make this easier? The solution needs to work on IE6 locally (i.e. webserver).
Update: I found a work-around: If I define my treeview stuff like this it works:
function makeTreeview() {
$("#container").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
}
setTimeout('makeTreeview();', 50);
I think the problem is, when I create the treeview, the ajax stuff hasn't done it's work yet, so when treeview() is called, the unordered list hasn't been created yet. I haven't tested this with IE6 yet. Is there a nicer way to do this, without using SetTimeout()?
I made the same type of call for another project.
For other reasons you will probably want to wrap your ajax call in an anonymous function to create a closure so that your variables remain what you expect them to...
The success method is a callback function that happens after your call is complete , just create your treeview inside that method, or break it out into a seperate fumction if you need to for clarity.
in the example that you show - your treeview will still fail if the ajax call takes longer than 50ms - which could easily happen during initial load if more than two objects are being loaded from that same server.
This example used JSON, and concurrently loaded html data from a page method into a series of divs.
$(document).ready(function() {
for (i= 1;i<=4;i++)
{
(function (){
var divname ="#queuediv"+i;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test12.aspx/GetHtmlTest",
data: "{}",
error: function(xhr, status, error) {
alert("AJAX Error!");
},
success: function(msg) {
$(divname).removeClass('isequeue_updating');
$(divname).html(msg);
$("#somethingfromthemsg").treeview();
}
});
})();
}
});
Hope that helps!
You need to get FireBug (Firefox add-in) and then you can see in the console what is being returned, and make sure it matches what you expect (And that it is actually doing the request..).
Once you get it working in FF, you can support the ancient 10-year old IE6 browser.
There's also some other things you may want to consider:
The whole ActiveXObject("Microsoft.XMLDOM") jumps out as me as unnecessary. If you pass XML in a string to $(), jQuery turns it into a DOM object.
Additionally, .Find can be replaced by:
$('Element', this);
So for example:
var xmlDoc = '<Group><Solution name="foo" /><Solution name="bar" /></Group>';
$('Solution', xmlDoc).each(function() {
document.write( $(this).attr('name') );
});
would spit out:
foo
bar
Also, with firebug, stick a console.log(list); at the end, to be sure you're generating the HTML you think you are. If you're really stuck in IE6, alert(list) somewhat works as a poor man's equivalent (as long as your file isn't too big).
In short, I think you're on the right track, you just need the tools to debug properly.
For anyone who also finds their way to this post. I had this trouble with an ajax call.
If you want to wait for the ajax call to be returned, you need to set async as false.
$.ajax({
type: 'POST',
async: false,
........