views:

57

answers:

4

I'm using PHP, and am wondering what the best way is to handle simple POSTs and AJAX POSTs without repeating code in the simplest way possible. Thanks!

A: 

I would start with the non-AJAX as the baseline and then add javascript to the form to submit the exact same  request with AJAX.

Something like(pseudo-js):

onsubmit="do_ajax(self.location, document.getElementsByTag('input').values()) return false)"

The real AJAX is of course much more complicated, involving browser compatibility, and code for fetching and  parsing all form values.

Pepijn
+3  A: 

Just create a form like this:

<form action="formhandler.php" method="post">
    <!-- form data here -->
</form>

And look what kind of request was fired in formhandler.php:

if($_SERVER['REQUEST_METHOD'] == 'POST' /* && isset($_POST['var'])*/){
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
        // Request was send by Ajax, so echo JSON-code
        echo '{"error": false}'
    } else {
        // No Ajax was used, so echo HTML-code
        echo '<html><head><title>Ok</title></head><body><p>Ok</p></body></html>';
    }
}

The only thing you need to know is that $_SERVER['HTTP_X_REQUESTED_WITH'] contains information if the form was submitted by an Ajax request

Harmen
+1  A: 

This is called progressive enhancement. The best way to go about it is to build a site that works well with JavaScript turned off, then add JavaScript features on top of that.

In my experience, the easiest way to do this is to submit your form via Ajax (and maybe add a parameter to let the server know it was an Ajax request), and have the server return HTML, which your script uses to update the document.

noah
A: 

I don't think there's a way to support JavaScript / Non-JavaScript-users (there's no "AJAX-capable browser) without code repetition. If you would like to support regular POSTs and AJAX-POSTs, you'll probably end up doing at least some of your work twice.

So if you really want to support users without JavaScript (how many are there, anyway?), stick with a non-JS-solution and do everything server-sided. Stick with Web 1.0, that is ;)

Select0r