Most votes on ajax questions 9

Most votes on ajax questions 9. #81 How do I catch an Ajax query post error? #82 Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses? #83 event.returnValue is deprecated. Please use the standard event.preventDefault() instead #84 Stop all active ajax requests in jQuery #85 How to generate a simple popup using jQuery #86 Request Monitoring in Chrome #87 Why use AJAX when WebSockets is available? #88 How can I remove or replace SVG content? #89 Pass array to ajax request in $.ajax() #90 Cache an HTTP 'Get' service response in AngularJS?

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

#81: How do I catch an Ajax query post error? (Score: 224)

Created: 2010-05-14 Last updated: 2017-07-22

Tags: jquery, ajax, post, error-handling

I would like to catch the error and show the appropriate message if the Ajax request fails.

My code is like the following, but I could not manage to catch the failing Ajax request.

function getAjaxData(id)
     $.post("status.ajax.php", {deviceId : id}, function(data){

        var tab1;

        if (data.length>0) {
            tab1 = data;
        else {
            tab1 = "Error in Ajax";

        return tab1;

I found out that, “Error in Ajax” is never executed when the Ajax request failed.

How do I handle the Ajax error and show the appropriate message if it fails?

#81 Best answer 1 of How do I catch an Ajax query post error? (Score: 327)

Created: 2010-05-14 Last updated: 2017-07-22

Since jQuery 1.5 you can use the deferred objects mechanism:

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling

Another way is using .ajax:

  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");

#81 Best answer 2 of How do I catch an Ajax query post error?(Score: 296)

Created: 2012-08-24 Last updated: 2012-12-05

jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you’d like after the call. Deferred objects even allow you to attach multiple success and error handlers.


$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {

Prior to jQuery 1.8, the function done was called success and fail was called error.

See also original question in stackoverflow

#82: Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses? (Score: 223)

Created: 2010-06-30 Last updated: 2017-08-04

Tags: javascript, ajax, security, json

Possible Duplicate:
Why does Google prepend while(1); to their JSON responses?

Google returns json like this:

throw 1; <dont be evil> { foo: bar}

and Facebooks ajax has json like this:

for(;;); {"error":0,"errorSummary": ""}
  • Why do they put code that would stop execution and makes invalid json?
  • How do they parse it if it’s invalid and would crash if you tried to eval it?
  • Do they just remove it from the string (seems expensive)?
  • Are there any security advantages to this?

In response to it being for security purposes:

If the scraper is on another domain they would have to use a script tag to get the data because XHR won’t work cross-domain. Even without the for(;;); how would the attacker get the data? It’s not assigned to a variable so wouldn’t it just be garbage collected because there’s no references to it?

Basically to get the data cross domain they would have to do

<script src=""></script>

But even without the crash script prepended the attacker can’t use any of the Json data without it being assigned to a variable that you can access globally (it isn’t in these cases). The crash code effectivly does nothing because even without it they have to use server sided scripting to use the data on their site.

#82 Best answer 1 of Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses? (Score: 193)

Created: 2010-06-30 Last updated: 2010-06-30

Even without the for(;;); how would the attacker get the data?

Attacks are based on altering the behaviour of the built-in types, in particular Object and Array, by altering their constructor function or its prototype. Then when the targeted JSON uses a {...} or [...] construct, they’ll be the attacker’s own versions of those objects, with potentially-unexpected behaviour.

For example, you can hack a setter-property into Object, that would betray the values written in object literals:

Object.prototype.__defineSetter__('x', function(x) {
    alert('Ha! I steal '+x);

Then when a <script> was pointed at some JSON that used that property name:

{"x": "hello"}

the value "hello" would be leaked.

The way that array and object literals cause setters to be called is controversial. Firefox removed the behaviour in version 3.5, in response to publicised attacks on high-profile web sites. However at the time of writing Safari (4) and Chrome (5) are still vulnerable to this.

Another attack that all browsers now disallow was to redefine constructor functions:

Array= function() {
    alert('I steal '+this);

[1, 2, 3]

And for now, IE8’s implementation of properties (based on the ECMAScript Fifth Edition standard and Object.defineProperty) currently does not work on Object.prototype or Array.prototype.

But as well as protecting past browsers, it may be that extensions to JavaScript cause more potential leaks of a similar kind in future, and in that case chaff should protect against those too.

#82 Best answer 2 of Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses?(Score: 61)

Created: 2010-07-17

Consider that, after checking your GMail account, that you go visit my evil page:

<script type="text/javascript">
Object = function() {
<script type="text/javascript" src=""></script>

What will happen now is that the Javascript code that comes from Google – which the asker thought would be benign and immediately fall out of scope – will actually be posted to my evil site. Suppose that the URL requested in the script tag sends (because your browser will present the proper cookie, Google will correctly think that you are logged in to your inbox):

  messages: [
      id: 1,
      subject: 'Super confidential information',
      message: 'Please keep this to yourself: the password is 42'
      id: 2,
      subject: 'Who stole your password?',
      message: 'Someone knows your password! I told you to keep this information to yourself! And by this information I mean: the password is 42'

Now, I will be posting a serialized version of this object to my evil server. Thank you!

The way to prevent this from happening is to cruft up your JSON responses, and decruft them when you, from the same domain, can manipulate that data. If you like this answer, please accept the one posted by bobince.

See also original question in stackoverflow

#83: event.returnValue is deprecated. Please use the standard event.preventDefault() instead (Score: 222)

Created: 2013-11-18 Last updated: 2013-12-23

Tags: javascript, jquery, ajax

I have this script:

$(document).ready(function () {
    $("#changeResumeStatus").click(function () {
        $.get("{% url 'main:changeResumeStatus' %}", function (data) {
            if (data['message'] == 'hidden') {
            } else {
        }, "json");

I receive the following error in my Google Chrome console:

event.returnValue is deprecated. Please use the standard event.preventDefault() instead.

I am using jQuery v1.10.2 and #changeResumeStatus is a <span>.

What’s wrong with my script?

#83 Best answer 1 of event.returnValue is deprecated. Please use the standard event.preventDefault() instead (Score: 204)

Created: 2013-11-18 Last updated: 2015-12-09

This is only a warning: your code still works, but probably won’t work in the future as the method is deprecated. See the relevant source of Chromium and corresponding patch.

This has already been recognised and fixed in jQuery 1.11 (see here and here).

#83 Best answer 2 of event.returnValue is deprecated. Please use the standard event.preventDefault() instead(Score: 22)

Created: 2013-11-19 Last updated: 2014-01-14

Just for other’s reference, I just received this and found it was due to AngularJS. It’s for backwards compatibility:

if (!event.preventDefault) {
    event.preventDefault = function() {
        event.returnValue = false; //ie

See also original question in stackoverflow

#84: Stop all active ajax requests in jQuery (Score: 220)

Created: 2009-11-26

Tags: jquery, ajax

I have a problem, when submitting a form all active ajax request fail, and that triggers error event.

How to stop all active ajax requests in jQuery without trigerring error event?

#84 Best answer 1 of Stop all active ajax requests in jQuery (Score: 276)

Created: 2009-11-26

Every time you create an ajax request you could use a variable to store it:

var request = $.ajax({
    type: 'POST',
    url: 'someurl',
    success: function(result){}

Then you can abort the request:


You could use an array keeping track of all pending ajax requests and abort them if necessary.

#84 Best answer 2 of Stop all active ajax requests in jQuery(Score: 180)

Created: 2012-01-12 Last updated: 2014-10-23

The following snippet allows you to maintain a list (pool) of request and abort them all if needed. Best to place in the <HEAD> of your html, before any other AJAX calls are made.

<script type="text/javascript">
	$(function() {
        $.xhrPool = [];
        $.xhrPool.abortAll = function() {
            $(this).each(function(i, jqXHR) {	//	cycle through list of recorded connection
                jqXHR.abort();	//	aborts connection
                $.xhrPool.splice(i, 1);	//	removes from list by index
            beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); },	//	annd connection to list
            complete: function(jqXHR) {
                var i = $.xhrPool.indexOf(jqXHR);	//	get index for current connection completed
                if (i > -1) $.xhrPool.splice(i, 1);	//	removes from list by index

See also original question in stackoverflow

#85: How to generate a simple popup using jQuery (Score: 218)

Created: 2009-08-25 Last updated: 2017-08-03

Tags: javascript, jquery, css, ajax, popup

I am designing a web page. When we click the content of div named mail, how can I show a popup window containing a label email and text box?

#85 Best answer 1 of How to generate a simple popup using jQuery (Score: 244)

Created: 2009-08-25 Last updated: 2018-07-26

First the CSS - tweak this however you like:

a.selected {

.messagepop {
  border:1px solid #999999;
  margin-top: 15px;
  padding: 25px 25px 20px;

label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  text-indent: -15px;

.messagepop p, .messagepop.div {
  border-bottom: 1px solid #EFEFEF;
  margin: 8px 0;
  padding-bottom: 8px;

And the JavaScript:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {

$(function() {
  $('#contact').on('click', function() {
    if($(this).hasClass('selected')) {
    } else {
    return false;

  $('.close').on('click', function() {
    return false;

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);

And finally the html:

<div class="messagepop pop">
  <form method="post" id="new_message" action="/messages">
    <p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
    <p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
    <p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>

<a href="/contact" id="contact">Contact Us</a>

Here is a jsfiddle demo and implementation.

Depending on the situation you may want to load the popup content via an ajax call. It’s best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you’ll want to make if you take this approach.

HTML becomes:

    <div class="messagepop pop"></div> 
    <a href="/contact" id="contact">Contact Us</a>

And the general idea of the JavaScript becomes:

$("#contact").on('click', function() {
    if($(this).hasClass("selected")) {
    } else {
        $.get(this.href, function(data) {
            $(".pop").html(data).slideFadeToggle(function() { 
    return false;

#85 Best answer 2 of How to generate a simple popup using jQuery(Score: 99)

Created: 2009-08-25

Check out jQuery UI Dialog. You would use it like this:

The jQuery:

$(document).ready(function() {

The markup:

<div id="dialog" title="Dialog Title">I'm in a dialog</div>


Bear in mind that’s about the simplest use-case there is, I would suggest reading the documentation to get a better idea of just what can be done with it.

See also original question in stackoverflow

#86: Request Monitoring in Chrome (Score: 215)

Created: 2009-11-30 Last updated: 2009-11-30

Tags: ajax, google-chrome, httprequest

In Firefox, I use Firebug which allows me to view every http request my ajax calls are making. I’ve switched over my development to Chrome and am liking it so far. My only complaint, however, is that the developer tools don’t seem to allow you to view each ajax request. I’ve had it happen once where the Resources panel showed multiple requests to the same resource, but it’s only done it once and never again.

Is there a way to reliably see every http request that a page is making through javascript from within Chrome?

[Edit:11/30/09 11:55]

Currently, to get around this, I’m running Fiddler next to Chrome to view my requests, but if there’s a way to do it from within the browser, I’d prefer that.

#86 Best answer 1 of Request Monitoring in Chrome (Score: 367)

Created: 2010-06-10 Last updated: 2016-03-23

I know this is an old thread but I thought I would chime in.

Chrome currently has a solution built in.

  1. Use CTRL+SHIFT+I (or navigate to Current Page Control > Developer > Developer Tools. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools.
  2. From within the developer tools click on the Network button. If it isn’t already, enable it for the session or always.
  3. Click the "XHR" sub-button.
  4. Initiate an AJAX call.
  5. You will see items begin to show up in the left column under "Resources".
  6. Click the resource and there are 2 tabs showing the headers and return content.

#86 Best answer 2 of Request Monitoring in Chrome(Score: 57)

Created: 2011-03-03

The most up-to-date answer to this is: they are listed under the ‘Network’ button in the developer tools, no longer under ‘Resources’ like it used to be.

See also original question in stackoverflow

#87: Why use AJAX when WebSockets is available? (Score: 215)

Created: 2012-04-30 Last updated: 2015-11-08

Tags: ajax, node.js, performance, websocket

I’ve been using WebSockets for a while now, I have chosen to create an Agile project management tool for my final year project at University utilizing Node server and WebSockets. I found using WebSockets provided a 624% increase in the number of requests per second my application could process.

However since starting the project I’ve read of security loopholes, and some browsers choosing to disable WebSockets by default..

This leads me to the question:

Why use AJAX when WebSockets seems to do such a great job of lowering latency and resource overhead, is there anything that AJAX does better than WebSockets?

#87 Best answer 1 of Why use AJAX when WebSockets is available? (Score: 218)

Created: 2012-04-30 Last updated: 2012-11-08

WebSockets isn’t intended to replace AJAX and is not strictly even a replacement for Comet/long-poll (although there are many cases where this makes sense).

The purpose of WebSockets is to provide a low-latency, bi-directional, full-duplex and long-running connection between a browser and server. WebSockets opens up new application domains to browser applications that were not really possible using HTTP and AJAX (interactive games, dynamic media streams, bridging to existing network protocols, etc).

However, there is certainly an overlap in purpose between WebSockets and AJAX/Comet. For example, when the browser wants to be notified of server events (i.e. push) then Comet techniques and WebSockets are certainly both viable options. If your application needs low-latency push events then this would be a factor in favor of WebSockets. On the other hand, if you need to co-exist with existing frameworks and deployed technologies (OAuth, RESTful APIs, proxies, load balancers) then this would be a factor in favor of Comet techniques (for now).

If you don’t need the specific benefits that WebSockets provides, then it’s probably a better idea to stick with existing techniques like AJAX and Comet because this allows you to re-use and integrate with a huge existing ecosystem of tools, technologies, security mechanisms, knowledge bases (i.e. far more people on stackoverflow know HTTP/Ajax/Comet than WebSockets), etc.

On the other hand, if you are creating a new application that just doesn’t work well within the latency and connection constraints of HTTP/Ajax/Comet, then consider using WebSockets.

Also, some answers indicate that one of the downsides of WebSockets is limited/mixed server and browser support. Let me just diffuse that a bit. While iOS (iPhone, iPad) still supports the older protocol (Hixie) most WebSockets servers support both Hixie and the HyBi/IETF 6455 version. Most other platforms (if they don’t already have built-in support) can get WebSockets support via web-socket-js (Flash based polyfill). This covers the vast majority of web users. Also, if you are using Node for the server backend, then consider using Socket.IO which includes web-socket-js as a fallback and if even that is not available (or disabled) then it will fall back to using whatever Comet technique is available for the given browser.

Update: iOS 6 now supports the current HyBi/IETF 6455 standard.

#87 Best answer 2 of Why use AJAX when WebSockets is available?(Score: 75)

Created: 2017-12-22 Last updated: 2017-12-28

Fast forward to December 2017, Websockets are supported by (practically) every browser and their use is very common.

However, this does not mean that Websockets managed to replace AJAX, at least not completely, especially as HTTP/2 adaptation is on the rise.

The short answer is that AJAX is still great for most REST applications, even when using Websockets. But god is in the details, so…:

AJAX for polling?

The use of AJAX for polling (or long polling) is dying out (and it should be), but it still remains in use for two good reasons (mainly for smaller web apps):

  1. For many developers, AJAX is easier to code, especially when it comes to coding and designing the backend.

  2. With HTTP/2, the highest cost related to AJAX (the establishment of a new connection) was eliminated, allowing AJAX calls to be quite performant, especially for posting and uploading data.

However, Websocket push is far superior to AJAX (no need to re-authenticate or resend headers, no need for “no data” roundtrips, etc'). This was discussed a number of times.


A better use for AJAX is REST API calls. This use simplifies the code base and prevents the Websocket connection from blocking (especially on medium sized data uploads).

There are a number of compelling reasons to prefer AJAX for REST API calls and data uploads:

  1. The AJAX API was practically designed for REST API calls and it’s a great fit.

  2. REST calls and uploads using AJAX are significantly easier to code, both on the client and the backend.

  3. As data payload increases, Websocket connections might get blocked unless message fragmentation / multiplexing logic is coded.

    If an upload is performed in a single Websocket send call, it could block a Websocket stream until the upload had finished. This will reduce performance, especially on slower clients.

A common design uses small bidi messages transferred over Websockets while REST and data uploads (client to server) leverage AJAX’s ease of use to prevent the Websocket from blocking.

However, on larger projects, the flexibility offered by Websockets and the balance between code complexity and resource management will tip the balance in favor of Websockets.

For example, Websocket based uploads could offer the ability to resume large uploads after a connection is dropped and re-established (remember that 5GB movie you wanted to upload?).

By coding upload fragmentation logic, it’s easy to resume an interrupted upload (the hard part was coding the thing).

What about HTTP/2 push?

I should probably add that the HTTP/2 push feature doesn’t (and probably can’t) replace Websockets.

This had been discussed here before, but suffice to mention that a single HTTP/2 connection serves the whole browser (all the tabs/windows), so data being pushed by HTTP/2 doesn’t know which tab/window it belongs to, eliminating it’s capacity to replace Websocket’s ability to push data directly to a specific browser tab / window.

While Websockets are great for small bi-directional data communication, AJAX still carried a number of advantages - especially when considering larger payloads (uploads etc').

And Security?

Well, generally, the more trust and control is offered to a programmer, the more powerful the tool… and the more security concerns that creep up.

AJAX by nature would have the upper hand, since it’s security is built in to the browser’s code (which is sometimes questionable, but it’s still there).

On the other hand, AJAX calls are more susceptible to “man in the middle” attacks, while Websockets security issues are usually bugs in the application code that introduced a security flaw (usually backend authentication logic is where you’ll find these).

Personally I don’t find this to be that big of a difference, if anything I think Websockets are slightly better off, especially when you know what you’re doing.

My Humble Opinion

IMHO, I would use Websockets for everything but REST API calls. Big data uploads I would fragment and send over Websockets when possible.

Polling, IMHO, should be outlawed, the cost in network traffic is horrid and Websocket push is easy enough to manage even for new developers.

See also original question in stackoverflow

#88: How can I remove or replace SVG content? (Score: 214)

Created: 2012-05-28 Last updated: 2014-10-21

Tags: javascript, ajax, svg, d3.js

I have a piece of JavaScript code which creates (using D3.js) an svg element which contains a chart. I want to update the chart based on new data coming from a web service using AJAX, the problem is that each time I click on the update button, it generates a new svg, so I want to remove the old one or update its content.

Here is a snippet from the JavaScript function where I create the svg:

var svg ="body")
        .attr("width", w)
        .attr("height", h);

How can I remove the old svg element or at least replace its content?

#88 Best answer 1 of How can I remove or replace SVG content? (Score: 300)

Created: 2012-06-06 Last updated: 2015-10-14

Here is the solution:"svg").remove();

This is a remove function provided by D3.js.

#88 Best answer 2 of How can I remove or replace SVG content?(Score: 162)

Created: 2014-06-16 Last updated: 2020-11-02

If you want to get rid of all children,


will remove all content associated with the svg.

See also original question in stackoverflow

#89: Pass array to ajax request in $.ajax() (Score: 213)

Created: 2012-01-17 Last updated: 2017-05-23

Tags: jquery, ajax, arrays, json

I want to send an array as an Ajax request:

info[0] = 'hi';
info[1] = 'hello';

  type: "POST",
  url: "index.php",
  success: function(msg){

How can I do this?

#89 Best answer 1 of Pass array to ajax request in $.ajax() (Score: 270)

Created: 2012-01-17

info = [];
info[0] = 'hi';
info[1] = 'hello';

   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){

#89 Best answer 2 of Pass array to ajax request in $.ajax()(Score: 72)

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

Just use the JSON.stringify method and pass it through as the “data” parameter for the $.ajax function, like follows:

    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){

You just need to make sure you include the JSON2.js file in your page…

See also original question in stackoverflow

#90: Cache an HTTP 'Get' service response in AngularJS? (Score: 211)

Created: 2013-01-02 Last updated: 2018-12-14

Tags: angularjs, ajax, caching, http-get

I want to be able to create a custom AngularJS service that makes an HTTP ‘Get’ request when its data object is empty and populates the data object on success.

The next time a call is made to this service, I would like to bypass the overhead of making the HTTP request again and instead return the cached data object.

Is this possible?

#90 Best answer 1 of Cache an HTTP 'Get' service response in AngularJS? (Score: 315)

Created: 2013-01-02 Last updated: 2017-03-19

Angular’s $http has a cache built in. According to the docs:

cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.

#Boolean value#

So you can set cache to true in its options:

$http.get(url, { cache: true}).success(...);

or, if you prefer the config type of call:

$http({ cache: true, url: url, method: 'GET'}).success(...);

#Cache Object# You can also use a cache factory:

var cache = $cacheFactory('myCache');

$http.get(url, { cache: cache })

You can implement it yourself using $cacheFactory (especially handly when using $resource):

var cache = $cacheFactory('myCache');

var data = cache.get(someKey);

if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(someKey, data);

#90 Best answer 2 of Cache an HTTP 'Get' service response in AngularJS?(Score: 48)

Created: 2013-08-06

I think there’s an even easier way now. This enables basic caching for all $http requests (which $resource inherits):

 var app = angular.module('myApp',[])
      .config(['$httpProvider', function ($httpProvider) {
            // enable http caching
           $httpProvider.defaults.cache = true;

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.