Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit checkbox values alongwith existing form data using PHP, jQuery and AJAX(i.e. avoid form reloading after checking any of the checkboxes)?

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

<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: enter image description here

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:

<?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.

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?

like image 631
PHPLover Avatar asked Jan 31 '14 15:01

PHPLover


2 Answers

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

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();
});
like image 121
kali Avatar answered Nov 01 '22 14:11

kali


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

$(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

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

    //return json
    echo json_encode($data);
like image 32
Sundar Avatar answered Nov 01 '22 14:11

Sundar