Best ajax questions in December 2010

Why does POST not honor charset, but an AJAX request does? tomcat 6.

12 votes

I have a tomcat based application that needs to submit a form capable of handling utf-8 characters. When submitted via ajax, the data is returned correctly from getParameter() in utf-8. When submitting via form post, the data is returned from getParameter() in iso-8859-1.

I used fiddler, and have determined the only difference in the requests, is that charset=utf-8 is appended to the end of the Content-Type header in the ajax call (as expected, since I send the content type explicitly).

ContentType from ajax: "application/x-www-form-urlencoded; charset=utf-8"

ContentType from form: "application/x-www-form-urlencoded"

I have the following settings:

ajax post (outputs chars correctly):

$.ajax( {
  type : "POST",
  url : "blah",
  async : false,
  contentType: "application/x-www-form-urlencoded; charset=utf-8",
  data  : data,
  success : function(data) { 
  }
 });

form post (outputs chars in iso)

 <form id="leadform" enctype="application/x-www-form-urlencoded; charset=utf-8" method="post" accept-charset="utf-8" action="{//app/path}">

xml declaration:

<?xml version="1.0" encoding="utf-8"?>

Doctype:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

meta tag:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

jvm parameters:

-Dfile.encoding=UTF-8

I have also tried using request.setCharacterEncoding("UTF-8"); but it seems as if tomcat simply ignores it. I am not using the RequestDumper valve.

From what I've read, POST data encoding is mostly dependent on the page encoding where the form is. As far as I can tell, my page is correctly encoded in utf-8.

The sample JSP from this page works correctly. It simply uses setCharacterEncoding("UTF-8"); and echos the data you post. http://wiki.apache.org/tomcat/FAQ/CharacterEncoding

So to summarize, the post request does not send the charset as being utf-8, despite the page being in utf-8, the form parameters specifying utf-8, the xml declaration or anything else. I have spent the better part of three days on this and am running out of ideas. Can anyone help me?

form post (outputs chars in iso)

<form id="leadform" enctype="application/x-www-form-urlencoded; charset=utf-8" method="post" accept-charset="utf-8" action="{//app/path}">

You don't need to specify the charset there. The browser will use the charset which is specified in HTTP response header.

Just

<form id="leadform" method="post" action="{//app/path}">

is enough.


xml declaration:

<?xml version="1.0" encoding="utf-8"?>

Irrelevant. It's only relevant for XML parsers. Webbrowsers doesn't parse text/html as XML. This is only relevant for the server side (if you're using a XML based view technology like Facelets or JSPX, on plain JSP this is superfluous).


Doctype:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Irrelevant. It's only relevant for HTML parsers. Besides, it doesn't specify any charset. Instead, the one in the HTTP response header will be used. If you aren't using a XML based view technology like Facelets or JSPX, this can be as good <!DOCTYPE html>.


meta tag:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Irrelevant. It's only relevant when the HTML page is been viewed from local disk or is to be parsed locally. Instead, the one in the HTTP response header will be used.


jvm parameters:

-Dfile.encoding=UTF-8

Irrelevant. It's only relevant to Sun/Oracle(!) JVM to parse the source files.


I have also tried using request.setCharacterEncoding("UTF-8"); but it seems as if tomcat simply ignores it. I am not using the RequestDumper valve.

This will only work when the request body is not been parsed yet (i.e. you haven't called getParameter() and so on beforehand). You need to call this as early as possible. A Filter is a perfect place for this. Otherwise it will be ignored.


From what I've read, POST data encoding is mostly dependent on the page encoding where the form is. As far as I can tell, my page is correctly encoded in utf-8.

It's dependent on the HTTP response header.

All you need to do are the following three things:

  1. Add the following to top of your JSP:

    <%@page pageEncoding="UTF-8" %>
    

    This will set the response encoding to UTF-8 and set the response header to UTF-8.

  2. Create a Filter which does the following in doFilter() method:

    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
    }
    chain.doFilter(request, response);
    

    This will make that the POST request body will be processed as UTF-8.

  3. Change the <Connector> entry in Tomcat/conf/server.xml as follows:

    <Connector (...) URIEncoding="UTF-8" />
    

    This will make that the GET query strings will be processed as UTF-8.

See also:

Is Silverlight a good alternative to AJAX?

10 votes

Hi,

Microsoft seems to propose 2 alternative options for building Web 2.0 business sites:

  • A thin client architecture consisting of ASP.NET (Weforms or MVC) on the server side and javascript on the client side

  • A fat client architecture consisting of a business layer exposed via RIA Services on the server and Silverlight on the client side.

I'm currently using the thin client approach and while the server side is always rock-solid, the client side tends to break much more easily because of

  • Javascript problems which can only be detected at runtime
  • CSS problems
  • Frail, but complex client / server interaction
  • Much less testability

Most of this wouldn't be an issue with a Silverlight client.

So, the more complex the client side gets, the more it seems to make sense to use a fat client model. However, all sites I know are using the thin client approach.

What I'd like to know:

  • Is Silverlight really a good alternative to javascript and CSS on the client side, especially for business websites?

  • Are there any examples of successful web 2.0 business websites built with Silverlight on the client-side? Microsoft's showcase is full of half-baked apps none of which really seems to have ever reached professional-grade quality. I'm looking for something that has a similar style to StackOverflow or the sites from 37 Signals.

Thanks,

Adrian

Edit: Obviously one of the disadvantages of Silverlight is that users have to download the Silverlight plugin. In my case this is less of an issue, since it takes a few minutes to setup your account anyway, so could you please ignore this aspect when providing an answer.

Edit 2: The first and foremost reason I wrote this post is that I have yet to see a really nice looking Silverlight business app.

Everything I have seen so far looks a bit outdated and in desperate need of polish compared to web sites like StackOverflow or the ones at 37 Signals. Most consist of carelessly arranged windows and scrollbars gallore. I am wondering if a clean and concise Web 2.0 look is so hard to achieve with Silverlight or if nobody actually tries to achieve it.

Actual post by one of my friends on facebook: "FireFox 4 beta 7 rocks..!!!!"

I thought - ugh, do my many sites need to be updated? Will they break with this? Do I check it now or after the beta?

A little Googling later I see Chrome's latest release was a few days ago (December 2nd), with over 800 improvements (that's gotta break something.)

