Getting 404 response becaues ajaxSetup adds timestamp to GET parameters - javascript

I have used $.ajaxSetup({ cache: false });
to stop caching of file in browser but it appends timestamp in along with GET request and now I'm getting 404-file not found response from server when requesting file using $.getJSON() because of this parameter after file url >?=1413455027207
>>>i.e. "http://test.com/objListObjlist.json?=1413455027207 "
Anybody have any solution how can i handle this parameter in GET request??
and yes I'm using HTML,Javascript only :)

Adding query string doeas not change the file requested by client. It is just for sending additional data to the server. Make sure you are able to get the file without query string.
Note: Appending additional unique query parameter(normally current date-time stamp) is cross-platform recommended approach for cache killing.
Refer the below Mozilla Dev link
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache

Related

Storing JSON data in jQuery cookie after successful AJAX call

I am trying to store JSON data I am retrieving via AJAX in a jQuery cookie. I am using the following plugin: https://github.com/carhartl/jquery-cookie to achieve this. The plugin works great when I am storing non JSON objects.
I can see it is working perfectly when storing simple strings. However, when I try to store my JSON data that I get from my AJAX call, the cookie is not saving. Here is my relevant code:
$.ajax({
dataType: "json",
url: "http://www.example.com/sandbox/BF/context/messagesNew.php",
success: function(data) {
//This works
$.cookie('Name', 'John');
console.log($.cookie('Name'));
//This does not work
$.cookie("test-data", JSON.stringify(data));
var myJSONCookie = JSON.parse($.cookie("test-data"));
console.log(myJSONCookie); // Returns error in console: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
}
});
I have tried several other snippets of code but none have worked properly. I do not even think that test-data is being created as a cookie because when I logged the entire $.cookie(); to the console, my cookie called Name appears but test-data does not.
The value you are trying to put in your cookie is way too large for a cookie. Cookies are limited to around 4k. Part of this is for storage management and part of this is because every request to a server sends all the cookies with it. If you stored a 9MB cookie, you'd be sending an extra 9MB with every single page or ajax request to that server which would obviously be a disaster.
LocalStorage is another option that has larger storage limits, is still partitioned per domain and does not have the issue with sending large things to the server on every request.
If LocalStorage is not large enough also, then you can start considering only modern browsers that contain something like IndexedDB which you can read about here.
You probably need a different design approach. We could probably help with ideas for a different approach, but would have to understand the overall problem you're trying to solve and why you need to store 9MB locally and cannot just retrieve it from the server when needed in the future?

Reading contents of an iframe with wikipedia source? [duplicate]

I am trying to implement a simple request to Wikipedia's API using AJAX (XMLHttpRequest). If I type the url in the address bar of Firefox, I get a neat XML, no sweat there. Yet, calling the exact same url with:
// this is my XMLHttpRequest object
httpObjectMain.open("GET", "http://en.wikipedia.org/w/api.php?action=query&format=xml&prop=langlinks&lllimit=500&titles=kaas", true);
httpObjectMain.send(null);
returns an empty response. According to FireBug, I get a 200 OK response, but the content is just empty.
I suspect I might be missing something on the header of the GET http request.
Help! (and thanks!)
The Wikipedia API does support JSONP.
Your query string'll become something like this:
http://en.wikipedia.org/w/api.php?action=query&format=json&callback=test&prop=langlinks&lllimit=500&titles=kaas
But you'll have to build the jsonp handler (or you can use your favorite library to do it), switch to json output format from the xml you choose and create the callback function to parse the result and do the stuff you need on the page.
The browser will not allow you to send an XHR to another domain other than the one the page is on. This is for security purposes.
One way around this that I have seen is to setup a proxy on the domain the page is hosted on that will pass requests through to the actual api server. See http://ajaxpatterns.org/Cross-Domain_Proxy

Problem with getJSON response

