mahenda Posted September 1, 2020 Share Posted September 1, 2020 //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; }); Quote Link to comment https://forums.phpfreaks.com/topic/311412-how-can-i-return-errors-from-php-using-ajax/ Share on other sites More sharing options...
requinix Posted September 1, 2020 Share Posted September 1, 2020 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. Quote Link to comment https://forums.phpfreaks.com/topic/311412-how-can-i-return-errors-from-php-using-ajax/#findComment-1581081 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.