IE9 is in beta with a "revamped JavaScript engine aimed at performance", isn't Ajax all about complicated JavaScript?

So my Ajax's hacks might just work great on all of my sites with all of these browsers.... but I doubt it. And either way, I have to check all of them with all of the new browsers.

I've decided that I'm going to get off of this endless treadmill.

Silverlight isolates you from the different browsers so you have just 1 new environment to test your code on with each new release of Silverlight.

I also see Microsoft is pushing Silverlight down to the clients every chance they get (updates, etc.) So I don't worry about the plug-in issue.

So I'm looking forward to committing to Silverlight for all of my new business applications in a big way.

Delphi serverside framework for managing sessions and respond with JSON to ajax requests?

10 votes

Without reinventing the wheel, what I can use to manage user sessions in a web application and being able to respond with JSON to ajax requests?

Is there some framework (made for example with Indy components or something like this)?

Note for bounty:

in practice it is enough for me to have a reply with a clear example of a server application that serves json. Somehow a Delphi example of the php example mentioned HERE. (without the DB part, I want to see the basics of what does it mean to send JSON. I have basic knowledge of TIdHTTPServer.)

Maybe this can help you:

REST Servers in Delphi XE Using DataSnap Whitepaper

Learn how to build REST servers using features available in Delphi XE, how to extend them with extra Delphi support code and how to take advantage of the jQuery library.

Marco Cantù

http://app.en25.com/e/er.aspx?s=608&lid=4414&elq=d428643420d2494581299418d9753feb

Why would multiple simultaneous AJAX calls to the same ASP.NET MVC action cause the browser to block?

9 votes

A few days back I asked this question:

Why does $.getJSON() block the browser?

I fire six jQuery async ajax requests at the same controller action pretty much all at once. Each request takes 10 seconds to return.

Through debugging and logging requests to the action method I notice that the requests are serialised and never run in parallel. i.e. I see a timeline in my log4net logs like this:

2010-12-13 13:25:06,633 [11164] INFO   - Got:1156
2010-12-13 13:25:16,634 [11164] INFO   - Returning:1156
2010-12-13 13:25:16,770 [7124] INFO   - Got:1426
2010-12-13 13:25:26,772 [7124] INFO   - Returning:1426
2010-12-13 13:25:26,925 [11164] INFO   - Got:1912
2010-12-13 13:25:36,926 [11164] INFO   - Returning:1912
2010-12-13 13:25:37,096 [9812] INFO   - Got:1913
2010-12-13 13:25:47,098 [9812] INFO   - Returning:1913
2010-12-13 13:25:47,283 [7124] INFO   - Got:2002
2010-12-13 13:25:57,285 [7124] INFO   - Returning:2002
2010-12-13 13:25:57,424 [11164] INFO   - Got:1308
2010-12-13 13:26:07,425 [11164] INFO   - Returning:1308

Looking at the network timeline in FireFox I see this:

alt text

Both the log sample above and the Firefox network timeline are for the same set of requests.

Are requests to the same action from the same page serialised? I'm aware of serialised access to the Session object in the same session, but no session data is being touched.

I stripped the client side code down to a single request (the longest running one) but this still blocks the browser, i.e. only when the ajax request completes does the browser respond to any link clicking.

What I also observe here (in Chrome's developer tools) is that upon clicking on a link when a long running ajax request is executing it reports a Failed to load resource error immediately which suggests that the browser has killed (or is attempting to kill and waiting?) the ajax request:

alt text

However the browser still takes an age to redirect to the new page.

Are ajax requests really asynchronous or is this sleight of hand because javascript is actually single threaded?

Are my requests just taking too long for this to work?

The problem occurs in Firefox and IE as well.

I also changed the script to use $.ajax directly and explicitly set async: true.

I'm running this on IIS7.5, both the Windows 2008R2 and Windows 7 flavours do the same thing.

Debug and release builds also behave the same.

The answer was staring me in the face.

ASP.NET Session State Overview

*Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished.

Annoyingly I'd skimmed paragraph this a couple of weeks ago not really taking in the full impact of the bold sentences. I had read that simply as "access to session state is serialised" and not "all requests, no matter whether you touch session state or not, are serialised" if the requests came from the same session.

Fortunately there is a work around in ASP.NET MVC3 and its possible to create session-less controllers. Scott Guthrie talks about these here:

Announcing ASP.NET MVC 3 (Release Candidate 2)

I installed MVC3 RC2 and upgraded the project. Decorating the controller in question with [SessionState(SessionStateBehavior.Disabled)] solves the problem.

And of course typically I just found this in Stack Overflow a few minutes ago:

Asynchronous Controller is blocking requests in ASP.NET MVC through jQuery

Replace current page with ajax content

6 votes

Hello, I have a page with a dialog window which sends ajax post data to server and receives a response. During development, there can be two responses - one regular (this is not the question) or one with an error. Server returns code 500 and a page with lot of debug informations. This is a regular page returned from a framework and contains some javascript code. I want to be able to display this error page in case it happens.

The problem is, I can not simply attach the returned result to body element or open a new link in a new page and load this error again. I simply get a html page instead of data and I have to display the page (in current window or in another one).

I am using jQuery.

Thanks for any suggestions!

Configure jQuery ajax setup as follows:

$.ajaxSetup({
    error: handleXhrError
});

where handleXhrError function look like this:

function handleXhrError(xhr) {
    document.open();
    document.write(xhr.responseText);
    document.close();
}

See also:

What is a good book or resource for writing large ajax applications?

6 votes

I am very experienced in engineering large-scale systems, but I am still relatively new to ajax-based design. I know how to use the apis, and I am fairly comfortable using jquery and javascript as a whole, but I often find myself thinking way too hard about the overall architecture.

Right now, my current application just has javascript files sprinkled all over the place, all in a /js directory. Most of them use jQuery, but some use YUI or a combination between the two because the features weren't available in jQuery.

Some of my REST server methods accept normal GET methods with request parameters, but others needed much more complex POSTs to handle the incoming data (lists of lists of objects). The handling of all of my ajax stuff is a mix and mash of different methods as a result of the complexity of the data I'm dealing with.

What I'd really like is to read about how to design an ajax-based system that is very clean and elegant architecturally, and is consistent from the simplest to the most complex of cases. Does such a resource exist?

Also suggestions on naming conventions of javascript files and conventions for ajax endpoint directory/method names?

Also how to do with entering form data? Should you use get or post to do this?

Also about validation of form data when all the constraints are already on the server? How to make this very trivial to do so you're not doing it for each form?

What are the best ways to generate new page content when people click things and settings this up so that it's easy to do over and over.

How to deal with application-specific javascript files depending on each other and managing this nicely.

I am also using Spring and Spring-MVC, but I don't expect this to make much difference. My questions are purely browser related.

There's a TL;DR summary at the end.

I can't really point you to a good resource for this as I haven't found one myself. However, all is not lost. You already have experience in developing large-scale applications and taking this knowledge into the browser-space doesn't require a lot of re-thinking.

First of all, unless your application is really trivial, I wouldn't start refactoring the entire codebase straight away because there are bound to be endless cases you haven't thought of yet.

Design the core architecture of the system you want first. In your case you probably want all your AJAX requests to go through one point. Select the XHR interface from either jQuery or YUI and write a wrapper around it that takes an option hash. All the XHR calls you write for new code go through there. This allows you to switch out the framework performing the XHR calls at any time with another framework or your own.

Next up, harmonize the wire protocol. I'd recommend using JSON and POST requests (POST requests have the additional benefit for FORM submissions of not being cached). Make a list of the different types of request/responses you need. For each of these responses, make a JS object to encapsulate them. (E.g. the form submission response is returned to the caller as a FormReponse object which has accessor functions for the validation errors, etc). The JS overhead for this is totally trivial and makes it easy to change the JSON protocol itself without going through your widget code to change the access of the raw JSON.

If you're dealing with a lot of forms, make sure they all have the same structure so you can use a JS object to serialize them. Most frameworks seem to have various native functions to do this, but I'd recommend rolling your own so you don't have to deal with shortcomings.

The added business value at this point is of course zero because all you have is the start of a sane way of doing things and even more JS code to load into your app.

If you have new code to write, write it on the APIs you've just implemented. That's a good way to see if you're not doing anything really stupid. Keep the other JS as it is for now but once you have to fix a bug or add a feature there, refactor that code to use your new APIs. Over time you'll find that the important code is all running on your APIs and a lot of the other stuff will slowly become obsolete.

Don't go overboard with re-inventing the wheel, though. Keep this new structure limited to data interaction and the HTTP wire and use your primary JS framework for handling anything related to the DOM, browser quirks, etc.

Also set up a global logger object and don't use console directly. Have your logger object use console or a custom DOM logger or whatever you need in different environments. That makes it easy to build in custom log levels, log filters, etc. Obviously you have to set up your build environment to scrub that code out for production builds (you do have a build process for this, right?)

My personal favorite for relatively sane JS source-code layout and namespacing is the Dojo framework. Object definitions relative to their namespace have obvious relations to their location on disk, there's a build system in place for custom builds, third-party modules, etc. The Dojo dependency/build system depends on dojo.require and dojo.provide statements in the code. When running on source a dojo.require statement will trigger the blocking load of the resource in question. For production the build system follows these statements and inserts the resource into the final bundle at that location. The documentation is a bit sparse, but it's definitely a good start for inspiration.

The TL;DR answer is,

  • Have all XHR calls go through a single interface
  • Don't pass raw response data back to higher levels
  • Do gradual refactoring of existing code
  • Harmonize the wire protocol
  • Use the dynamic power of JS for building light-weight proxy code
  • Sane code structure and call graphs look the same in JS as they do in other languages

Does a Javascript process have multiple threads of execution?

5 votes

Background

I am creating an 'addressbook'-type application. There are a lot of entries to load. One idea was to initially load a small subset of the entries, to get the user started, then queue up the remaining entries, giving priority to the entries that the user clicks on. (e.g. if they click on the names that start with X, load those first before processing the rest of the queue). The idea is to load an initial dataset upon initialization (via AJAX) and then load the rest in the background (making a lot of AJAX calls).

My many questions

Conceptually, I know how to do this, but I'm not clear on the limitations of the Javascript engine:

  1. Is order of execution browser dependent? One of the things I tried to do was queue up the set of entries (A's, B's, C's, etc) and then make a whole bunch of requests all at once. This wasn't very successful. I got most of the calls back, but not in any particular order. I need all of my calls back. :)

  2. How do I debug this/track this? I'm not sure how Javascript handles the response; it was easy enough for a single response, but I'm not sure how to handle multiple, relatively large responses from the server.

  3. Is there a single thread of execution for a given page? That is, if the Javascript gets a response from the server but is still executing code, does the transaction block until the currently executing code finishes?

  4. Would it be recommended to put in a delay between requests? This could also cause problems because the loading up and sending of the request (as of now) is in the initialization phase; if I have to sleep() between requests, then I might as well just force the user to wait for the all the data to load without trying to do this gradual loading.

I looked around on SO but I didn't find anything useful. I'm curious about how JS process these asynchronous requests/responses.

What I've done so far

Just to give folks a better idea of what's happening, here's what I'm doing in order of execution. There are 5 hard-coded search categories: first names, last names, classes, regions, states. Each of these categories have ranges. For example the first names category might have 26 ranges, one for each letter of the alphabet: "Aardvark - Azariah" would be an example of a range. Each range has the user information for each user in that range. I have two tables: a ranges table and a users table.

  1. Initialize range table and range data source objects. Map range table object to specific events.
  2. AJAX call to get all the ranges for each category. We wait for this before continuing.
  3. Initialize users table similarly to range table.
  4. Build a load queue to get all the users for each range. The load queue looks like this: [ lastNames['S'], states['CA'], regions['northwest'], lastNames['A'], etc]
  5. Preselect a the first names category, the 'A' first names range and the zeroeth user in that range. (This is just an arbitrary choice I made to give the user a starting point)
  6. AJAX call to get all the users for firstName['A']. Remove the firstNames['A'] range from the load queue.
  7. Populate the appropriate UI elements
  8. Loop through our load queue, dequeuing ranges and constructing AJAX requests for the data.

There are a lot of other details too... but this is the basic gist of it.

What happens is that my range table gets populated fine... but then the browser just blocks up (spod) and then my users table gets all sorts of crazy data being populated in it. Clearly the latter is a UI bug on my part so I have to investigate that, but it's not clear to me that this is the best way to do this.

At step 7, I'm not sure if there should be a delay between requests. Ideally, if a user chose a specific range, say states['AK'], we would process that request first, dq'ing that range from our load queue. But if I'm sending all the requests on the front end, then we'd never get a chance to give our chosen range the appropriate priority.

Javascript is completely single-threaded.

If you make multiple AJAX calls, you will receive each response as soon as the server sends it; the order depends on the amount of time that it takes the server to send each reply.

If your code is still running when the server replies, the reply will only be processed after your code finishes.

You should try to load all of the data in a single request.

AJAX calls to untrusted HTTPS fail silently

5 votes

I want to make AJAX calls to a secure server that uses a self-signed certificate. In the environment where my app is being used, this is fine -- I can provide the CA cert to users and have them install it before using the app. However, sometimes, a user tries to visit the app before installing the certs. In these cases, the app silently fails -- at least in Firefox (most common case of the problem), it appears that the call silently dies, without even firing off the error handler. FWIW, if the user visits an actual page on the server, they get a cert warning.

I could hack in a workaround -- say, make a heartbeat/ping request and set up a watchdog timer to see if the server responds in time -- but that seems, well, hacky. I'd prefer to be able to test the connection ahead of time. What's the "right" way to make sure the server you want to talk to has a trusted cert from within Javascript? If it makes any difference, I'm doing my AJAX requests via JQuery.

UPDATE: There's an awesome punchline here. Turns out, AJAX was not the problem at all. I was sure based on the symptoms that it was related to the self-signed certs, but the lack of AJAX error was disturbing, esp. given the spec linked to in the answer below. Another team member nailed it: the AJAX error handlers weren't firing off because JQuery was never loaded! We were including JQuery from another subdomain of our site, also hosted on HTTPS -- and users had added exceptions for ourService.example.com but not js.example.com. Apparently if you point a <script> tag at non-trusted secure connection, that fails silently as well.

{/headdesk}

XMLHttpRequests (AJAX requests) are only permitted on same-origin servers. That means the scheme://host:port part of the target URL has to match that of the current document. According to the spec, you shouldn't even be allowed to make a request on the SSL URL from the non-SSL one.

The less hackish solution that I see is that you just force-redirect all users to the SSL site. That way they will be forced to see the certificate warning before any AJAX request can be made.

Note: The spec also says that in case of TLS handshake failure (which I assume this case falls under, in a way) it should throw a NETWORK_ERR (code 19) exception. You could try to catch the exception when initiating the AJAX request. Refer to the spec on error handling for more details.

Why does $.getJSON() block the browser?

4 votes

I have a page where I list hardware devices we monitor for customers. Each row displayed also shows the status of the device i.e. whether it's running, paused, starting up etc.

To improve page load times I list the devices but don't query for their status until the page is rendered. This is because some queries such as via SNMP or other API's can take as much as 5-10 seconds to respond. So for a list of say ten devices it could take well over a minute of the user looking at a blank page. So I do the following instead -

On the device list page I have the following script:

$(document).ready(function () {

  var devices = $('div[name="runStatus"]');
  devices.each(function () {

    // Get device ID (I embed this using the HTML5 data-* attributes/annotations)
    var deviceId = $(this).attr("data-deviceid");
    var url = "/devmanager/status/" + deviceId;

    $.getJSON(url, function (response) {
      // Not actually important to the question...set text status, colours etc
      $('div[data-deviceid="' + deviceId + '"]').text(response);
      //...
    });
  });
});

What I'm finding is that if I allow this script to run, all links on the page become unresponsive.

I'm guessing this is because I've quite a few almost parallel async requests blocking until they get a response from the server and somehow the "UI thread" is being blocked by this?

However I thought this wasn't supposed to happen with AJAX.

I find this 'blocking' behaviour to happen in IE8, Chrome 8.0 and Firefox 3.6. Chrome in fact shows the arrow cursor + spinning-toilet-bowl-of-death (I'm using Windows 7) as if the page isn't completely rendered.

How can I fix this?

Turns out this isn't a problem with the client side:

Would multiple calls to the same ASP.NET MVC action cause the browser to block?

Would multiple calls to the same ASP.NET MVC action cause the browser to block? - Answer

This was being caused by a "by-design" feature of ASP.NET where multiple requests made in the same session are serialised.

jQuery $.ajaxError() runs on 200 - OK

4 votes

I have a global ajax error handler that runs even though the xhr.status is 200, xhr.statusText is "OK" and xhr.responseText is my JSON string. This happens in firefox and IE.

$.ajax({
    data: {
        method: "getRequestDetails",
        loggedInUsername: loggedInUsername,
        search: search
    },
    success: function(data){
        var arrayObject = eval("(" + data + ")")['DATA'];
        if (arrayObject.length == 0){
            alert("That search term returned no results");
        } else {
            callBeforeShow("Results");
            $.each(arrayObject, function(index, value){
                showJSON(value, "Results");
            });
            callAfterShow("Results");
        }
    }
});

$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError){
    var errorMessage = "Ajax Error\n";
    errorMessage += "Type: " + ajaxOptions.type + "\n";
    errorMessage += "Requesting Page: " + ajaxOptions.url + "\n";
    errorMessage += "Status: " + XMLHttpRequest.status + " - " + XMLHttpRequest.statusText + "\n";
    errorMessage += "Error Thrown: " + thrownError
    alert(errorMessage);
});

