Tag Archives: Javascript

JavaScript: Delayed keypress event (sort of)

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.

Continue reading

Measure upload time and speed with PHP and Javascript

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?

  1. Right before data is posted, nudge the server with an AJAX call which stores the current timestamp in a session variable
  2. Post the data
  3. 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 :)

Continue reading

PHP: What’s a valid JavaScript identifier (or function name)?

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,

Continue reading

JavaScript: Uppercase first letter in a string

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.

Needed that in JavaScript, but discovered there was no such thing.

Continue reading

PHP: How to easily provide JSON and JSONP

Would you like to grab some server-side data through an AJAX call? For example by using the handy jQuery.ajax method?

A good data format to use then is JavaScript Object Notation, more commonly known as JSON. Providing data in the JSON format with PHP is super duper simple 8)

Continue reading