How do i return the error message

Hi, I am having problem in my trappings…I am submitting the form to other page which is adduser.php via jquery.ajax, and then in the adduser.php i have server side validation for the fields but the problem is how can i returned the message back to to the register.php ?

register.php


    formdata = $('#userform').serialize();
   $.ajax({
                     type: 'post',
                     data: formdata,
                     url: "adduser.php",
                     success: function(data){
                          if(data=="ok"){
                              //process some script here...
                          }
                      }


                  });




adduser.php



 include_once 'myfunction.php';

    if(isset($_POST['firstname'])){

      $firstname   = $_POST['firstname'];
      $middlename   = $_POST['middlename'];
      $firstname  = $_POST['lastname'];
      $address    = $_POST['address'];
  
      $error = validate_firstname($firstname);
     
     if($error != ' '){
       //how do i return back to my register.php ?
  }
    
  adduser($firstname,$middlename,$lastname,$address);

}

Thank you in advance.

My bad, i was thinking that the JS is disabled,…anyways the user cannot submit the form if the js is disabled…sorry for this.

Sure they can, there are a lot of tools out there to post arbitrary data to arbitrary URLs. You always need to check input on the server. Always. No excuses.

In this case I would return JSON. Something like


include_once 'myfunction.php';

if (isset($_POST['firstname'])) {
      $firstname   = $_POST['firstname'];
      $middlename   = $_POST['middlename'];
      $firstname  = $_POST['lastname'];
      $address    = $_POST['address'];
  
      $error = validate_firstname($firstname);
     
     if ($error != ' '){
         echo json_encode(array('error' => true, 'errorMessage' => $error));
         exit;
     }
  }
    
  adduser($firstname,$middlename,$lastname,$address);
}

then in the javascript you can check for data.error, and if it is set, display data.errorMessage somewhere

Hi Thank you for the reply…but what if the user will try to use the firebug and they let the error message to false in my condition in my js.does this will not cause problem?..can you please show me how will you check in the JS so that i can have some idea.

Thank you in advance.:slight_smile:

If they fake the response in Firebug they are only fooling themselves because that has no effect on what happens on the server.

Thank you for enlighten my mind. :slight_smile:

As for the JS, it goes a little something like this


var formdata = $('#userform').serialize();
$.ajax({
    type: 'post',
    data: formdata,
    url: "adduser.php",
    success: function(data) {
        if (data.error) {
            alert(data.errorMessage);
        } elseif (data === 'ok') {
            // continue processing
        } else {
            // unknown response
        }
    }
});