How to stop refreshing page after ajax call?

感情迁移 提交于 2019-12-28 03:43:06

问题


I am unable to stop refreshing page after ajax call. I have tried by putting e.preventDefault(); and return false; as well but again my page is refreshing.

I dont know what is the problem with the code or something. Please help me to stop refreshing page after ajax call. solving this issue would be a great help for me. Thanks in advance.

Here is my code:

$(document).ready(function() {
    $('#loginForm').on('click', function(e) {
        e.preventDefault();
        var formData = {
            'uname'  : $('#uname').val(),
            'pwd'    :      $('#pwd').val()
        };
        $.ajax({
            type        : "POST",
            url         : "getresults.php", 
            data        : formData
        }).done(function(data) {
              alert(data+"This is working");
        }).fail(function(data) {
              alert("This is not working");
        });
    });
});

回答1:


Is the id #loginForm pointing to a form? If yes you need to listen to the submit event instead of click. If you really need to listen to the click event, you have to bind the event to the submit button or whatever triggers the form.submit().

Try something like this:

$('#loginForm').on('submit', function(e) {
    e.preventDefault();
    e.stopPropagation(); // only neccessary if something above is listening to the (default-)event too

    [YOUR CODE GOES HERE]
});

This should do the trick for you.




回答2:


Adding type="button" attribute to button solved my problem. Otherwise it was interpreted as submit operation.




回答3:


I think just adding return false after the on click function will stop the page from refreshing




回答4:


This was happening to me earlier tonight, and I found my way to this question - This might be a long shot but I realized what my issue was and figure this might help someone in the future dealing with this.

Are you using something like live-server locally or some other form of script that intelligently refreshes local code if new files appear in the same working folder? If so - the page is refreshing not because of your code, but because whatever ajax you called manipulated the folder you were working in resulting in the page 'updating'.



来源:https://stackoverflow.com/questions/27759380/how-to-stop-refreshing-page-after-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!