简体   繁体   中英

jQuery ajax does not work

I made a test jQuery ajax script and I attached it to a form when submitted but despite the fact that I have return false at the end of my function the page keep refreshing at submit and I also don't get any response.

The form look like this:

<form id="LogInForm" onsubmit="return LogIn();">
    <input type="text" placeholder="Username" name="Username"><br/>
    <input type="password" placeholder="Password" name="Password"><br/>
    <input id="LogIn" type="submit" value="Sign In">
</form>

The script look like this:

function LogIn() {

    $.ajax({
          type:'POST',
          url: 'login.php',
          data:$('#LogInForm').serialize(),
          success: function(response) {
                    alert(response);
                 }});
        return false;
       }

The login.php file only contains echo "test";

The index.php and login.php are in the same folder.

I just removed the onsubmit from you'r form and implemented it into the script.

<form id="LogInForm">
    <input type="text" placeholder="Username" name="Username"><br/>
    <input type="password" placeholder="Password" name="Password"><br/>
    <input id="LogIn" type="submit" value="Sign In">
</form>

script

$(function() {
    $("#LogInForm").submit(function() {
        $.ajax({
          type:'POST',
          url: 'login.php',
          data:$('#LogInForm').serialize(),
          success: function(response) {
               alert(response);
           }});
        return false;
    });
});
$(function() {
    $("#LogInForm").submit(function() {  
        $.post('login.php', $("#LogInForm").serialize()).done(function(data) {
            alert(data);
        }); 
    });
});

and the html

<form id="LogInForm">
   <input type="text" placeholder="Username" name="Username"><br/>
   <input type="password" placeholder="Password" name="Password"><br/>
   <input id="LogIn" type="submit" value="Sign In">
</form>

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