Most votes on ajax questions 6

Most votes on ajax questions 6. #51 In what situations would AJAX long/short polling be preferred over HTML5 WebSockets? #52 Why is it a bad practice to return generated HTML instead of JSON? Or is it? #53 TypeError: $.ajax(…) is not a function? #54 How do I integrate Ajax with Django applications? #55 Can an AJAX response set a cookie? #56 How to save an HTML5 Canvas as an image on a server? #57 How to pass parameters in GET requests with jQuery #58 Detect the Internet connection is offline? #59 Prevent browser caching of AJAX call result #60 PHP "php://input" vs $_POST

Read all the top votes questions and answers in a single page.

#51: In what situations would AJAX long/short polling be preferred over HTML5 WebSockets? (Score: 312)

Created: 2012-04-05 Last updated: 2016-06-03

Tags: javascript, ajax, html, websocket, network-protocols

I am building a small chat application for friends, but unsure about how to get information in a timely manner that is not as manual or as rudimentary as forcing a page refresh.

Currently, I am implementing this using simple AJAX, but this has the disadvantage of regularly hitting the server when a short timer elapses.

In researching long/short polling, I ran across HTML5 WebSockets. This seems easy to implement, but I’m not sure if there are some hidden disadvantages. For example, I think WebSockets is only supported by certain browsers. Are there other disadvantages to WebSockets that I should be aware of?

Since it seems like both technologies do the same thing, in what sorts of scenarios would one prefer to use one over the other? More specifically, has HTML5 WebSockets made AJAX long/short polling obsolete, or are there compelling reasons to prefer AJAX over WebSockets?

#51 Best answer 1 of In what situations would AJAX long/short polling be preferred over HTML5 WebSockets? (Score: 518)

Created: 2012-04-05 Last updated: 2021-03-30

WebSockets is definitely the future now.

Long polling is a dirty workaround to prevent creating connections for each request like AJAX does - but long polling was created when WebSockets didn’t exist. Now due to WebSockets, long polling is going away no more.

WebRTC allows for peer-to-peer communication.

I recommend learning WebSockets.


of different communication techniques on the web

  • AJAX - requestresponse. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.

  • Long poll - requestwaitresponse. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic. support chart (full) | wikipedia

  • WebSockets - clientserver. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted. support chart (very good) | wikipedia

  • WebRTC - peerpeer. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to “link” peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required. support chart (medium) | wikipedia

  • Server-Sent Events - clientserver. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia


The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don’t need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.

Security considerations

People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it’s connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).


Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.

#51 Best answer 2 of In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?(Score: 13)

Created: 2013-08-27 Last updated: 2017-05-23

One contending technology you’ve omitted is Server-Sent Events / Event Source. has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.

See also original question in stackoverflow

#52: Why is it a bad practice to return generated HTML instead of JSON? Or is it? (Score: 303)

Created: 2009-08-16

Tags: javascript, jquery, html, ajax, json

It is quite easy to load HTML content from your custom URLs/Web services using JQuery or any other similar framework. I’ve used this approach many times and till now and found the performance satisfactory.

But all the books, all the experts are trying to get me to use JSON instead of generated HTML. How’s it much more superior than HTML?

Is it very much faster?
Does it have a very much lesser load on the server?

On the other side I have some reasons for using generated HTML.

  1. It’s simple markup, and often just as compact or actually more compact than JSON.
  2. It’s less error prone cause all you’re getting is markup, and no code.
  3. It will be faster to program in most cases cause you won’t have to write code separately for the client end.

Which side are you on and why?

#52 Best answer 1 of Why is it a bad practice to return generated HTML instead of JSON? Or is it? (Score: 258)

Created: 2009-08-16 Last updated: 2009-08-16

I’m a bit on both sides, actually :

  • When what I need on the javascript side is data, I use JSON
  • When what I need on the javascript side is presentation on which I will not do any calculation, I generally use HTML

The main advantage of using HTML is when you want to replace a full portion of your page with what comes back from the Ajax request :

  • Re-building a portion of page in JS is (quite) hard
  • You probably already have some templating engine on the server side, that was used to generate the page in the first place… Why not reuse it ?

I generally don’t really take into consideration the “performance” side of things, at least on the server :

  • On the server, generating a portion of HTML or some JSON won’t probably make that much of a difference
  • About the size of the stuff that goes through the network : well, you probably don’t use hundreds of KB of data/html… Using gzip on whatever you are transferring is what’s going to make the biggest difference (not choosing between HTML and JSON)
  • One thing that could be taken into consideration, though, is what resources you’ll need on the client to recreate the HTML (or the DOM structure) from the JSON data… compare that to pushing a portion of HTML into the page ;-)

