PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, September 7, 2022

[FIXED] How to use Ajax & jQuery to change data order retrieved at table in Blade

 September 07, 2022     ajax, jquery, laravel, laravel-8, php     No comments   

Issue

I'm working with Laravel 8 and I have retrieved the list of users at a table in Blade:

<table class="table table-hover" id="contentDiv">
   <tbody>
      <tr>
          <th></th>
          <th>Username</th>
          <th>Email</th>
          <th>User Status</th>
      </tr>
      @foreach($users as $user)
      <tr>
          <td>{{ $user->id }}</td>
          <td>{{ $user->name }}</td>
          <td>{{ $user->email }}</td>
          <td>{{ $user->status }}</td>
      </tr>
      @endforeach
</table>

And this is my Controller method:

public function index()
    {
        $users = User::query();

        if(request('desc') == 1){
             $users->orderBy('id','DESC');
        }else{
             $users->orderBy('id','ASC');
        }

        $users = $users->latest()->paginate(20);

        return view('admin.users.all', compact('users'));
    }

Then I tried adding a select option that can change the table order:

<select class="form-control select2" id="dropdown-list">
     <option value="asc" selected="selected">Ascending</option>
     <option value="desc">Descending</option>
</select>

So for example if user clicks on Descending option, an ajax request must change the table order from asc to desc.

And here is my try on Ajax:

   $("#dropdown-list").on('change', function(){
        var val = $(this).val();

        if(val == "desc") {
            $.ajax({
                url: baseurl + '/admin/users?desc=1',
                type: 'get',
                data: {
                    val: val,
                },
                jsonType: 'json',
                success: function (response) {
                    $("#contentDiv tr").remove();
                    // populate new data and append to table
                }
            });
        }else{
            $.ajax({
                url: baseurl + '/admin/users',
                type: 'get',
                data: {
                    val: val,
                },
                jsonType: 'json',
                success: function (response) {
                    $("#contentDiv tr").remove();
                    // populate new data and append to table
                }
            });
        }
    });

So I try removing the entire table contents and after that I should populate the new data ($users) and append them to table.

How can I do that?

Update #1 on Martin Amu's answer

I tried everything he says but when I test, I get this error:

Undefined variable: orderby

Which is referring to this line:

$data['orderby'] = User::orderBy('id', $orderby)->paginate(20);

I also tried $data['orderby'] = User::orderBy('id', $orderby)->get(); but still shows the same error.

Meaning that the if..else conditions on OrderBy method does not run, because I also tested this but none of the conditions ran and skipped to the next line:

        if($request->has('order_by') && $request->order_by == "asc")
        {
            dd(1);
        } elseif($request->has('order_by') && $request->order_by == "desc")
        {
            dd(2);
        }

After that I tried making the query manually like this:

$data['orderby'] = User::orderBy('id', 'DESC')->get();

And it successfully pushes the data into the table but some of the fields are set to Undefined somehow.

Another thing is that, I need to load the the table when the page loads at first time. But now it is empty and I have to make changes to that select option in order to push data into the table.


Solution

View:

<table class="table table-hover" id="contentDiv">
   <tbody>
      <tr>
          <th></th>
          <th>Username</th>
          <th>Email</th>
          <th>User Status</th>
      </tr>
      @foreach($users as $user)
      <tr>
          <td>{{ $user->id }}</td>
          <td>{{ $user->name }}</td>
          <td>{{ $user->email }}</td>
          <td>{{ $user->status }}</td>
      </tr>
      @endforeach
</table>

<table class="table table-hover" id="ajaxView" style="display:none">
   <tbody>
      <tr>
          <th></th>
          <th>Username</th>
          <th>Email</th>
          <th>User Status</th>
      </tr>
     
      <tr id="user-list">
          
      </tr>
      
</table>


<select class="form-control select2" id="dropdown-list" name="dropdown-list">
     <option value="asc" selected="selected">Ascending</option>
     <option value="desc">Descending</option>
</select>

JS in view:

<script>
$("#dropdown-list").on('change', function(){
         var orderBy = document.getElementById("dropdown-list").value;
            $('#contentDiv').hide();
            $('#ajaxView').show();
            $("#user-list").html('');

            if(orderBy == 'asc')
            {
            var orderBy = 1;
            } else if(orderBy == 'desc')
            {
            var orderBy = 2;
            }

            $.ajax({
                    url: "{{url('/api/orderby-users')}}",
                    type: "POST",
                    data: {
                        order_by: orderBy,
                        _token: '{{csrf_token()}}'
                    },
                    dataType: 'json',                 
                    success: function (result) {                        
                        $.each(result.orderby, function (key, value) {                                                         
                          $("#user-list").append('<td>' + value.id + '</td> <td>' + value.name + '</td> <td>' + value.email + '</td> <td>' + value.status + '</td>');
                        });                                            
                     }
                 });
              });        
</script>

Controllers:

public function index()
    {
        $users = User::query();

        $users = $users->latest()->orderBy('id', 'ASC')->paginate(20);

        return view('admin.users.all', compact('users'));
    }

public function OrderBy(Request $request)
{
 if($request->order_by == 1)
 {
  $data['orderby'] = User::orderBy('id', 'ASC')->get();

 } elseif($request->order_by == 2)
 {
  $data['orderby'] = User::orderBy('id', 'DESC')->get();
 }
 
 return response()->json($data);
}

Route:

use App\Http\Controllers\YOURController;
Route::post('api/orderby-users', [YOURController::class, 'OrderBy']);


Answered By - EHF Shahab
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing