Guest User

Untitled

a guest
Jul 30th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. How do I return a proper success/error message for JQuery .ajax() using PHP?
  2. <script type="text/javascript">
  3. $(function() {
  4. $("form#subsribe_form").submit(function() {
  5. var email = $("#email").val();
  6.  
  7. $.ajax({
  8. url: "subscribe.php",
  9. type: "POST",
  10. data: {email: email},
  11. dataType: "json",
  12. success: function() {
  13. alert("Thank you for subscribing!");
  14. },
  15. error: function() {
  16. alert("There was an error. Try again please!");
  17. }
  18. });
  19. return false;
  20. });
  21. });
  22. </script>
  23.  
  24. <?php
  25. $user="username";
  26. $password="password";
  27. $database="database";
  28.  
  29. mysql_connect(localhost,$user,$password);
  30. mysql_select_db($database) or die( "Unable to select database");
  31.  
  32. $senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^.-_@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
  33.  
  34. if($senderEmail != "")
  35. $query = "INSERT INTO participants VALUES (CURDATE(),'".$senderEmail."')";
  36. mysql_query($query);
  37. mysql_close();
  38.  
  39. $response_array['status'] = 'success';
  40.  
  41. echo json_encode($response_array);
  42. ?>
  43.  
  44. header('Content-type: application/json');
  45. echo json_encode($response_array);
  46.  
  47. ?>
  48.  
  49. data: {'email': email},
  50.  
  51. if(mysql_query($query))
  52. $response_array['status'] = 'success';
  53. else
  54. $response_array['status'] = 'error';
  55.  
  56. success: function(data) {
  57. if(data.status == 'success')
  58. alert("Thank you for subscribing!");
  59. else if(data.status == 'error')
  60. alert("Error on query!");
  61. },
  62.  
  63. $results = array(
  64. 'error' => false,
  65. 'error_msg' => 'Everything A-OK',
  66. 'data' => array(....results of request here ...)
  67. );
  68. echo json_encode($results);
  69.  
  70. if (!data.error) {
  71. ... got data, do something with it ...
  72. } else {
  73. ... invoke error handler ...
  74. }
  75.  
  76. error:function(x,e){
  77. if(x.status==0){
  78. alert('You are offline!!n Please Check Your Network.');
  79. }else if(x.status==404){
  80. alert('Requested URL not found.');
  81. }else if(x.status==500){
  82. alert('Internel Server Error.');
  83. }else if(e=='parsererror'){
  84. alert('Error.nParsing JSON Request failed.');
  85. }else if(e=='timeout'){
  86. alert('Request Time out.');
  87. }else {
  88. alert('Unknow Error.n'+x.responseText);
  89. }
  90. }
Add Comment
Please, Sign In to add comment