Friday, October 7, 2011


AJAX calls in javascript come into picture when we have to execute some server side code based on some events on the client. A simple example would be performing a DB insert on the server by picking up the values on the client side. A lot of things can go wrong if there is some error in the SQL query and the entire sql query is displayed to the user. One of the generous way too handle this on the server in PHP is:

people familiar with jquery ajax and PHP can read the bold part directly.

<?php

try{
 class NoBuddiesException extends Exception {}

header("Content-type: application/json\n");

$buddy_sql="select your buddies SQL here";
$result=mysql_query($buddy_sql);
 if(mysql_error()){
    throw new Exception(mysql_error());
}

if( mysql_num_rows($result)==0  ){
    throw new NoBuddiesException("Empty Buddy List");
}
}
catch(NoBuddiesException $e ){
       header("HTTP/1.0 204 Accepted");
       echo json_encode( array("errorno" => 160, "error" => "get on with life...get some buddies") );
       die;
}
catch (Exception $e){
     header("HTTP/1.0 500 Error");
     echo json_encode( array( "errorno" => 123 , "error" => $e->getMessage() ) );
     die;
}

be sure to catch the narrower exception before you catch a more generic exception or else everything will get caught in the more generic exception and exit. Eg. above NoBuddiesException is a subclass of Exception and so is caught before we catch the more generic Exception.

The javascript ajax call for the above

$.ajax({
      url: "location of the above php",
      data: { user: $("#yourdiv").val() },
      type: "post",
      succcess: function (data, status, jqXHR){/
             //congrats your ajax call was successful
             if(data.status == 204){
           
             }
      }
       error: function(errorMsg, textStatus, error){
              //catch all your exceptions here based on the server error codes specified
               if(errorMsg.status==500){
                  //handle the error appropriately
               
}
              alert(errorMsg.responseText); //to get the message sent from the server              
             
}
});

Thanks to awattson

No comments:

Post a Comment