简体   繁体   中英

jquery, cannot have an ajax call in a callback function

<head>  
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
         $(document).ready(function(){
              $("#submit").click(function(){
                     $.get("invite_friends_session.php", function(){
                    });
               });
          });
</script>
</head>
<body>
<form >
<input type="submit" name="submit" id="submit" style="margin-top:100px; margin-left:100px;" />
</form>
</body>

the $.get("invite_friends_session.php") part does not work. But it works if i keep it outside the callback function.

But i need to call the invite_friends_session.php whenever there is a click on the #submit.

how to do that?

Since the submit button is inside a form , clicking the submit button bubbles up and submits the form. You need to add a return false to the end of the handler:

$("#submit").click(function(){
    $.get("invite_friends_session.php", function(){
    });
    return false;
});

[Edit] You should prevent the default form submit action upon click.

$(document).ready(function(){
  $("#submit").click(function(e){
    e.preventDefault(); //edit
    $.get({ url: "invite_friends_session.php",
            success: function() {
              alert('success');
            },
            error: function() {
              alert('error');
            },
            complete: function() {
              alert('complete');
            }
          });
  });
});

Remove the <form> tags around the submit button. Since you're using jQuery's .get method, you don't need that form tag (technically, it doesn't even need to be a submit input button). Right now, it's trying to post using the form instead of getting the page via jquery.

Example: http://jsfiddle.net/R3CWp/

<head>  
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
         $(document).ready(function(){
              $("#submit").click(function(){
                     alert("i got clicked");
                     $.get("invite_friends_session.php", function(){
                    });
               });
          });
</script>
</head>
<body>
<input type="submit" name="submit" id="submit" style="margin-top:100px; margin-left:100px;" />
</body>

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