Advertisement
HwapX

Ajax Sample

May 17th, 2015
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. <?php
  2. $usuarios = array(
  3. array('login' => 'fulano', 'email' => 'fulano@exemplo.com'),
  4. array('login' => 'beltrano', 'email' => 'beltrano@exemplo.com'),
  5. array('login' => 'siclano', 'email' => 'siclano@exemplo.com')
  6. );
  7.  
  8. if($_POST) {
  9. $login = $_POST['login'];
  10. $email = $_POST['email'];
  11.  
  12. $encontrado = array();
  13.  
  14. foreach($usuarios as $usuario) {
  15. if($usuario['login'] === $login)
  16. $encontrado['login'] = true;
  17. if($usuario['email'] === $email)
  18. $encontrado['email'] = true;
  19. }
  20. header('Content-type: application/json');
  21.  
  22. $json = array();
  23.  
  24. if($encontrado) {
  25. $json['status'] = false;
  26. $json['message'] = "Login ou email em uso.";
  27. $json['data'] = $encontrado;
  28. } else {
  29. $json['status'] = true;
  30. $json['message'] = "Cadastro efetuado com sucesso.";
  31. }
  32.  
  33. exit(json_encode($json));
  34. }
  35. ?>
  36.  
  37. <html>
  38. <head>
  39. <title>Teste</title>
  40. </head>
  41. <body>
  42. <form id="myForm" method="post">
  43. <label>
  44. Login
  45. <input name="login">
  46. </label>
  47. <label>
  48. Email
  49. <input name="email" type="email">
  50. </label>
  51. <input type="submit" value="Enviar">
  52. </form>
  53. <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  54. <script>
  55. jQuery(function($) {
  56. var $myForm = $('#myForm');
  57. $myForm.submit(function() {
  58. $.post(window.location.href, $myForm.serialize(), function(response) {
  59. if(response.status) {
  60. $('input').css('border-color', '');
  61. } else {
  62. for(field in response.data) {
  63. $('[name=' + field + ']').css('border-color', 'red');
  64. }
  65. }
  66.  
  67. alert(response.message);
  68. });
  69. return false;
  70. });
  71. });
  72. </script>
  73. </body>
  74. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement