NYCPHP Meetup

NYPHP.org

[nycphp-talk] Ajax 101: what to return from a POST

Jon Baer jonbaer at jonbaer.com
Thu May 3 18:36:29 EDT 2007


Not sure it has to be that complicated ... Im not sure what framework  
you are using but the point is that you also eval() the response you  
get back @ status 412 and send back something like such in a simple  
example:

server.php
header("HTTP/1.0 412 Precondition failed");
header("Content-Type: text/javascript");
$response = <<<EOR
$('errorDiv1').innerHTML = "The following errors occured for div1: ..."
$('errorDiv2').innerHTML = "The following errors occured for div2: ..."
$('errorDiv3').innerHTML = "The following errors occured for div3: ..."
EOR;
echo($response);

index.php
<html>
<head>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function run() {
   var myRequest = new Ajax.Request('server.php', {
   onFailure: function() {
   // will automatically eval since we return text/javascript
   }
});
}
</script>
</head>
<body>
<a href="javascript:void(0)" onclick="run()">Run</a>
<div id="errorDiv1"></div>
<div id="errorDiv2"></div>
<div id="errorDiv3"><div>
</body>
</html>

Mark's method is similiar in that it builds on the existing DOM w/  
JSON returned, but just showing you could easily control your divs  
server side.

- Jon

On May 3, 2007, at 3:48 PM, David Mintz wrote:

> Yes, I got the part about the HTTP response code.
>
> I am trying to pose a question about what else to do  if validation  
> fails, i.e., req.status == 412:  send back the redrawn form w/  
> errors and display it, or send back just the validation error  
> messages as a JSON object and work with that?
>
> On 5/3/07, Felix Shnir <felix.shnir at gmail.com> wrote: Jon means  
> that the response status should be 412...
>
>         var req = this.getTransport ();
>         req.open('POST', uri, true);
>         req.onreadystatechange = function (aEvt) {
>           if (req.readyState == 4) {
>              if(req.status == 200)
>               var r = eval(req.responseText);
>
>                if(req.status == 412)
>                   alert("error has occured: " + req.responseText);
>               }
>           }
>
> Felix



More information about the talk mailing list