I have some problem with $.getJSON response in Chrome
The query is
$.getJSON("http://www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json?callback=?&points=55.77184,37.623553",
function(json){
<some code>
}
);
if you click on this link you'll get an json text.
By when I run this query Chrome shows an error:
Resource interpreted as Script but transferred with MIME type application/json
SyntaxError: Unexpected token : timezone.json:1
Does it try to convert json response to JavaScript object? If it is so why it cann't do that? Is there any way of resolving this problem?
in Chrome debugger I found the file "timezone.json" with this content:
{"code":0,"message":"ok","data":[{"timeZone":"Europe/Moscow","currentOffsetMs":14400000,"latitude":55.77184,"longitude":37.623553}]}
The server you are requesting data from is not setup to return JSONP. therefore, you need to build some kind of proxy to get the data for you, or use YQL.
Edit:
If you were to use YQL, this is the url you would use:
http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A%2F%2Fwww.askgeo.com%2Fapi%2F428014%2Fsf2t36ujv1tsf325t5734gstr4%2Ftimezone.json%3Fpoints%3D55.77184%2C37.623553%22&format=json&diagnostics=true
and for information on how I generated that url, visit:
http://developer.yahoo.com/yql/console/#h=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A//www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json%3Fpoints%3D55.77184%2C37.623553%22
You can find the url at the bottom.
Fiddle using YQL: http://jsfiddle.net/JGwU3/1/
there is however one quirk with using YQL. if the result only contains one result, it's contents is an object, however, if it is multiple, its contents will be an array. you can see the difference by console.logging the response.
In the API documentation it says, that you should provide the query paramaters in a separate JSON object as the second argument.
$.getJSON('http://www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json', {'callback':'', 'points': '55.77184,37.623553'}, function(json) {
alert(json.data[0].timeZone);
});
Works fine when I tested it.
(This is totally ignoring JSONP)
EDIT
OK, my post was wrong, it is a JSONP issue. See this jQuery documentation page on how to retrieve the data from the URL:
http://api.jquery.com/jQuery.ajax/

Using the HTTP Accept Header from JavaScript

I have a web service that performs a database search. It accepts both GET and POST requests, and can return data in either JSON, CSV, or HTML format based on the HTTP Accept header.
I have a web page that makes an Ajax request to this web service, and displays the search results.
I have been asked to add a button to this page that will allow the user to save the data in CSV format.
Earlier this year, someone was in the same boat, and got the response
You cannot do it using javascript
capabilities, since javascript has no
permission to write on client machine,
instead you can send request to server
to create csv file and send it back to
client.
So I added a button that does
window.open("MyWebService.cgi?" + theSameQueryStringIPassedInTheAjaxCall),
which opens the HTML version in a new browser tab. I want the CSV version. Is there a way I could pass an Accept: text/csv HTTP header? (I know how to do it with XMLHttpRequest and setRequestHeader, but that doesn't help me.)
Don't think so. I think you should use an parameter instead.

Modifying the HTTP headers client-side with JavaScript

Is it possible to use JavaScript to dynamically change the HTTP Headers received when loading an image from an external source? I'm trying to control the caching of the image (Expires, Max-Age, etc...) client-side since I do not have access to the server.
As the others have said, no, it is not possibly to manipulate http headers and caching directives from the server in client code.
What is possible
What you do have the ability to do is ensure you get a new file. This can be done by appending a unique string to the URL of the request as a query string parameter.
e.g. if you wanted to ensure you got a new file each hour
<script type="text/javascript">
var d = new Date();
url += ("?" +d.getYear() + "_" + d.getDay() + "_" + d.getHours());
</script>
What this does is add a value containing the year, day and hour to the url, so it will be unique for each hour, hence ensuring a new file request. (Not tested!)
Obviously this can be made much more generic and fine tuned, but hopefully you'll get the idea.
What is impossible
What you can't do is ensure you will not retrieve a new version from the server.
Caching directives are in the server's responsibility. You can't manipulate them on the client side.
Maybe it's an option for you to install a proxy server, e.g. if you are aiming at company employees?
I do not think Javascript can actually do that : the images are requested by the browser, and it's up to him to define HTTP-headers to issue.
One way to use some custom headers would be with some kind of Ajax-request, not passing by any <img> tag ; but you'd have to know what to do with the returned data... Don't think it would help much.
If you want your images to be kept in cache by the browser, you server has to send the right headers in the responses (like Etag, and/or Expires -- see mod_expires, for Apache, for instance)
If you want to be absolutly sure the browser will download a new image, and not use the version it has in cache, you should use a different URL each time.
This is often done using the timestamp as a parameter to the URL ; like example.com/image.jpg?123456789 (123456789 being, more or less, the current timestamp -- obviously less than more, but you get the idea : each second, the browser will see the URL has changed)
EDIT after the edit of the question :
The Expires header is generated by the server, and is one of the headers that come in the Response (it's not a header the client sends in the Request ; see List of HTTP headers).
So, you absolutly have no control over it from the client-side : it's the server that must be configured to do the work, here...
If you want more answers : what are you trying to do exactly ? Why ?

Categories