In IE this says that the XMLHttpRequest is not ready and in Firefox this returns

"AJAX Error" "Type: POST" "Requesting Page: something.CFC" "Status: 200 - OK" "Error Thrown: undefined"

So my work around is to use

$(document).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions, errorThrown){
    if (XMLHttpRequest.status != 200){
        var errorMessage = "Ajax Error\n";
        errorMessage += "Type: " + ajaxOptions.type + "\n";
        errorMessage += "Requesting Page: " + ajaxOptions.url + "\n";
        errorMessage += "Status: " + XMLHttpRequest.status + " - " + XMLHttpRequest.statusText;
        alert(errorMessage);
    }
});

EDIT *This only happens on some occassions. Most of the time it works but sometimes it runs $.ajaxError()* EIDT

{"COLUMNS":["ID","SUMMARY_SPEC","TOTAL_EFFORT","EFFORT_HISTORY","LOG_HISTORY"],"DATA":[[816,"test only","2 Minutes - Last Updated: 09\/12\/2010",{"COLUMNS":["CC_ID","RECORD_ID","USER_ID","USER_NAME","EFFORT_DATE","EFFORT_DAYS","EFFORT_HRS","EFFORT_MINS","EFFORT_TOT_HRS"],"DATA":[[816,496,"ruhlet","Tim Ruhle","December, 09 2010 00:00:00",0,0,1,0.0167],[816,497,"ruhlet","Tim Ruhle","December, 08 2010 00:00:00",0,0,1,0.0167]]},{"COLUMNS":["CC_ID","RECORD_ID","USER_ID","USER_NAME","LOG_DT","LOG_ENTRY"],"DATA":[]}]]}{"COLUMNS":["ID","SUMMARY_SPEC","TOTAL_EFFORT","EFFORT_HISTORY","LOG_HISTORY"],"DATA":[[816,"test only","2 Minutes - Last Updated: 09\/12\/2010",{"COLUMNS":["CC_ID","RECORD_ID","USER_ID","USER_NAME","EFFORT_DATE","EFFORT_DAYS","EFFORT_HRS","EFFORT_MINS","EFFORT_TOT_HRS"],"DATA":[[816,496,"ruhlet","Tim Ruhle","December, 09 2010 00:00:00",0,0,1,0.0167],[816,497,"ruhlet","Tim Ruhle","December, 08 2010 00:00:00",0,0,1,0.0167]]},{"COLUMNS":["CC_ID","RECORD_ID","USER_ID","USER_NAME","LOG_DT","LOG_ENTRY"],"DATA":[]}]]}{"COLUMNS":["ID","SUMMARY_SPEC","TOTAL_EFFORT","EFFORT_HISTORY","LOG_HISTORY"],"DATA":[[816,"test only","2 Minutes - Last Updated: 09\/12\/2010",{"COLUMNS":["CC_ID","RECORD_ID","USER_ID","USER_NAME","EFFORT_DATE","EFFORT_DAYS","EFFORT_HRS","EFFORT_MINS","EFFORT_TOT_HRS"],"DATA":[[816,496,"ruhlet","Tim Ruhle","December, 09 2010 00:00:00",0,0,1,0.0167],[816,497,"ruhlet","Tim Ruhle","December, 08 2010 00:00:00",0,0,1,0.0167]]},{"COLUMNS":["CC_ID","RECORD_ID","USER_ID","USER_NAME","LOG_DT","LOG_ENTRY"],"DATA":[]}]]}