Finally, one thing that definitly matters :

  • How long will it take you to develop a new system that will send data as JSON + code the JS required to inject it as HTML into the page ?
  • How long will it take to just return HTML ? And how long if you can re-use some of your already existing server-side code ?

And to answer another answer : if you need to update more than one portion of the page, there is still the solution/hack of sending all those parts inside one big string that groups several HTML portions, and extract the relevant parts in JS.

For instance, you could return some string that looks like this :

here goes the html
code for part 1
here goes the html
code for part 2
here goes the json data
that will be used to build part 3
from the JS code

That doesn’t look really good, but it’s definitly useful (I’ve used it quite a couple of times, mostly when the HTML data were too big to be encapsulated into JSON) : you are sending HTML for the portions of the page that need presentation, and you are sending JSON for the situation you need data…

… And to extract those, the JS substring method will do the trick, I suppose ;-)

#52 Best answer 2 of Why is it a bad practice to return generated HTML instead of JSON? Or is it?(Score: 117)

Created: 2009-08-16

I mainly agree with the opinions stated here. I just wanted to summarize them as:

  • It is bad practice to send HTML if you end up parsing it client-side to do some calculations over it.

  • It is bad practice to send JSON if all you’ll end up doing is to incorporate it into the page’s DOM tree.

See also original question in stackoverflow

#53: TypeError: $.ajax(…) is not a function? (Score: 292)

Created: 2013-08-16 Last updated: 2018-09-24

Tags: jquery, ajax, json

I’m trying to create a simple AJAX request which returns some data from a MySQL database. Here’s my function below:

