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.
Related
I have a jsp where there are two radio buttons and based on the button clicked I call corresponding function. Both the functions have ajax call and the success response opens the new url in new tab. The first function does it perfectly , but second function doesn't work properly.
Console doesn't show anything. (Chrome)Pop up blocker blocks the response link from second function's ajax response, but not for the first function's ajax response.I don't want the (chrome) browser's pop up blocker to block it. This doesn't happen in Firefox and Safari. I haven't tried against IE yet. But right now happening only in Chrome.
function submit(){
if($('input[name=questionOption]:checked').val() == "A"){
yesHelper();
}else if($('input[name=questionOption]:checked').val() == "B"){
addHelper();
}
}
function yesHelper(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var AQuestion = document.getElementById("A_Actual_Question_Id").value;
var lang= "T";
var stringifiedInput = JSON.stringify({"A_Actual_Question" : AQuestion, "language" : "T"});
alert(stringifiedInput);
$.ajax({
url: "/Abcd/efgh/add1",
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: stringifiedInput,
beforeSend: function(xhr) {
xhr.setRequestHeader(header, token);
},
success: function(response){
window.open("http://localhost:8080/Abcd"+response, '_blank');
}
});
}
function addHelper(){
var token1 = $("meta[name='_csrf']").attr("content");
var header1 = $("meta[name='_csrf_header']").attr("content");
var B_Question = document.getElementById("B_ActualQuestion_Id").value;
var lang1= "T";
var B1 = document.getElementById("B1_Id").value;
var stringifiedInput_B = JSON.stringify({"B_Question" : document.getElementById("B_ActualQuestion_Id").value,
"language" : "T",
"B1" : B1
});
$.ajax({
url: "/Abcd/efgh/add2",
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: stringifiedInput_B,
beforeSend: function(xhr) {
xhr.setRequestHeader(header1, token1);
},
success: function(response1){
window.open("http://localhost:8080/Abcd"+response1, '_blank');
}
});
}
If you don’t want browsers to block a popup, then you must open it directly on some sort of user interaction (such as a click on something) – otherwise, most current browsers will block it in default settings, because popups opened without user interaction are usually the ones users don’t want (advertising, or other annoying stuff.)
Now, making an asynchronous AJAX request first, and then trying to open the popup in the success handler, has already “decoupled” this from the initial user interaction.
You could instead try to:
make a synchronous AJAX request instead (not recommendable),
open the popup first (address about:blank), make the AJAX request, and then change the location of the popup window afterwards.
Using the LinkedIn API, I want to get the share count for an URL.
https://www.linkedin.com/countserv/count/share?url=http://www.linkedin.com&format=json
But this gives me an error because of Same-Origin Policy.
I want to use JSONP to then get the data, but I am stuck there.
$.getJSON("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback", function(data) {
elem.find(".count").html(data.count);
});
I still get the Same-Origin Policy error and no data from data.count.
Can anyone help me out? Thanks!
Try
myCallback = function(data) {
// do stuff with `data`
};
var url = "https://www.linkedin.com/countserv/count/share?"
+ "url=https://www.linkedin.com&format=jsonp&callback=myCallback";
$.getScript(url);
See jQuery.getScript()
myCallback = function(data) {
$("body").append("<pre>" + JSON.stringify(data, null, 2) + "</pre>")
};
$.getScript("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Thanks everyone for your answers, but I solved it already myself.
This worked for me:
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
As of jQuery 1.5.1, this is the recommended way of structuring AJAX requests:
$.ajax({
dataType: "jsonp",
url: "http://www.linkedin.com/countserv/count/share",
data: {
callback: "?",
format: "jsonp",
url: "http://www.example.com/"
}
}).done(function(data) {
console.log(data.count);
});
A few days ago, LinkedIn changed their API and the solutions above are broken :
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
fails because jQuery will replace the ? into a callback with a random name with numbers in it. And Linkedin now prevents using numbers in callback names.
The solution is to use to call "manually" $.ajax to prevent jQuery automation
$.ajax({
dataType: "jsonp",
url: 'https://www.linkedin.com/countserv/count/share',
data: {'url':encodeURIComponent(location.href)},
jsonpCallback: 'this_is_a_random_name',
success: function(data){
elem.find(".count").html(data.count);;
}
});
The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.
I have this JavaScript code:
$('#selectionoptions').change(function() {
var courseId = $(this).val();
$.get('../php/lecturer_getcourse_info.php',
{ course_id: $(this).val() },
function(courseData) {
var description = courseData.description;
$("#coursecontent").html(description);
...
Assume I can also modify 'description' and save it back to the db. Now, on Firefox every time I refresh the page I see the correct description; but on IE I have to clear the cache before I see the correct description....
How can I fix this?
The reason being in IE you have to false the Ajax Calls not to cache.
Use this:
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
or use a completely different ajax call rather than $.get such as:
$.ajax({
url: "test.html",
success: function(data){
alert('data returned!');
},
cache: false
});
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