Return a JSON object.

Construct a PHP array such as $json_data = array('result' => 0,
'error' => 'This is an error').  End your PHP script with json_encode
($json_data).  Then you can reference del.result and del.error (I'm
referring to your definition of the' success' function from your
sample code)


On Jan 4, 7:16 am, rob303 <r...@cube33.com> wrote:
> Hi,
>
> I'm new to ajax and jquery but I'm not new to PHP.  The following
> example seems to work okay to a point but I can't figure out how to
> handle data validation errors generated in my PHP.
>
> In my example I want to post some data to a script called ajax.php.
> That script will check the data for validity and then return true or
> false depending on the outcome of the checks. It will also set an
> appropriate error message.
>
> How can I handle the returned data and display an error message if
> needed in ajax?
>
> ----------------------
> HTML / Ajax - test.php
> ----------------------
> <?php
>
> require_once("includes.php");
>
> ?>
> <html>
>   <head>
>     <script src="js/jquery.js" type="text/javascript"></script>
>     <script type="text/javascript">
>       $(document).ready(function(){
>         $("form#submit").submit(function() {
>           var email = $('#email').attr('value');
>           $.ajax({
>             type: "POST",
>             url: "ajax.php",
>             data: "email="+ email,
>             success: function(del){
>               $('form#submit').hide();
>               $('div.success').fadeIn('medium');
>               // what if the data failed validation in PHP?
>               // we need to show 'div.error".
>             }
>           });
>           return false;
>         });
>       });
>     </script>
>   </head>
>   <body>
>     <form id="submit" method="post">
>       Email:
>       <input id="email" class="text" name="email" size="20"
> type="text" />
>       <input type="submit" value="send mail" />
>     </form>
>     <div class="success" style="display:none;">
>       Email sent.
>     </div>
>     <div class="error">
>       <?php echo $userError; ?>
>     </div>
>   </body>
> </html
>
> ----------------------
> PHP - ajax.php
> ----------------------
> <?php
>
> require_once("includes.php");
>
> $message = $_POST['email'];
>
> if($message != '') {
>   mail('some-em...@email.com', 'Ajax test', $message);
>   return 1;} else {
>
>   $userError = "Please enter your email address";
>   return 0;
>
> }
>
> ?>
>
> I've been searching the web for an answer but can't find one
> anywhere!  Any help would be greatly appreciated.

Reply via email to