如何使用PHP、jQuery和AJAX(例如检查任何复选框后,避免表单重新加载?

时间:2022-11-23 20:02:43

I've a filter form in a smarty template as follows:

我有一个smarty模板中的过滤器表单,如下所示:

<form id="view-questions-form" name="user_transactions" action="{$control_url}modules/transactions/view_transactions.php" method="post">
      <div class="w50">
        <ul>
          <li>
            <label>From Date</label>
            <div class="form-element">
              <input type="text" class="cal fl-left" id="frmDate" name="from_date" value="{if $from_date}{$from_date}{else}{$today_date}{/if}" maxlength="10">
            </div>
          </li>
          <li>
            <label>Transaction No.</label>
            <div class="form-element">
              <input type="text" name="transaction_no" id="transaction_no" class="" value="{if $transaction_no}{$transaction_no}{/if}" maxlength="50">
            </div>
          </li>
        </ul>
      </div>
      <div class="w50">
        <ul>
          <li>
            <label>To Date</label>
            <div class="form-element">
              <input type="text" name="to_date" id="toDate" class="cal" value="{if $to_date}{$to_date}{else}{$today_date}{/if}" maxlength="10">
            </div>
          </li>
          <li>
            <label>Discount Code</label>
            <div class="form-element">
              <input type="text" name="userName" id="userName" class="">
            </div>
          </li>
        </ul>
      </div>
      <div class="w50">
        <ul>
          <li>
            <label>Status</label>
            <div class="form-element">
              <select name="transaction_status" id="transaction_status">
                <option value="">All</option> 
                <option value="success" {if $transaction_status=='success'} selected="selected" {/if}>Success</option>
                <option value="inprocess" {if $transaction_status=='inprocess'} selected="selected" {/if}>Inprocess</option>
                <option value="cancelled" {if $transaction_status=='cancelled'} selected="selected" {/if}>Cancelled</option>
                <option value="fail" {if $transaction_status=='fail'} selected="selected" {/if}>Fail</option>
              </select>
            </div>
          </li>
        </ul>
      </div>
      <div class="fl-right">
        <div class="form-element">
          <span class="c-bl-btn c-search-btn-another"><input type="submit"  name="Submit" id="" value="Search" onclick="get_user_filter_data(); return false;"></span>
        </div>
      </div>
    </form>    

Exactly below this form tag completion I've added four checkboxes. The code for it is as follows:

就在这个表单标签完成之后,我添加了四个复选框。其代码如下:

<div class="trans_menu">
  <ul class="trans_menuul">
    <li>
      <a href="#" class="blue_active">
        <div>
          <div class="checkbxd"><input class="custom-check" type="checkbox" name="cancelled" id="cancelled">  
          </div>
          <div class="checkbxd_txt">Cancelled : {$user_transactions_count.cancelled_transaction_count}</div>
        </div>
      </a> 
    </li>
    <li>
      <a href="#" class="green">
        <div>
          <div class="checkbxd"><input class="custom-check" type="checkbox" name="success" id="success"></div>
          <div class="checkbxd_txt">Success : {$user_transactions_count.success_transaction_count}</div>
        </div>
      </a> 
    </li>
    <li>
      <a href="#" class="yellow">
        <div>
          <div class="checkbxd"><input class="custom-check" type="checkbox" name="inprocess" id="inprocess"></div>
          <div class="checkbxd_txt">Inprocess : {$user_transactions_count.inprocess_transaction_count}</div>
        </div>
      </a> 
    </li>
    <li>
      <a href="#" class="red">
        <div>
          <div class="checkbxd"><input class="custom-check" type="checkbox" name="failed" id="failed"></div>
          <div class="checkbxd_txt">Failed : {$user_transactions_count.failed_transaction_count}</div>
        </div>
      </a> 
    </li>
  </ul>
</div>

For better understanding of the scenario find the the screenshot of above HTML as follows: 如何使用PHP、jQuery和AJAX(例如检查任何复选框后,避免表单重新加载?

为了更好地理解这个场景,请找到上面HTML的截图如下:

By submitting the filter form by clicking on submit button I'm providing some search criteria by means of values entered/selected by user in above filter form. The data matching with the given search criteria is fetched and displayed into grid. Till here everything works fine. The PHP code for it is as follows:

通过点击submit按钮,通过提交过滤器表单,我提供了一些搜索标准,通过用户在上面的过滤器表单中输入/选择的值。获取与给定搜索条件匹配的数据并显示到网格中。在此之前一切正常。PHP代码如下:

<?php
/*Below is the function call which fetches all the matching data with the given search criteria*/
list( $grid_data, $transaction_count_data, $sort_status, $sort_link_array, $pag_link_array ) = get_all_user_transactions($request,$cur_page, $sort_col_id ,$desc_or_asc, $where_str, $query_string);
/*Below two statements are used to assign the fetched data to smarty template*/
$smarty->assign('user_transactions', $grid_data);
$smarty->assign('user_transactions_count', $transaction_count_data);
?>

Now when user first time comes to this page there is noting in the grid to display. Then he/she provides some filter criteria and submits the form. Then the matched data is fetched and displayed into a grid below the checkboxes.

现在,当用户第一次访问这个页面时,网格中没有任何要显示的内容。然后他/她提供一些筛选条件并提交表单。然后获取匹配的数据并显示到复选框下面的网格中。

Now my requirement is after all the matching records are fetched and displayed into grid, if user checks any one of the check boxes (say checkbox with title "Inprocess"). Then in the grid only the transactions whose status is "Inprocess" should display.

现在,我的要求是,在获取所有匹配记录并显示到网格之后,如果用户选中任何一个复选框(例如带有标题“Inprocess”的复选框)。然后在网格中只显示状态为“Inprocess”的事务。

And these transactions should be amongst the transactions searched by user by providing search criteria previously by submitting the form. If user selects one or more checkboxes then all the matched data should display amongst the fetched data and when user deselects all of the checkboxes then the originally matched data which displayed initially should get display.

并且这些事务应该在用户之前通过提交表单提供搜索条件搜索的事务中。如果用户选择一个或多个复选框,那么所有匹配的数据都应该显示在获取的数据中,当用户删除所有的复选框时,最初显示的原始匹配数据应该会显示出来。

That is in short, I think this can be achieved by submitting the selected checkbox data along with the filter criteria form data together using jQuery and AJAX. So that the form should get submitted and the desired data should get displayed without reloading the form. After getting all the necessary data I can manage the further things on my own. Can anyone help me in submitting all the data together by using jQuery and AJAX?

简而言之,我认为可以通过使用jQuery和AJAX同时提交选中的复选框数据以及筛选条件表单数据来实现这一点。因此,表单应该被提交,而所需的数据应该在不重新加载表单的情况下显示。在得到所有必要的数据之后,我可以自己处理更多的事情。谁能帮我用jQuery和AJAX一起提交所有数据吗?

3 个解决方案

#1


3  

You can get and handle the values of check boxes individually but the easiest option is to wrap your inputs in one element (you do not necessarily need to this either but I'm making life easier for myself here)

您可以单独获取和处理复选框的值,但最简单的选项是将输入封装到一个元素中(您也不一定需要这样做,但我在这里让自己的工作更轻松)

<html>
  <div id="myWrapper">
    <form id="view-questions-form">
      ...... Form elements here
    </form>
    <div class="trans_menu">
      ...... Some checkboxes here
    </div>
  </div>
<html>

Javascript to submit

Javascript来提交

window.myProductsPage = {};

myProductsPage.prepareCheckboxes() = function() {
    var $wrapper = $('#myWrapper');

    $wrapper.find('.custom-check').on('click',function(event) {
        event.preventDefault();
        var searchString = $wrapper.serialize();
        var url = '/submit/to/here?' + searchString;

        $.ajax({
            url     : url,
            dataType: 'json',
            success : function (response) {
                // alert('yay!!, do some stuff here');
            },
            error: function( response ) {
                // alert('noooo');
            }
        });
    });
}

$(document).ready(function () {
    myProductsPage.prepareCheckboxes();
});

#2


2  

This will work for you, I added more variable for your understanding you can reduce the variable usage if you want

这将对您有用,我添加了更多的变量,以便您理解,如果您愿意,您可以减少变量的使用

This is your jquery code. e.preventDefault() will protect the form to be submit/page redirect

这是jquery代码。. preventdefault()将保护提交/页面重定向的表单

$(document).ready(function () {

    //you submit button click handler - please change the selector as you implemented
    $('#submit-button').click(function(e){

        //prevent the form changes
        e.preventDefault();

        //from date
        var from_date1 = $('#frmDate').val();

        //transaction number
        var transaction_no1 = $('#transaction_no').val();

        //to date
        var to_date1 = $('#toDate').val();

        //username
        var userName1 = $('#userName').val();

        //declare a variable
        var checkbox_selection = '';

        //find the check box selection
        if($('#cancelled').prop('checked'))
        {
            //set the value
            checkbox_selection = 'cancelled';
        }
        else if($('#success').prop('checked'))
        {
            //set the value
            checkbox_selection = 'success';
        }
        else if($('#inprocess').prop('checked'))
        {
            //set the value
            checkbox_selection = 'inprocess';

        }
        else if($('#failed').prop('checked'))
        {
            //set the value
            checkbox_selection = 'failed';        
        }


        //use ajax to post the content
        $.ajax({
            type: "POST",
            dataType:'json',
            url: "post_url_location.php", //change your post location URL
            data: {from_date:from_date1,
                   transaction_no:transaction_no1,
                   to_date:to_date1,
                   userName:userName1,
                   checkbox_select:checkbox_selection},
            success: function(response)
            {
                alert('submit success');

            },
            error: function(response)
            {
                alert('submit error');
            }
        }); 

    });

});

If you want to return any success or failure from your process file you can use json data

如果希望从流程文件返回任何成功或失败,可以使用json数据

<?php 
    //variable array
    $data = array();
    $data['status'] = TRUE;
    $data['msg'] = 'success/failure';

    //return json
    echo json_encode($data);

#3


2  

You can use JavaScript to submit the form and use return false; if you do not want to reload the page/form. return false; prevents the form from doing the default action.

可以使用JavaScript提交表单并使用return false;如果不想重新加载页面/表单。返回错误;阻止窗体执行默认操作。

If you want to use jQuery, you can pass e as a parameter to the anonymous function and do a e.preventDefault(). This will acheive the same thing as return false;.

如果希望使用jQuery,可以将e作为参数传递给匿名函数并执行e.preventDefault()。这和返回false是一样的。

For more information on return false; and e.preventDefault(), take a look at this question.

有关返回false的更多信息;和e。preventdefault(),看看这个问题。

#1


3  

You can get and handle the values of check boxes individually but the easiest option is to wrap your inputs in one element (you do not necessarily need to this either but I'm making life easier for myself here)

您可以单独获取和处理复选框的值,但最简单的选项是将输入封装到一个元素中(您也不一定需要这样做,但我在这里让自己的工作更轻松)

<html>
  <div id="myWrapper">
    <form id="view-questions-form">
      ...... Form elements here
    </form>
    <div class="trans_menu">
      ...... Some checkboxes here
    </div>
  </div>
<html>

Javascript to submit

Javascript来提交

window.myProductsPage = {};

myProductsPage.prepareCheckboxes() = function() {
    var $wrapper = $('#myWrapper');

    $wrapper.find('.custom-check').on('click',function(event) {
        event.preventDefault();
        var searchString = $wrapper.serialize();
        var url = '/submit/to/here?' + searchString;

        $.ajax({
            url     : url,
            dataType: 'json',
            success : function (response) {
                // alert('yay!!, do some stuff here');
            },
            error: function( response ) {
                // alert('noooo');
            }
        });
    });
}

$(document).ready(function () {
    myProductsPage.prepareCheckboxes();
});

#2


2  

This will work for you, I added more variable for your understanding you can reduce the variable usage if you want

这将对您有用,我添加了更多的变量,以便您理解,如果您愿意,您可以减少变量的使用

This is your jquery code. e.preventDefault() will protect the form to be submit/page redirect

这是jquery代码。. preventdefault()将保护提交/页面重定向的表单

$(document).ready(function () {

    //you submit button click handler - please change the selector as you implemented
    $('#submit-button').click(function(e){

        //prevent the form changes
        e.preventDefault();

        //from date
        var from_date1 = $('#frmDate').val();

        //transaction number
        var transaction_no1 = $('#transaction_no').val();

        //to date
        var to_date1 = $('#toDate').val();

        //username
        var userName1 = $('#userName').val();

        //declare a variable
        var checkbox_selection = '';

        //find the check box selection
        if($('#cancelled').prop('checked'))
        {
            //set the value
            checkbox_selection = 'cancelled';
        }
        else if($('#success').prop('checked'))
        {
            //set the value
            checkbox_selection = 'success';
        }
        else if($('#inprocess').prop('checked'))
        {
            //set the value
            checkbox_selection = 'inprocess';

        }
        else if($('#failed').prop('checked'))
        {
            //set the value
            checkbox_selection = 'failed';        
        }


        //use ajax to post the content
        $.ajax({
            type: "POST",
            dataType:'json',
            url: "post_url_location.php", //change your post location URL
            data: {from_date:from_date1,
                   transaction_no:transaction_no1,
                   to_date:to_date1,
                   userName:userName1,
                   checkbox_select:checkbox_selection},
            success: function(response)
            {
                alert('submit success');

            },
            error: function(response)
            {
                alert('submit error');
            }
        }); 

    });

});

If you want to return any success or failure from your process file you can use json data

如果希望从流程文件返回任何成功或失败,可以使用json数据

<?php 
    //variable array
    $data = array();
    $data['status'] = TRUE;
    $data['msg'] = 'success/failure';

    //return json
    echo json_encode($data);

#3


2  

You can use JavaScript to submit the form and use return false; if you do not want to reload the page/form. return false; prevents the form from doing the default action.

可以使用JavaScript提交表单并使用return false;如果不想重新加载页面/表单。返回错误;阻止窗体执行默认操作。

If you want to use jQuery, you can pass e as a parameter to the anonymous function and do a e.preventDefault(). This will acheive the same thing as return false;.

如果希望使用jQuery,可以将e作为参数传递给匿名函数并执行e.preventDefault()。这和返回false是一样的。

For more information on return false; and e.preventDefault(), take a look at this question.

有关返回false的更多信息;和e。preventdefault(),看看这个问题。