Category Archives: AJAX

How do you get the length of a string in jQuery?

If you’ve found this page, then chances are you are coming up against the problem where the Javascript .length method is always returning 1 for a jQuery selector. For example, if you have a variable in Javascript, you can ascertain its length as follows:


var myString = "Hello World";
alert(myString.length);

Which should give an output of 11 – i.e. there are 11 characters in the variable. This also applies for variables within jQuery functions. However if you try to apply .length to a selector – e.g.:


alert($('#mySelector').length);

You will always get a return value of 1. What you actually need to do is as follows:


HTML Code:
<div id='mySelector'>Hello World</div>

jQuery Code:
alert($('#mySelector').val().length);

Which will give the expected return value of 11.

Mootools request is not defined error

I kept getting a ‘request is not defined’ error with my Mootools scripts. Took me a few minutes to figure out that Javascript is of course case sensitive and the function is called ‘Request’ not ‘request’. If you’re getting the same error, chances are you need to check your capitalisation!

Why won’t my AJAX form upload a file?

Do you ever have those dumb moments? You waste a whole load of time trying to get a piece of code to work and performing the most complex de-bugging on it only to realise that you have overlooked the most basic and obvious thing?

Yesterday I was putting together an image upload script, which I wanted to do with AJAX. I wanted to have a file upload box at the top of the screen, press upload, have a nice spinning graphic whilst it uploaded, and then have the image fade into a gallery below. I tried all the AJAX methods with Mootools, checked and double checked my form enctype, until it dawned on me…

When you submit forms via AJAX, then it runs through Javascript (that’s all AJAX is of course). The Javascript takes the content of the form boxes and then sends it through an AJAX request. What Javascript cannot do is access local files on your machine, which is why a file upload field on an AJAX form will not work.

D’oh! I couldn’t believe I’d been so stupid. I put it down to the excessive hours I’ve been working…

Anyway, how about a simple workaround?

Put an IFRAME on the page with invisible borders and load up a file in that. Works perfectly, and although the page in the frame is reloading, it doesn’t appear to be at all. End result is exactly what I wanted and very simple.