简体   繁体   中英

jQuery Ajax loop on form submit

New to Ajax, however, I can't figure out what is wrong, and I assume its the Javascript. My php page is working just fine, however, with this code my login Html simply refreshes over and over with the end of the url changing to ?username=whatIenter&password=whatIenter

JAVASCRIPT

 <script type="text/javascript">

      $(document).ready(function() {
        $('#login_form').submit(function(e) {
          e.preventDefault();
          $.ajax({
             type: "POST",
             url: '/lib/login.php',
             data: $(this).serialize(),
             success: function(data)
             {
              alert("WORKED");
             }
         });
       });
      });

  </script>

HTML

<form id="login_form" action="" method="POST">
      <input type="text" id="user" name="username">

      <input type="password" id="pass" name="password">

      <button id="loginButton" class="login_submit" type="submit" >Login</button>
  </form>

try:

    var header =  {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
    };

    var request = $.ajax({
        url:   '/lib/login.php'
        ,data: $(this).serialize(),
        ,headers: header
    });


    request.done(function(response) {
      alert("WORKED "+response);
    });

Edit:

The thing is, some/most API's will require you to explicitly specify the content type, before they return the "standard" HTTP response that your Javascript will read.

Resources:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

First of all, which jQuery version are you using?

Your code is working fine with jQuery 3.3.1

Always keep in mind this good practices:

  1. Disable the cache on your browser while you develop
    • Each time you wanna check your site, open the browser console and then press F5
  2. Javascript code always needs to stay at bottom inside body tag (just before < /body > )
    • This also apply in the case you put it on a separated file (recommended)
  3. Set the action parameter on your form, this can prevent unexpected errors
    • Even if you are gonna call the same file or url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM