Mukhlis Raza
Mukhlis Raza

Reputation: 220

Laravel: JavaScript (Status Update Issue)

I have some issue with the update status. Everything works fine status also store in the database, but the status icon does not change accordingly. when I refresh the page the status icon back to the previous position but in the database status remain the same. Actually the position of status==0 not save. enter image description here

banner.blade.php

 @foreach ($banner as $banners)
   @if($banners->status==1)
       <a class="updateBannerStatus" id="banners-{{$banners->id}}" banners_id="{{$banners->id}}" href="javascript:void(0)"><i class="fas fa-toggle-on" aria-hidden='true' status="Active"></i></a>
   @else
       <a class="updateBannerStatus" id="banners-{{$banners->id}}" banners_id="{{$banners->id}}" href="javascript:void(0)"><i class="fas fa-toggle-on" aria-hidden='true' status="Inactive"></i></a>
   @endif
 @endforeach

JS Script

$(document).on("click", ".updateBannerStatus", function () {
    var status = $(this).children("i").attr("status");
    var banners_id = $(this).attr("banners_id");

    $.ajax({
        type: 'post',
        url: '/admin/update-banner-status',
        data: { status: status, banners_id: banners_id },
        success: function (resp) {
            // alert(resp['status']);
            // alert(resp['section_id']);
            if (resp["status"] == 0) {
                $("#banners-" + banners_id).html("<i class='fas fa-toggle-off' aria-hidden='true' status='Inactive'></i>");
            } else if (resp["status"] == 1) {
                $("#banners-" + banners_id).html("<i class='fas fa-toggle-on' aria-hidden='true' status='Active'></i>");
            }
        }, error: function () {
            alert("Error");
        }
    });
});

BannerController

 public function updateBannerStatus(Request $request)
{
    if ($request->ajax()) {
        $data = $request->all();
        // echo "<pre>";
        // print_r($data);
        // die;
        if ($data['status'] == "Active") {
            $status = 0;
        } else {
            $status = 1;
        }
        Banner::where('id', $data['banners_id'])->update(['status' => $status]); // save the new status
        return response()->json(['status' => $status, 'banners_id' => $data['banners_id']]);
    }
}

Upvotes: 1

Views: 178

Answers (1)

Harpal Singh
Harpal Singh

Reputation: 702

In your banner.blade.php, use class fas fa-toggle-off in case of inactive

@foreach ($banner as $banners)
   @if($banners->status==1)
       <a class="updateBannerStatus" id="banners-{{$banners->id}}" banners_id="{{$banners->id}}" href="javascript:void(0)"><i class="fas fa-toggle-on" aria-hidden='true' status="Active"></i></a>
   @else
       <a class="updateBannerStatus" id="banners-{{$banners->id}}" banners_id="{{$banners->id}}" href="javascript:void(0)"><i class="fas fa-toggle-off" aria-hidden='true' status="Inactive"></i></a>
   @endif
 @endforeach

Upvotes: 1

Related Questions