Jump to content

how can i return errors from php using ajax


Recommended Posts

//my php code sample
<?php
include_once('con.php');
if(isset($_POST['username'])){
    $message = [];
    if(empty($_POST['username'])){
        $message['username'] = 'username required';
    }
	#some validation continue...
    $data = $_POST['username'];
    if (count($errors) === 0){
 		#ccode...
		$message['username'] = 'success your name saved';
    }
}
?>
//my jquery ajax
 $('.username').click(function() {
        $.ajax({
            url: 'user.php',
            method: 'POST',
            data: $('.user').serialize(),
            success: function(data) {
                 swal('Wow!','success message from php','success');
            },
            error: function(data) {
                 swal('Oops!','error message from php','error');
            }
        });
        return false;
    });

 

Link to post
Share on other sites

jQuery will consider it an error if the request responds with a 4xx or 5xx status. You can use http_response_code to set it.

Suggested status codes are:
- 400 if the request didn't have the fields you need
- 400 if the new username was invalid
- 403 if the user tried to update the status of someone they're not supposed to

jQuery won't deserialize the JSON for an error response so your code should attempt to do that itself. Then it can look for an error message.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.