jeudi 31 janvier 2019

Laravel - Search using Ajax, Automatically search when page is open

How can I automatically search the data when I put a value on my textbox let's say the value is fixed. like this <input type="text" name="search" id="search" class="form-control" value="10310" />

the value there is 10310 and when I open the page I want to automatically search that value. right now my search has an ajax and it is working well. but my problem is I cannot automatically search the value when i open the page by putting a value on my textbox.

Expected Output - I want to automatically search the data that my textbox has.

View

            <input type="text" name="search" id="search" class="form-control" value="10310" />



    <div id="divContent">

    </div>    

here is my Ajax Script

<script type="text/javascript">

    $(document).ready(function(){

    fetch_customer_data();

    function fetch_customer_data(query = '')
    {
    $.ajax({
    url:"",
    method:'GET',
    data:{query:query},
    dataType:'json',
    success:function(data)
    {
    $('#divContent').html(data.table_data);
    $('#total_records').text(data.total_data);
    }
    })
    }

    $(document).on('keyup', '#search', function(){
    var query = $(this).val();
    fetch_customer_data(query);
    });
    });

</script>

my Controller

 function actionActualTime(Request $request)
{
 if($request->ajax())
 {
  $output = '';
  $query = $request->get('query');
  if($query != '')
  {
   $data = DB::table('employeefms')
     ->where('last_name', 'like', '%'.$query.'%')
     ->orWhere('first_name', 'like', '%'.$query.'%')
     ->orWhere('employee_no', 'like', '%'.$query.'%')
     ->get();

  }
  else
  {
   $data = DB::table('employeefms')
     ->orderBy('last_name', 'desc')
     ->get();
  }
  $total_row = $data->count();
  if($total_row > 0)
  {
   foreach($data as $row)
   {

    $output .= '
    <div class="container">
     <img height="50px" width="60px" src="/storage/employee_photos/'.$row->employee_photo.'" /><span class="d-none">'.$row->employee_photo.'</span><br><br>
     <p><b>Employee No: </b></p><input type="text" class="form-control col-md-2" value='.$row->employee_no.'></input><br>
     <p><b>Name: </b></p><input type="text" class="form-control col-md-3" value='.$row->last_name.'></input><br><hr>
     </div>
    ';
   }
  }
  else
  {
   $output = '
   <tr>
    <td align="center" colspan="5">No Data Found</td>
   </tr>
   ';
  }
  $data = array(
   'table_data'  => $output,
   'total_data'  => $total_row
  );

  echo json_encode($data);
 }


}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire