How to send a form without refreshing the page?

这一生的挚爱 提交于 2019-12-01 12:09:35

You will have to use $.ajax() for that

this is what I use in one of my apps

$('#submitSearch').click(function() {

        var formData = {
            searchData: $('#searchData').val(),
        };

        $.ajax({
            url: siteUrl + 'fetch/search',
            type: "POST",
            data: formData,
            cache: true,            
            beforeSend:function(){
                jQuery('#main').html('<div class="loading"><img src="' + siteUrl + 'resources/imgs/ajax-loader.gif" alt="Loading..." /></div>');
            },
            success: function(data) {
                jQuery('#main').empty();
                jQuery('#main').append(data);
            },
            error:function(x,e){
                if(x.status==0){
                    alert('You are offline!!\n Please Check Your Network.');
                }else if(x.status==404){
                    alert('Requested URL not found.');
                }else if(x.status==500){
                    alert('Internel Server Error.');
                }else if(e=='parsererror'){
                    alert('Error.\nParsing JSON Request failed.');
                }else if(e=='timeout'){
                    alert('Request Time out.');
                }else {
                    alert('Unknow Error.\n'+x.responseText);
                }
            }
        });
        return false;
    });

I'd suggest using a Javascript framework like jQuery and use it's AJAX function. Lots of tutorials to find on the internet if you Google for it.

Start at jquery.com

  1. posibility - Use ajax in any form - jQuery, plain, etc ... see Google

  2. posibility - Create hidden iframe with name="sender" and use form target attribute ( I'm not sure if it is valid, but it works without javascript )

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