The latest version of firebug recognises it as json.

ah, well after days of searching i commented out different settings in $.ajaxSetup(). It ended up being that i had set a timeout. If only there was a better error message given. Thanks for all the help guys, would not have gotten here if not for you. You all get up votes!!!

Jquery form only working the first time you submit it, and not the second...

4 votes

I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the

$(document).ready(function(){

But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing. The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js

$(document).ready(function(){
$('#AddCaller').click(function(e){

    //stop the form from being submitted
    e.preventDefault();

    /* declare the variables, var error is the variable that we use on the end
    to determine if there was an error or not */
    var error = false;
    var Firstname = $('#Firstname').val();
    ...OTHER FORM FIELDS HERE

    /* in the next section we do the checking by using VARIABLE.length
    where VARIABLE is the variable we are checking (like name, email),
    length is a javascript function to get the number of characters.
    And as you can see if the num of characters is 0 we set the error
    variable to true and show the name_error div with the fadeIn effect. 
    if it's not 0 then we fadeOut the div( that's if the div is shown and
    the error is fixed it fadesOut. */


    if(Firstname.length == 0){
        var error = true;
        $('#Firstname_error').fadeIn(500);
    }else{
        $('#Firstname_error').fadeOut(500);
    }
    if(Lastname.length == 0){
        var error = true;
        $('#Lastname_error').fadeIn(500);
    }else{
        $('#Lastname_error').fadeOut(500);
    }
    ...MORE CONDITIONAL STATEMENTS HERE




    //now when the validation is done we check if the error variable is false (no errors)
    if(error == false){
        //disable the submit button to avoid spamming
        //and change the button text to Sending...
        $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

        /* using the jquery's post(ajax) function and a lifesaver
        function serialize() which gets all the data from the form
        we submit it to send_email.php */
        $.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
            //and after the ajax request ends we check the text returned
            if(result == 'added'){

                 //$('#cf_submit_p').remove();
                //and show the success div with fadeIn
                $('#Add_success').fadeIn(500);
                 $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
                 document.getElementById('Firstname').value = "";
                 document.getElementById('Lastname').value = "";
                 document.getElementById('PhoneNumber').value = "";
                 document.getElementById('DefaultETA').value = "";
                 document.getElementById('Apparatus').value = "";
                 document.getElementById('DefaultLocation').value = "";


                 setTimeout(" $('#Add_success').fadeOut(500);",5000);

            }else if(result == 'alreadythere'){
                                    //checks database to see if the user is already there
                $('#Alreadythere').fadeIn(500);
                $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
            }
            else{
                //show the failed div
                $('#Add_fail').fadeIn(500);
                //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                $('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');

            }
        });
    }
});    
});

Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.