function AJAXrequest(url, postedData, callback) {
	$.ajax() ({
        type: 'POST',
        url: url,
        data: postedData,
        dataType: 'json',
        success: callback

…and here’s where I call it, parsing in the required parameters:

AJAXrequest('voting.ajax.php', imageData, function(data) {

Yet, my success callback does not run (as “success!” is not logged to the console), and I get an error in my console:

TypeError: $.ajax(...) is not a function.
success: callback

What does this mean? I’ve done AJAX requests before where the success event triggers an anonymous function inside of $.ajax, but now I’m trying to run a separate named function (in this case, a callback). How do I go about this?

#53 Best answer 1 of TypeError: $.ajax(…) is not a function? (Score: 1161)

Created: 2016-11-21 Last updated: 2016-11-26

Neither of the answers here helped me. The problem was: I was using the slim build of jQuery, which had some things removed, ajax being one of them.

The solution: Just download the regular (compressed or not) version of jQuery here and include it in your project.

#53 Best answer 2 of TypeError: $.ajax(…) is not a function?(Score: 146)

Created: 2017-09-12

Double-check if you’re using full-version of jquery and not some slim version.

I was using the jquery cdn-script link that comes with jquery. The problem is this one by default is slim.jquery.js which doesn’t have the ajax function in it. So, if you’re using (copy-pasted from Bootstrap website) slim version jquery script link, use the full version instead.

That is to say use <script src=""> instead of <script src=""

See also original question in stackoverflow

#54: How do I integrate Ajax with Django applications? (Score: 283)

Created: 2013-11-30 Last updated: 2013-12-01

Tags: python, ajax, django

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together.

Could someone give me a quick explanation of how the codebase must change with the two of them integrating together?

For example, can I still use the HttpResponse with Ajax, or do my responses have to change with the use of Ajax? If so, could you please provide an example of how the responses to the requests must change? If it makes any difference, the data I am returning is JSON.

#54 Best answer 1 of How do I integrate Ajax with Django applications? (Score: 671)

Created: 2013-12-01 Last updated: 2019-04-21

Even though this isn’t entirely in the SO spirit, I love this question, because I had the same trouble when I started, so I’ll give you a quick guide. Obviously you don’t understand the principles behind them (don’t take it as an offense, but if you did you wouldn’t be asking).

Django is server-side. It means, say a client goes to a URL, you have a function inside views that renders what he sees and returns a response in HTML. Let’s break it up into examples:

def hello(request):
    return HttpResponse('Hello World!')

def home(request):
    return render_to_response('index.html', {'variable': 'world'})


<h1>Hello {{ variable }}, welcome to my awesome site</h1>

url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),

That’s an example of the simplest of usages. Going to means a request to the hello() function, going to will return the index.html and replace all the variables as asked (you probably know all this by now).

Now let’s talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some URL, you get the same data you would get as a user going to that place.

For example, an AJAX call to will return the same thing it would as if you visited it. Only this time, you have it inside a JavaScript function and you can deal with it however you’d like. Let’s look at a simple use case:

    url: '',
    type: 'get', // This is the default though, you don't actually need to always mention it
    success: function(data) {
    failure: function(data) { 
        alert('Got an error dude');

The general process is this:

  1. The call goes to the URL as if you opened a new tab and did it yourself.
  2. If it succeeds (status code 200), do the function for success, which will alert the data received.
  3. If fails, do a different function.

Now what would happen here? You would get an alert with ‘hello world’ in it. What happens if you do an AJAX call to home? Same thing, you’ll get an alert stating <h1>Hello world, welcome to my awesome site</h1>.

In other words - there’s nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:

  1. Learn jQuery. I cannot stress this enough. You’re gonna have to understand it a little to know how to handle the data you receive. You’ll also need to understand some basic JavaScript syntax (not far from python, you’ll get used to it). I strongly recommend Envato’s video tutorials for jQuery, they are great and will put you on the right path.
  2. When to use JSON?. You’re going to see a lot of examples where the data sent by the Django views is in JSON. I didn’t go into detail on that, because it isn’t important how to do it (there are plenty of explanations abound) and a lot more important when. And the answer to that is - JSON data is serialized data. That is, data you can manipulate. Like I mentioned, an AJAX call will fetch the response as if the user did it himself. Now say you don’t want to mess with all the html, and instead want to send data (a list of objects perhaps). JSON is good for this, because it sends it as an object (JSON data looks like a python dictionary), and then you can iterate over it or do something else that removes the need to sift through useless html.
  3. Add it last. When you build a web app and want to implement AJAX - do yourself a favor. First, build the entire app completely devoid of any AJAX. See that everything is working. Then, and only then, start writing the AJAX calls. That’s a good process that helps you learn a lot as well.
  4. Use chrome’s developer tools. Since AJAX calls are done in the background it’s sometimes very hard to debug them. You should use the chrome developer tools (or similar tools such as firebug) and console.log things to debug. I won’t explain in detail, just google around and find out about it. It would be very helpful to you.
  5. CSRF awareness. Finally, remember that post requests in Django require the csrf_token. With AJAX calls, a lot of times you’d like to send data without refreshing the page. You’ll probably face some trouble before you’d finally remember that - wait, you forgot to send the csrf_token. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it’s easy as pie.

That’s everything that comes to my head. It’s a vast subject, but yeah, there’s probably not enough examples out there. Just work your way there, slowly, you’ll get it eventually.

#54 Best answer 2 of How do I integrate Ajax with Django applications?(Score: 24)

Created: 2015-02-05 Last updated: 2018-02-03

Further from yuvi’s excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses AjaxableResponseMixin and assumes an Author model.

import json

from django.http import HttpResponse
from django.views.generic.edit import CreateView
from myapp.models import Author

class AjaxableResponseMixin(object):
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
            return self.render_to_json_response(data)
            return response

class AuthorCreate(AjaxableResponseMixin, CreateView):
    model = Author
    fields = ['name']

Source: Django documentation, Form handling with class-based views

The link to version 1.6 of Django is no longer available updated to version 1.11

See also original question in stackoverflow

Created: 2010-07-27 Last updated: 2012-02-08

Tags: ajax, cookies

Can an AJAX response set a cookie? If not, what is my alternative solution? Should I set it with Javascript or something similar?

Created: 2010-07-27 Last updated: 2016-01-06

According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.


If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.

#55 Best answer 2 of Can an AJAX response set a cookie?(Score: 262)

Created: 2010-07-27

Yes, you can set cookie in the AJAX request in the server-side code just as you’d do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

See also original question in stackoverflow

#56: How to save an HTML5 Canvas as an image on a server? (Score: 281)

Created: 2012-11-02 Last updated: 2017-08-10

Tags: javascript, php, ajax, html5-canvas

I’m working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:

  • Create an image on an HTML5 Canvas using a generative algorithm
  • When the image is completed, allow users to save the canvas as an image file to the server
  • Allow the user to either download the image or add it to a gallery of pieces of produced using the algorithm.

However, I’m stuck on the second step. After some help from Google, I found this blog post, which seemed to be exactly what I wanted:

Which led to the JavaScript code:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var ajax = new XMLHttpRequest();"POST", "testSave.php", false);
  ajax.onreadystatechange = function() {
  ajax.setRequestHeader("Content-Type", "application/upload");
  ajax.send("imgData=" + canvasData);

and corresponding PHP (testSave.php):

if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
  $imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
  $filteredData = substr($imageData, strpos($imageData, ",") + 1);
  $unencodedData = base64_decode($filteredData);
  $fp = fopen('/path/to/file.png', 'wb');

  fwrite($fp, $unencodedData);

But this doesn’t seem to do anything at all.

More Googling turns up this blog post which is based off of the previous tutorial. Not very different, but perhaps worth a try:

$data = $_POST['imgData'];
$file = "/path/to/file.png";
$uri = substr($data,strpos($data, ",") + 1);

file_put_contents($file, base64_decode($uri));
echo $file;

This one creates a file (yay) but it’s corrupted and doesn’t seem to contain anything. It also appears to be empty (file size of 0).

Is there anything really obvious that I’m doing wrong? The path where I’m storing my file is writable, so that isn’t an issue, but nothing seems to be happening and I’m not really sure how to debug this.


Following Salvidor Dali’s link I changed the AJAX request to be:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var xmlHttpReq = false;
  if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
  else if (window.ActiveXObject) {
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
  }"POST", "testSave.php", false);
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajax.onreadystatechange = function() {
  ajax.send("imgData=" + canvasData);

And now the image file is created and isn’t empty! It seems as if the content type matters and that changing it to x-www-form-urlencoded allowed the image data to be sent.

The console returns the (rather large) string of base64 code and the datafile is ~140 kB. However, I still can’t open it and it seems to not be formatted as an image.

#56 Best answer 1 of How to save an HTML5 Canvas as an image on a server? (Score: 257)

Created: 2012-11-02 Last updated: 2020-09-20

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)
<canvas id="myCanvas" width="578" height="200"></canvas>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.strokeStyle = 'blue';
  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
    }).done(function(o) {
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

#56 Best answer 2 of How to save an HTML5 Canvas as an image on a server?(Score: 72)

Created: 2012-11-02 Last updated: 2015-07-13

I played with this two weeks ago, it’s very simple. The only problem is that all the tutorials just talk about saving the image locally. This is how I did it:

  1. I set up a form so I can use a POST method.

  2. When the user is done drawing, he can click the “Save” button.

  3. When the button is clicked I take the image data and put it into a hidden field. After that I submit the form.

    document.getElementById(‘my_hidden’).value = canvas.toDataURL(‘image/png’); document.forms[“form1”].submit();

  4. When the form is submited I have this small php script:

See also original question in stackoverflow

#57: How to pass parameters in GET requests with jQuery (Score: 281)

Created: 2013-03-22 Last updated: 2017-05-23

Tags: javascript, jquery, ajax, get

How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I’m sure there is a cleaner way that does not require me to encode manually.

	url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
	success: function(response) {
        //Do Something
	error: function(xhr) {
        //Do Something to handle error

I’ve seen examples where query string parameters are passed as an array but these examples I’ve seen don’t use the $.ajax() model, instead they go straight to $.get(). For example:

$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );

I prefer to use the $.ajax() format as it’s what I’m used to (no particularly good reason - just a personal preference).

Edit 09/04/2013:

After my question was closed (as “Too Localised”) i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):

This answered my question perfectly, I found that doing it this way is much easier to read & I don’t need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen’s answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:

    url: "ajax.aspx?ajaxid=4",
    data: { 
        "VarA": VarA, 
        "VarB": VarB, 
        "VarC": VarC
    cache: false,
    type: "POST",
    success: function(response) {

    error: function(xhr) {


#57 Best answer 1 of How to pass parameters in GET requests with jQuery (Score: 337)

Created: 2013-03-22 Last updated: 2018-10-17

Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method

Try this

  url: "ajax.aspx",
  type: "get", //send it through get method
  data: { 
    ajaxid: 4, 
    UserID: UserID, 
    EmailAddress: EmailAddress
  success: function(response) {
    //Do Something
  error: function(xhr) {
    //Do Something to handle error

And you can get the data by (if you are using PHP)

 $_GET['ajaxid'] //gives 4
 $_GET['UserID'] //gives you the sent userid

In aspx, I believe it is (might be wrong)


#57 Best answer 2 of How to pass parameters in GET requests with jQuery(Score: 22)

Created: 2013-03-22 Last updated: 2015-07-08

Put your params in the data part of the ajax call. See the docs. Like so:

    url: "/TestPage.aspx",
    data: {"first": "Manu","Last":"Sharma"},
    success: function(response) {
        //Do Something
    error: function(xhr) {
        //Do Something to handle error

See also original question in stackoverflow

#58: Detect the Internet connection is offline? (Score: 279)

Created: 2008-10-09 Last updated: 2019-05-25

Tags: javascript, ajax, offline, connectivity, internet-connection

How to detect the Internet connection is offline in JavaScript?

#58 Best answer 1 of Detect the Internet connection is offline? (Score: 142)

Created: 2008-10-09 Last updated: 2019-01-09

You can determine that the connection is lost by making failed XHR requests.

The standard approach is to retry the request a few times. If it doesn’t go through, alert the user to check the connection, and fail gracefully.

Sidenote: To put the entire application in an “offline” state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.

Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you’re still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.

Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we’d have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won’t be able to get to the server, and if the connection problem is only on our own domain, we won’t be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what’s going on. So again, determining the state of the internet connection as a whole may be more trouble than it’s worth. You’ll have to weight these options out for your specific app.

#58 Best answer 2 of Detect the Internet connection is offline?(Score: 95)

Created: 2018-12-17 Last updated: 2021-04-16

Almost all major browsers now support the window.navigator.onLine property, and the corresponding online and offline window events. Run the following code snippet to test it:

console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');

window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));

document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
<button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
Check the console below for results:

Try setting your system or browser in offline/online mode and check the log or the window.navigator.onLine property for the value changes.

Note however this quote from Mozilla Documentation:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always “connected.” Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.

(emphasis is my own)

This means that if window.navigator.onLine is false (or you get an offline event), you are guaranteed to have no Internet connection.

If it is true however (or you get an online event), it only means the system is connected to some network, at best. It does not mean that you have Internet access for example. To check that, you will still need to use one of the solutions described in the other answers.

I initially intended to post this as an update to Grant Wagner’s answer, but it seemed too much of an edit, especially considering that the 2014 update was already not from him.

See also original question in stackoverflow

#59: Prevent browser caching of AJAX call result (Score: 276)

Created: 2008-12-15 Last updated: 2020-03-16

Tags: javascript, jquery, ajax, browser-cache

It looks like if I load dynamic content using $.get(), the result is cached in browser.

Adding some random string in QueryString seems to solve this issue (I use new Date().toString()), but this feels like a hack.

Is there any other way to achieve this? Or, if unique string is the only way to achieve this, any suggestions other than new Date()?

#59 Best answer 1 of Prevent browser caching of AJAX call result (Score: 530)

Created: 2009-04-09 Last updated: 2012-07-06

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });

#59 Best answer 2 of Prevent browser caching of AJAX call result(Score: 342)

Created: 2009-04-09

JQuery’s $.get() will cache the results. Instead of

$.get("myurl", myCallback)

you should use $.ajax, which will allow you to turn caching off:

$.ajax({url: "myurl", success: myCallback, cache: false});

See also original question in stackoverflow

#60: PHP "php://input" vs $_POST (Score: 275)

Created: 2012-01-17 Last updated: 2014-07-24

Tags: php, ajax, input

I have been directed to use the method php://input instead of $_POST when interacting with Ajax requests from JQuery. What I do not understand is the benefits of using this vs the global method of $_POST or $_GET.

#60 Best answer 1 of PHP "php://input" vs $_POST (Score: 536)

Created: 2012-01-17 Last updated: 2019-11-19

The reason is that php://input returns all the raw data after the HTTP-headers of the request, regardless of the content type.

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data (mostly used for file uploads)

This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don’t expect to receive any other content type (which doesn’t mean they couldn’t).

So, if you simply POST a good old HTML form, the request looks something like this:

POST /page.php HTTP/1.1


But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:

POST /page.php HTTP/1.1


The content would now be application/json (or at least none of the above mentioned), so PHP’s $_POST-wrapper doesn’t know how to handle that (yet).

The data is still there, you just can’t access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it’s not multipart/form-data-encoded).

This is also how you would access XML-data or any other non-standard content type.

#60 Best answer 2 of PHP "php://input" vs $_POST(Score: 57)

Created: 2012-01-17 Last updated: 2012-01-17

php://input can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.

Here’s a function to do just that:

   * Returns the JSON encoded POST data, if any, as an object.
   * @return Object|null
  private function retrieveJsonPostData()
    // get the raw POST data
    $rawData = file_get_contents("php://input");

    // this returns null if not valid json
    return json_decode($rawData);

The $_POST array is more useful when you’re handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded (see for details).

See also original question in stackoverflow

  1. This page use API to get the relevant data from stackoverflow community.
  2. Content license on this page is CC BY-SA 3.0.
  3. score = up votes - down votes.