开发者

How to echo an error if my server code returns false

开发者 https://www.devze.com 2023-01-19 15:26 出处:网络
What I want to do is alert() an error message to the user if my PHP script return开发者_如何转开发s an error. Can someone tell me how to do this?EDIT:

What I want to do is alert() an error message to the user if my PHP script return开发者_如何转开发s an error. Can someone tell me how to do this?


EDIT:

So what i would do is simply use json and return a 200 response with a message for example

PHP

  $validationErrors = array();

  foreach($data as $name => $value){
    // validate each value, if its not valid append a message to the $validationErrors array
    // like $validationErrors[$name] = $message; 
  }

  if(!empty($validationErrors)){
     // send json headers so jquery can parse properly
     header('Content-type: application/json');
     echo json_encode('valid'=>false, 'errors' => $validationErrors));
     exit;
  } else {
    // send json headers so jquery can parse properly
    header('Content-type: application/json');
    echo json_encode(array('valid'=>true));
    exit;
  }

jQuery:

  $.ajax({
      url: '/url/for/whatever.php',
      data: {'my': 'data'},
      dataType: 'json',
      success: function(response){
         if(!response.valid){
            $.each(response.errors, function(name, msg){
                var errmsg = $('<div class="error"></div>').text(msg);
                $('[name='+name+']').before(errmsg);
            });
            alert('Errors were found!'); 
         }
      }
    });

This way you can also display the errors for each field allowing the user to correct them. Youll probably need to modify my error message insertion but you get the idea.


Assuming you mean using $.ajax you would simple assign an error function:

$.ajax({
  url: '/url/for/whatever.php',
  data: {'my': 'data'},
  error: function(){
    alert('An error occurred!');
  }
  success: function(response){
     // whatever happens if the response is successful
  }
});

However for the error function to be invoked the server must respond with 400 or 500 range error code. IF for example you are handling the errors in your php and then outputting an error message then presumable you would be sending a 200 response so the success function would still be invoked. You can manipulate this by setting the header manually with the php header() function if you want.


The ajax has a error block , you can put your custom message in the error block.

0

精彩评论

暂无评论...
验证码 换一张
取 消