Thanks for the help!

EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.

EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.

<form action='addcallers.php' method='post' id='AddCaller_form'>

 <h2>Add Callers</h2>
 <p>
 First Name:
 <div id='Firstname_error' class='error'> Please Enter a First Name</div>
 <div><input type='text' name='Firstname' id='Firstname'></div>
 </p>

 <p>
 Last Name:
 <div id='Lastname_error' class='error'> Please Enter a Last Name</div>
 <div><input type='text' name='Lastname' id='Lastname'></div>
 </p>
 ...MORE FORM FIELDS HERE


 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly >

 </div>
 </p>

 <p>




 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 <p id='cf_submit_p'>
 <input type='submit' id='AddCaller' value='Send The Message'>
 </p>
 </form>  

 </div>

EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.

EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it

EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?

most likely, it's the #DefaultLocation field, since it's a read only and you are resetting it after the first post:

document.getElementById('DefaultLocation').value = "";

And never changing it's value back to something (or are you?) so you have to do one of the following:

  1. don't reset it
  2. set it's value with something after posing the form
  3. don't validate it at all since it's a read only and you are using it as a hidden input (which is wrong by the way)!

also, it can be the other "ajax" code you are talking about so please post that too here, also maybe you have other fields (elements) somewhere else on the page with same IDs like the ones in the form..

