Submit form without page reloading

后端 未结 17 2498
无人及你
无人及你 2020-11-22 00:45

I have a classifieds website, and on the page where ads are showed, I am creating a \"Send a tip to a friend\" form...

So anybody who wants can send a tip of the ad

17条回答
  •  太阳男子
    2020-11-22 01:30

    It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.

    First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().

    event.preventDefault()
    

    Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.

    Example:

    Form:

    Javascript:

    function func(){
        event.preventDefault();
        var newValue = $('#input-field-id').val();
        $.ajax({
            type: 'POST',
            url: '...',
            data: {...},
            datatype: 'JSON',
            success: function(data){...},
            error: function(){...},
        });
    }
    

提交回复
热议问题