开发者

jquery, cannot have an ajax call in a callback function

开发者 https://www.devze.com 2023-03-19 02:03 出处:网络
<head> <script type=\"text/javascript\" src=\"js/jquery-1.3.2.min.js\"></script> <script type=\"text/javascript\">
<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号