anyway, here are sometips for you: 1- close the input tags correctly (add / to the end of it):

<input type='text' name='Firstname' id='Firstname' />

2- make sure all DIVs and Ps are closed...as it seems that you have an open P here:

 <p>


 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 </p> <---- missing this one
 <p id='cf_submit_p'>

3- you are redeclaring the error variable all the time, you don't need to do that:

if(Firstname.length == 0){
    var error = true;
....

just use error = true; without var this applies on all places you are changing its value only use var on initialization:

var error = false;

4- instead of this:

$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

use:

$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });

5- if you are using DefaultLocation as a hidden field then instead of this:

 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly />

 </div>

use:

<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />

Ajax simple question

4 votes

I have a very simple question about ajax. If I'd like to refresh a particular area of my site I supose ajax would be the best way.

But is there anyway instead of having a javascript periodically checking for changes on the server, the server would send the data when a given event would happen?

What I'd like was the client not needing to send requests periodically but instead the server would only send the info to the client which in turn would have some kind of event listener.

Thanks in advance

Yes, this can be done. It is referred to as "push" or "push streaming".

Here is one website that offers the ability to do this: InstantPush. And a brief quote from their home page:

"InstantPush is used to make web pages and mobile phones go live. They will instantly be updated in real time when a change occurs at the server side. Standard web communication makes updates pass firewalls and proxies. Without any modules at the client side!

InstantPush has been used since 2001, before "Ajax was invented". It is probably the First Ajax Push Framework.

InstantPush is leading the market in northern Europe."

Here is another company offering this technology: LightStreamer. And a quote from their home page:

"Lightstreamer is a scalable and reliable Server for pushing live data to Rich Internet Applications

Based on the Comet and Real-Time Web paradigms, it streams real-time data to any Web browser and client application. HTML, HTML5, AJAX, Flex, Silverlight, Java, .NET, iOS, Android, and BlackBerry applications, can easily receive live data from Lightstreamer Server.

