$.ajax not working properly on IE6 - javascript

Basically, I have something like this:
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
dataType: 'json'
});
This code is working in all tested browsers (IE7/8, chrome, safari, firefox) but in IE6 the success function is not called.
I used Fiddler to see what's going on in the HTTP requests, and everything seems normal, I get the expected result as an HTTP answer but success doesn't seem to be called in IE6, same for onerror.
Any thoughts?

Try using complete instead of success. If it fires consistently then you can evaluate the status code to determine if it was successful...
$.ajax({
type: "GET",
cache: true,
complete: function(xhr) {
if(xhr.status != 200) {
throw "Error!";
return;
}
var data = xhr.responseText;
}
});

Are you sure it's not just a cache thing? Remove your browsers cache and test again.
A good test case would be getting rid of the 'cache' option, and also making it a POST request (since GET ajax calls are always cached in ie6).

You don't mention the server-side code you're using. I had some issues with jQuery AJAX calls in IE when using ASP.NET on the server side (a ashx handler). They went away when I read the request fully before starting to write the response (even though in my case I was using POST, not GET request, so the body of the request contained some data).
I wrote the following simple ASP.NET project to test your issue in IE6. However I'm unable to reproduce (IE6 SP2 running in virtual machine hitting IIS 7.5 shows the alert box from success handler properly). Could you try running it in your environment and reporting whether it works from IE6 for you?
Note: Sometimes when I cleared IE6 cache and commented out the "SetCacheability" line in ashx.cs, the first click on "Send" button would not show the success alert box, although subsequent clicks did show it. Maybe all you need is adding "no-cache" headers to the call response in your implementation?
file index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX GET test</title>
</head>
<body>
<input type="button" id="test" value="Send" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$("#test").click(function () {
$.ajax({
url: "Api.ashx?param=one",
cache: true,
type: "GET",
dataType: "json",
success: function (data) {
alert("Success, result = " + data.result);
},
error: function (request, status, err) {
alert("Error");
}
});
});
</script>
</body>
</html>
file Api.ashx
<%# WebHandler Language="C#" CodeBehind="Api.ashx.cs" Class="AjaxTest.Api" %>
file Api.ashx.cs
using System.Diagnostics;
using System.Text;
using System.Web;
namespace AjaxTest
{
public class Api : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
var param = context.Request["param"]; // this flushes the request
Trace.WriteLine("Request: \"" + context.Request.RawUrl + "\", param: \"" + param + "\"", "** Debug");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Write("{\"result\":\"" + param + "\"}");
}
}
}

What happens if you add a failure function, and alert out the responseText within there?
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
error: function(data) {
alert(data.responseText);
},
dataType: 'json'});
http://docs.jquery.com/Ajax/jQuery.ajax#options

Related

PHP & JS - append html and scripts on page

I'm using an ajax call to append a MVC partial view with some styles sheets and script files to my php page.
However it is not appending de <script> tags. I already checked my HTTP request on the network and it really brings those tags.
My code:
$.ajax({
type: 'POST',
url: 'http://localhost:63322/MyController/MyAction', //external url project
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
crossDomain: true,
processdata: true,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "*"
},
success: function(result){
$(".pageContainer").html(result);
},
error: function(er){ alert('Error'); }
});
On ajax success function I already tried:
to use $(".pageContainer").empty().append(result)
to separate the script tags and add to <head> like this:
var elems = $(result);
var scripts = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() == "script";
}catch(er){ return false; }
});
var remainElems = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() != "script";
}catch(er){ return false; }
});
$.each(scripts, function(){ $('head')[0].appendChild(this); });
$(".pageContainer").append(remainElems);
to give some time before appending with setTimeout(function(){ $(".pageContainer").html(result); }, 1000);
to change <script> tags to <link type="text/javascript" src="http://someurl.com" rel="tag"/> and it was appended but the code wasn't executed
But nothing works.
What is wrong? What I'm missing?
My PHP page uses jquery-1.8.3 and jquery-ui-1.9.2.custom. This is the problem?
NOTE:
My question is very different from that on: Executing inside retrieved by AJAX
If you read both you will see they are very different. I already readed what and noticed that.
Solved. I don't know why but seems jquery-1.8.3 don't performs the insertion of the <script> tags to the html code dynamically.
I changed
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
to
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
and now it works.

Uncaught ReferenceError when calling REST Service using jQuery

