Ajax Lab: Draggable w/ Memory

Added position saving to yesterday’s Prototype example: you can see it here. When you move the box around it will save the position where you drop it, then when you reload the page it’ll start out in that position. Pretty nifty, eh?

I ran into some more syntax issues where I kept switching PHP and JavaScript syntax. That’s mostly an experience issue which should erode with time.

One important concern is that anyone can POST data to the page’s accompanying PHP file. I tested this by posting a position of 1000000px,1000000px and sure enough, when I loaded the page the green box jumped to that spot. Firefox was not too fond of this. To remedy the problem, I added a conditional to the JavaScript which adjusts negative and high values but in retrospect, I should check them in the PHP file before they are saved in the database.

I asked John whether there was a way to check that a POST was coming from my site and he said yeah, with $_SERVER['HTTP_REFERER']. At first this seemed like it would solve the problem, but I realized that you can use FireBug to modify the source code on any page. That means that someone can visit any page on this site, edit the HTML to POST to the PHP file, and it would treat it the same as code I had written.

I think the best solution is to validate the data before inputting it into the database. That way if someone does try to set the position to 1000000px, 1000000px it won’t cause any problems.

Two more helpful sites:

JavaScript – Converting Strings to Numbers

JavaScript – Conditional Statement Syntax

On an unrelated note, I added a “Recommended Books” section to the sidebar, which is something I wish other tech writers did more often.

One thought on “Ajax Lab: Draggable w/ Memory

  1. Yep you are right about being able to modify the post variables. Anytime you have POST data you need to verify it before storing it. Generally in a “Drag N’ Drop” situation you’re going to have some kind of boundaries so that would be a simple check.

    Another way would be to set boundaries in your actual javascript code. So if someone stores a value of like 100000px you can just have it reduce the number to a fixed value.

    I think the second option would be better considering dragging and dropping usually involves some kind of containers. This way you can keep all your restrictions in one file, or at least one language. You’ll want to create some javascript objects that represent containers that have certain attributes like width, height, radius, droppable, snappable, etc…

    Either way if you want preventative measures there’s generally lots of ways to do it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s