Lightstreamer has been used in many mission-critical production systems, where scalability, low network impact, bandwidth management, adaptive streaming, and other advanced features, have proven fundamental."

Do I need to care about thread-safety in ASP.NET with AJAX?

4 votes

The question is, is it possible that requests for the same session are executed from multiple threads? Are methods in ASP.NET reentrant? Especially we are using AJAX which means that asychronous requests are taking place.

Would this mean to place locks around operations on objects placed inside the session?

I know that locks are essential when handling static and application wide variables, but the question is is the same true for session objects?

ASP.NET normally uses one thread per request. It can use more than one thread, e.g. when serving asynchronous pages, but even then only one thread will be processing the request at any given time.

It's safe to use the session state from multiple threads, however, because accesses to the session object are serialized. From MSDN:

What if other pages attempt to concurrently access the session state? In that case, the current request might end up working on inconsistent data, or data that isn't up to date. Just to avoid this, the session state module implements a reader/writer locking mechanism and queues the access to state values. A page that has session-state write access will hold a writer lock on the session until the request terminates.

Remove hash from url

4 votes

Hi all (again!)

I am ajax-ifying the pagination in one of me projects and since I want the users to be able to bookmarks the current page, I am appending the page number via hash, say:

onclick="callPage(2); window.location.hash='p=2'; return false;"

and thats on the hyperlink it works fine and everything, except, when the page number is 1, i dont want to URL to be /products#p=1, I just want it to be /products

I tried these variations:

  1. window.location.hash='' works but the url is now like /products# and I dont quite the hash there.
  2. not using window.location.hash at all, but when the user comes back to page 1 from, say page 3, he is in page one, but url is still /products#p=3 since I am not messing with the hash.
  3. Google search on this led me to several minutes (about 15) of silly forums where the question was asked right, but answers were suggesting that the page jumps because the thread creator had a hash in href like <a href="#"> and he should use javascript:void(0) instead. (had they never heard of Ajax?)

So finally, I decided to make this thread, I found several similar threads here, but all the answers ls very similar to my second point.

so my big question still remains a question: How to kick the hash out of the URL and possibly out of the universe? (only for the first page!)

You can do this:

var loc = window.location.href;
  index = loc.indexOf('#');
if (index > 0) {
  window.location = loc.substring(0, index);
}

... but that refreshes the page for you which seems a trifle rude after just arriving there. Grin and bear it seems to be the best option.

How to retrieve a form using AJAX, JSON and PHP onchange of value in a select box?

3 votes

I Have a select box, on selectinga value in it I have to display a form in which there is a Date field which include a javascript calendar functionalty. I tried it with normal AJAX and PHP combination, but I dont get the Calendar in it, So I just need to know How I can make it happen using JSON and AJAX and PHP?

Thanks

Every Help Is Appreciated....

THE CODE

This is The Javascript I am Using to AJAX function:

<script>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(path,val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
 if (req.readyState==4) {
      if (req.status==200) {
            document.getElementById('docfields').innerHTML="";
            if(req.responseText != ''){
           document.getElementById('docfields').innerHTML=req.responseText; //retuen value
            }else{
            document.getElementById('docfields').innerHTML="<br>&nbsp;\t<font size='2'><b>No Fields Available</b></font>";
            }
      }
 }
};
req.open("GET", path+"getDocFields.php?doctype_id="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
</script>

Below Is the HTML form which I need to display with Calendar object (tcal) instantiated in the script tag:

<form onsubmit="" action="" method="post" name="newdoc">
         <table border="0" style="border: medium none;" id="docfield">
          <tbody>
          <tr>
            <td style="border-right: medium none;">
                Date
            </td>
         <td style="border-right: medium none;">
            <input type="text" value="" maxlength="10" name="Test" style="width: 100px;" id="date">
        <script>
         new tcal ({  
      'formname': 'newdoc',  
      'controlname': 'Test'
         });
     </script>
        </td>
     </tr>
    </tbody>
 </table>
</form>

I am not getting the calendar displayed...

I see javascrip in the response html, which will never be executed if the html is coming through ajax call. Try to put that javascript

new tcal ({
'formname': 'newdoc',
'controlname': 'Test'
});
after your XMLHttpRequest object fetches and puts data in '#docfields'.

if (req.readyState==4)
{
   if (req.status==200)
   {
      document.getElementById('docfields').innerHTML="";
      if(req.responseText != '')
      {
          document.getElementById('docfields').innerHTML=req.responseText; //retuen value
          /** here **/
          new tcal ({'formname': 'newdoc','controlname': 'Test'});
          /** here **/
      }
      else
      {
          document.getElementById('docfields').innerHTML="No Fields Available";
      }
   }
}

Hope it will help.