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.
Related
I've seen lots of questions about problems with ajax and IE but i haven't found one like this..
The environment is Bootstrap / jQuery / Ajax / parsley / IE-11
I have an ajax script that is working in firefox and chrome. In IE 11, the script will not send... it jumps right to the fail section. It's supposed to pop-up a bootstrap modal with content. The modal pops-up, but it's empty.
the url of the ajax request is the same url as the page it's on...
it's an http request, not an https request.. it's to an internal web server that pings to a 192.168 address.
Ajax requests on an earlier version of this system (between the same url's) that do NOT use bootstrap are working with no problem..
I've turned off all console.log(). didn't help.
I've turn off the server, and it didn't make a difference.. the request isn't getting there...
i've tried lowering all the security settings without going into the custom detail dialog.. no effect..
when i turn back on the console log for fail
i get: Request failed: [object Object] (the object is not clickable)
Something in ie is blocking the request..
<script>
var AjaxSubmit
$("#rbbutton, #ubbutton").click(function() {
AjaxSubmit = $(this).attr("value");
return true;
});
$(function () {
var serverScript = '#serverurl' ; // Server side script we will be calling
$("#rb").submit(function(e) {
var str = $('#rb').serialize();
str = str + '&ajaxfunction=IamBidding' + '&AjaxSubmit='+encodeURIComponent(AjaxSubmit);
if (typeof console == "object") {
}
var request = $.ajax({
type : "POST",
url : serverScript,
data : str,
cache : false,
encode : true
});
request.done(function(data) {
$("#modalbidconfirm").html(data);
$('#bidconfirmmodal').modal('show');
});
request.fail(function( data) {
if (typeof console == "object") {
console.log( "Request failed: " + data );
}
$("#modalbidconfirm").html(data);
$('#bidconfirmmodal').modal('show');
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
</script>
the problem was not in the javascript. the problem was in the html which i did not include in the question.
Firefox and chrome did not have a problem with the serverurl id being defined in a div.
IE would not work unless the serverurl was defined in an input.
<form class="form-inline bidding" ID="rb" name="IamBidding" ACTION="">
i changed this:
<div id="serverurl" value="http://sometingorother.com/?&ajaxfunction=IamBidding"></div>
to this:
<input type="hidden" id="serverurl" value="http://sometingorother.com/?&ajaxfunction=IamBidding" />
and the script works in all 3 browsers.
I have an html file with many <a> tags with href links.
I would like to have the page do nothing when these links point to an outside url (http://....) or an internal link that is broken.
The final goal is to have the html page used offline without having any broken links. Any thoughts?
I have tried using a Python script to change all links but it got very messy.
Currently I am trying to use JavaScript and calls such as $("a").click(function(event) {} to handle these clicks, but these have not been working offline.
Also, caching the pages will not be an option because they will never be opened online. In the long run, this may also need to be adapted to src attributes, and will be used in thousands of html files.
Lastly, it would be preferable to use only standard and built in libraries, as external libraries may not be accessible in the final solution.
UPDATE: This is what I have tried so far:
//Register link clicks
$("a").click(function(event) {
checkLink(this, event);
});
//Checks to see if the clicked link is available
function checkLink(link, event){
//Is this an outside link?
var outside = (link.href).indexOf("http") >= 0 || (link.href).indexOf("https") >= 0;
//Is this an internal link?
if (!outside) {
if (isInside(link.href)){
console.log("GOOD INSIDE LINK CLICKED: " + link.href);
return true;
}
else{
console.log("BROKEN INSIDE LINK CLICKED: " + link.href);
event.preventDefault();
return false;
}
}
else {
//This is outside, so stop the event
console.log("OUTSIDE LINK CLICKED: " + link.href);
event.preventDefault();
return false;
}
}
//DOESNT WORK
function isInside(link){
$.ajax({
url: link, //or your url
success: function(data){
return true;
},
error: function(data){
return false;
},
})
}
Also an example:
Outside Link : Do Nothing ('#')
Outside Link : Do Nothing ('#')
Existing Inside Link : Follow Link
Inexistent Inside Link : Do Nothing ('#')
Javascript based solution:
If you want to use javascript, you can fix your isInside() function by setting the $.ajax() to be non asynchronous. That is will cause it to wait for a response before returning. See jQuery.ajax. Pay attention to the warning that synchronous requests may temporarily lock the browser, disabling any actions while the request is active (This may be good in your case)
Also instead of doing a 'GET' which is what $.ajax() does by default, your request should be 'HEAD' (assuming your internal webserver hasn't disabled responding to this HTTP verb). 'HEAD' is like 'GET' except it doesn't return the body of the response. So it's a good way to find out if a resource exists on a web server without having to download the entire resource
// Formerly isInside. Renamed it to reflect its function.
function isWorking(link){
$.ajax({
url: link,
type: 'HEAD',
async: false,
success: function(){ return true; },
error: function(){ return false; },
})
// If we get here, it obviously did not succeed.
return false;
}
Python based solution:
If you don't mind preprocessing the html page (and even caching the result), I would go with parsing the HTML in Python using a library like BeautifulSoup.
Essentially I would find all the links on the page, and replace the href attribute of those starting with http or https with #. You can then use a library like requests to check the internal urls and update the appropriate urls as suggested.
Here is some javascript that will prevent you from going to external site:
var anchors = document.getElementsByTagName('a');
for(var i=0, ii=anchors.length; i < ii; i++){
anchors[i].addEventListener('click',function(evt){
if(this.href.slice(0,4) === "http"){
evt.preventDefault();
}
});
}
EDIT:
As far as checking if a local path is good on the client side, you would have to send and ajax call and then check the status code of the call (infamous 404). However, you can't do ajax from a static html file (e.g. file://index.html). It would need to be running on some kind of local server.
Here is another stackoverflow that talks about that issue.
I have the following code that runs when the process_2banner button is clicked on a html page. This code does what is supposed to do when using Firefox. When using Chrome and Internet Explorer the ajax code is called but the div spinner_block does not show/hide as the code intends to.
Strangely enough it works if I open firebug in Chrome and place a breakpoint right before the ajax call (after the .css("display","block") statement. The spinner_box <div> shows, and then after the ajax call returns, it hides.
Can you see what is wrong here?
Thank you very much!
Andres
$('#process_2banner').on("click",function() {
var postdata = "lead_id="+rowId; //needs to include the pidm of the user clicking the button
$('#spinner_box').css("display","block");
$('#spinner_box').html('Wait, we are processing the record..');
$('#spinner_box').css("display","block");
$.ajax({type: "POST",
url: "insert_srwordpress.php",
data:postdata,
success:function(result) {
if (result.isOk == false) {
alert('Some error occurred while writing Banner') }
else {
$('#spinner_box').hide();
}
},
async: false});
});
The response result is an string in format JSON?
May you need parse the JSON before use it?
Example:
var jData = $.parseJSON(result);
if (jData.isOk === false) {
}
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 have basically this on a page:
<script type="text/javascript">
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
$("#ajax-context").html($("display", xml).text());
$("#context").val($("context", xml).text());
}, 'xml');
}
$(document).ready(function() {
$("#username").blur(refresh_context);
});
</script>
<input type="text" name="username" id="username" maxlength="255" value="" />
<input type="hidden" name="context" id="context" value=""/>
<div id="ajax-context"></div>
What it should do (and does fine on Firefox) is when you type a username in to the #username field, it will run /ajax/ldap_search.php?cn=$username, which searches our company's ldap for the username and returns it's raw context and a formatted version of the context like this:
<result>
<display>Staff -> Accounting -> John Smith</display>
<context>cn=jsmith,ou=Accounting,ou=Staff,ou=Users,o=MyOrg</context>
</result>
The formatted version (display) goes to the div #ajax-context and goes to the hidden input #context. (Also, the -> are actually - "& g t ;" (without spaces)).
However, on IE the div stays stuck on "Searching..." and the hidden input value stays blank.
I've tried both .get and .post and neither work. I'm sure it's failing on the .get because if I try this, I don't even get the alert:
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function() {
alert("Check");
});
Also, IE doesn't give me any script errors.
Edit: Added "$(document).ready(function() {", the .blur was already in it in my code, but I forgot to include that in my post.
Edit 2: The request is being sent and apache2 is receiving it:
10.135.128.96 - - [01/May/2009:10:04:27 -0500] "GET /ajax/ldap_search.php?cn=i_typed_this_in_IE HTTP/1.1" 200 69
Problem was in the ldap_search.php file.
I had this (based on an example I read on someone's blog):
header("content-type:application/xml-xhtml;charset=utf-8");
It actually needed to be this for IE to read it properly:
header("content-type:application/xml;charset=utf-8");
God, I hate IE.
Try changing:
$("#username").blur(refresh_context);
To:
$(function(){
$("#username").blur(refresh_context);
});
This will hold off on assigning the blur event until the entire page is loaded.
Edit:
Could it be the use of > in the text of the XML?
set your type to 'xml'
jQuery.get( url, [data], [callback], [type] )
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function() {
alert("Check");
},'xml');
Can you find out if the Ajax request is even being fired?
You can use Web Development Helper or Fiddler to log Ajax requests.
As general good practice you should enclose any jQuery code that accesses the DOM in a $(document).ready function. This will ensure it doesn't execute until the entire DOM is loaded, although in this instance it doesn't look like that's causing the problem if the div is changing to 'Loading...'
<script type="text/javascript">
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
$("#ajax-context").html($("display", xml).text());
$("#context").val($("context", xml).text());
}, "xml"); // As pointed out, you should specify the return type
}
$(document).ready(function() {
$("#username").blur(refresh_context);
});
</script>
You may want to change the $.get call to a $.ajax call, so you can set an error handler to see why it's erroring.
As I recall, this is done like this:
$.ajax({
type: 'GET',
url: "/ajax/ldap_search.php",
data: {cn: $("#username").val()},
success: function(response) { /* do something here */ },
error: function(xhr, type, exception) { alert("Error: " + type); }
})
The exception object should have more detail about the error as well.
I had same problem but not with xml - i had simple html as ajax-return. header("content-type:text;charset=utf-8"); was the solution.
Does not work:
$.post("/welcome/add_mail", function(data){
alert('ok');
});
Works fine with base url in IE7:
$.post("http://localhost/welcome/add_mail", function(data){
alert('ok');
});
Usually with $.get/$.post you have to specify the return type. This makes it easier for jquery to a) recognize what it looks for and b) decode it for you.
This may help.
Instead of $("display", xml).text()
Maybe try: $(xml).find("display").text()
Can you see what the response is or is it just timing out? Can you see what params are being sent in? If not, expand your:
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
$("#ajax-context").html($("display", xml).text());
$("#context").val($("context", xml).text());
}, "xml"); // As pointed out, you should specify the return type
}
to
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
var displayXml = $("display", xml).text();
$("#ajax-context").html(displayXml);
var contextXml = $("context", xml).text();
$("#context").val(contextXml);
}, "xml"); // As pointed out, you should specify the return type
}
and then debugging the script.
I had a similar problem, but loading JSON. The $.ajax fix worked for me but I also discovered that in my case it had to do with the URL. When I use:
$.getJSON('',{ ajax: "addressPicker",OID:pickIDNo,s:pickVal}, function(data) {
I would get a silent response, but when I replaced the empty URL '' with '?' it worked. In your case the URL was present, but it might be picky as to URL.