#1
  1. A Change of Season
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    3,215
    Rep Power
    220

    PHP returns success to ajax request no matter what


    Hi;

    How come $.ajax always returns success even if the php returns false?

    Thanks

    This is the php code that inserts comments into the database
    PHP Code:
    if(isset($_POST['name']) && isset($_POST['comment']) && strlen($_POST['comment'])>&& strlen($_POST['name'])>0)
                    {
                        
    $data = array(
                           
    'comment_content' => $_POST['comment'],
                           
    'comment_author' => $_POST['name'],
                           
    'comment_created_at' => time(),
                           
    'comment_approved' => 1
                        
    );
                        
    $this->db->insert('comments'$data); 
                        echo 
    "<div class=\"alert alert-success\"><small class = \"red_tect\">Your comment has been added successfully.</small></div>";
                    }    
                else 
                    {
                        return 
    false;
                    } 
    This is the code that passes the data.
    Code:
    $(document).ready(function() 
      {
          $('#comment_form').submit(function() { // catch the form's submit event
              $.ajax({ // create an AJAX call...
                  data: $(this).serialize(), // get the form data
                  type: $(this).attr('method'), // GET or POST
                  url: $(this).attr('action'), // the file to call
                  success: function(response) 
                    { // on success..
                      $('#comment_form_div').html(response); // update the DIV
                    },
                  error: function () 
                    {
                      alert('error');//$('#status').html('Failed').slideDown();
                    }  
              });
              return false; // cancel original event to prevent form submitting
          });
      });
  2. #2
  3. Lazy Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,382
    Rep Power
    9645
    The return value has no bearing on the response status or output or anything like that: it's purely for code written like
    PHP Code:
    $value = (include "script.php"); 
    Send a non-2xx status. Given the failure has to do with bad data in the request I suggest 400.
  4. #3
  5. A Change of Season
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    3,215
    Rep Power
    220
    Thank you. It's beautiful.

IMN logo majestic logo threadwatch logo seochat tools logo