I'm really new in web services, so I would appreciate any help here. I have created a RESTful web service using Spring-boot. The code for my web service is simple as I'm just testing:
#RestController
public class MainController {
#RequestMapping("/test")
public String getStringTest(#RequestParam(value="name", defaultValue="Test") String name){
System.out.println("Name received: " + name);
return "HelloTest: " + name;
}
}
After deploying the web service, I'm able to access it using: http://localhost:8080/imagesTest and I get the "HelloTest" string in my browser, so it's working fine. But the problem is when When I try to access it using jQuery in a web page it's not working. This is the page:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<p id="info"></p>
</body>
</html>
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: "http://localhost:8080/test?name=Gabriel",
success: function(data){
alert("Success: " + data);
},
error: function(){
alert("Something went wrong.");
}
});
})
</script>
When I execute my page, I get the following error message in the console:
Uncaught ReferenceError: HelloTest is not defined(anonymous function)
# imagesTest?callback=jQuery1113027941066049970686_1447350578572&_=1447350578573:1
Any help on this would be very much appreciated so I can understand what's really going on.
Thank you in advance for your help.
dataType: 'jsonp' tells jQuery to expect JSONP, but your returning a plain string "HelloTest: Gabriel"
Change the dataType to something more suitable, such as "text" (or remove it completely)
$.ajax({
type: 'GET',
dataType: 'text',
url: "http://localhost:8080/test?name=Gabriel",
success: function(data){
alert("Success: " + data);
},
error: function(){
alert("Something went wrong.");
}
});
The possible values are listed in the api documentation of the $.ajax method

IE 8 caching ajax calls

I am trying to get some data using ajax GET method, it works great in all the browsers except IE.
In IE it is caching the data the first time the call is made and caching it I need to prevent it.
I tried the following methods in my code but still unable to resolve the issue
1) Setting caching = false globally in the code
$.ajaxSetup({ cache: false });
2) putting this in the meta tags
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
3)Using POST instead of GET method
$.ajax({
cache: false,
type: "POST",
url: '/XYZURL/' + Id,
dataType: "json",
async: false,
success: function(Response) {
$scope.data = Response;
},
4)Tried including this bit in my code but with no success
if(url.replace("?") != url)
url = url+"&rand="+new Date().getTime();
else
url = url+"?rand="+new Date().getTime();
Please help me with this issue, it has been bugging me for the past 2 days.
Thank you in advance.
var browser = window.navigator.userAgent;
var msie = browser.indexOf ( "MSIE " );
if(msie > 0){
var remoteId = index.entity.id;
var ie_fix = new Date().getTime();
$.ajax({
cache: false,
type: "GET",
url: '/XYZURL/' + Id,
dataType: "json",
async: true,
success: function(Response) {
$scope.data = Response;
},
error: function(jqXHR,errorThrown) {
alert("jqXHR");
}
});
}else{
$scope.data = datafactory.show({id: index.id});
}
Altough my code is angular based I used jQuery ajax for all the service calls but tried to implement angular and ajax calls depending on the browser and that has solved my issue. I know it may not be the right approach but the only solution which worked for me.
As suggested in this post, How to prevent a jQuery Ajax request from caching in Internet Explorer?
If you are using cache: false option, calls shouldn't be cached. What I found different is async option.
So, Try after changing, async: false to async: true in your ajax call.

Parsing xml data from a remote website

I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());

No return value from getJSON

The alert with "success" is not fired when i run this. I checked with firebug, and it tells me that ret is undefined. What does that mean?
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var ret = $.getJSON(URL, function(data, textStatus) {
alert("success");
});
}
EDIT:
this is the test.jsp btw
<%# page language="java" contentType="application/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*, net.sf.json.JSONObject"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
response.setContentType("application/json");
JSONObject jo = new JSONObject();
jo.put("location", "1");
jo.put("name", "someUni");
out.println(jo);
out.flush();
%>
</body>
</html>
The AJAX call did not work. A few points to check, is the URL correct? Did you check the application server log to see if the call has ever reached. Can you check firebug for the HTTP code if the AJAX call is successful?
EDIT:
(Changed from text/json to application/json) Thanks Bergi
JSP:
<%# page contentType="application/json" %>
Java Servlet:
response.setContentType("application/json");
First check for ".jsp" file returning json data or not
Use one more parameter for callback
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
User like this
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var ret = $.getJSON(URL,"",function(data){
alert("success");
});
}
ret is scoped to your function, so only code inside your function can access it. My guess is that you don't have a web server running on port 8080 of your local computer or the URL is invalid for some other reason. Try .ajax if you want to get a callback on the error also (fiddle):
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var ret = $.ajax(
{
url: URL,
success: function(data, textStatus) {
alert('success!');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error "' + textStatus + '": ' + errorThrown);
}
});
}
You might want to check your json too, the getJson page warns that it will fail silently on inavlid json, including strict requirements like quoted property names, you can try just using .get and deserializing yourself.

Categories