Wanted to do an AJAX call whenever the content of a field was changed. This can be done simply with the onchange event, but the problem is that you have to tab out of the field to make it fire. You can also do it with the keypress event, but then you’ll get one AJAX call for each and every keypress, which is just silly.
Found a nice and easy solution, and here it is slightly simplified.
Stumbled upon a question on StackOverflow the other day which got me curious. The question was about how to measure how long it takes to upload a file to a PHP script. This is what had been tried out:
$upload_time = time() - $_SERVER['REQUEST_TIME'];
This pretty much always returns zero, even though the uploading actually took many seconds, because the request start time is after the server has received the post data. That we actually just get how long the script took to run, which of course is pretty close to zero seconds. So, what can we do?
- Right before data is posted, nudge the server with an AJAX call which stores the current timestamp in a session variable
- Post the data
- Compare current timestamp with the one stored in step 1
Wasn’t sure how it would work, but seems to work pretty well. There will of course be a very tiny difference since the AJAX request will be a bit part of the time, but compared to the upload time it shouldn’t matter much. Anyways, here’s how you could do it
After another reply to a question I’ve had on StackOverflow for a while, I decided that I perhaps should add another level of security to my method of providing JSONP from PHP. The way I did it before, I didn’t do any checking on the provided callback. This means that someone could technically put whatever they wanted in there, including malicious code. So, therefore it might be a good idea to check if the callback, which should be a function name, actually is a valid function name. But,
Needed to add a hover effect on some table rows and wanted to make it look nice. Think I managed to get it quite smooth in the end and thought I could share it.
In PHP there is a very handy function called ucfirst which
Returns a string with the first character of str capitalized, if that character is alphabetic.
Would you like to grab some server-side data through an AJAX call? For example by using the handy jQuery.ajax method?