Change dynamic status with x-editable in laravel
Asked Answered
P

2

8

I have select button where I choose status for my entries. This status comes from statuses table and it's not a column in each table (it's general option). What I want to do is to change status_id column in my tables with help of x-editable but I don't know how to get my dynamic data in JavaScript.

Here is my current form to show statuses in index page of my reviews for example:

 <form action="{{route('updatebyajax', $rating->id)}}" method="post">
    {{csrf_field()}}
       <td class="text-center" style="width:100px;">
          <select class="form-control status" name="status_id">
            @foreach($statuses as $status)
              <option id="rating" class="rating" data-url="{{ route('updateratebyajax', $rating->id) }}" data-pk="{{ $rating->id }}" data-type="select" data-placement="right" data-title="Edit Rate" value="{{$status->id}}">{{$status->title}}</option>
           @endforeach
        </select>
    </td>
 </form>

So what I need is basically get info out of statuses table and change by select.

dropdown

Update

As requested here is my table screenshot:

table image

PS: here is default sample of select button: sample link

<a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a>
<script>
$(function(){
    $('#status').editable({
        value: 2,    
        source: [
              {value: 1, text: 'Active'},
              {value: 2, text: 'Blocked'},
              {value: 3, text: 'Deleted'}
           ]
    });
});
</script>

Update 2

Review Database reviews

Status Table status

Update 3

I just add my controller method and route in case

controller

public function updatebyajax(Request $request, $id)
  {
    return Rating::find($id)->update([
      'status_id' => $request->get('status_id'),
    ]);
  }

route

Route::post('/updatebyajax/{id}', 'RatingController@updatebyajax')->name('updatebyajax');

UPDATE 4

I mixed several solutions on internet till I finally get status 200 OK in my network but still nothing changes in my database, here is my current codes:

controller

public function updatebyajax(Request $request, $id)
  {
    if (request()->ajax())
        {
            $ratings = DB::table('ratings')->select('status_id','id')->where('status_id', '=', $id)->get();
            return Response::json( $ratings );
        }
  }

AJAX

<script type="text/javascript">
$(".status").change(function() {
    $.ajax({
        type: "post", // for edit function in laravel
        url: "{{url('admin/updatebyajax')}}" + '/' + $(this).val(), // getting the id of the data
        data: {_token: "{{ csrf_token() }}",status: this.value }, //passing the value of the chosen status
        dataType: 'JSON',
        success: function (data) {
            console.log('success');
        },
        error: function (data) {
            console.log('error');
        }
    });
});
</script>

FORM

<form action="{{route('updatebyajax', $rating->id)}}" method="post">
                             {{csrf_field()}}
                              <td class="text-center" style="width:100px;">
                                <select id="{{ $rating->id }}" class="form-control status" name="status_id">
                                  @foreach($statuses as $status)
                                    <option value="{{$status->id}}">{{$status->title}}</option>
                                  @endforeach
                                </select>
                              </td>
                          </form>

UPDATE 5

Regarding to leih answer currently I have this:

Controller

public function updatebyajax(Request $request, $id)
  {
    // Note: should probably use a $request->has() wrapper to make sure everything present

    try {
        // you can also use the ID as a parameter, but always supplied by x-editable anyway
        $id = $request->input('pk');
        $field = $request->input('name');
        $value = $request->input('value');

        $rating = Rating::findOrFail($id);
        $rating->{$field} = $value;
        $rating->save();
    } catch (Exception $e) {
        return response($e->getMessage(), 400);
    }
  }

Route

Route::post('/updatebyajax', 'RatingController@updatebyajax')->name('updatebyajax');

Blade

//Select
<a
  href="#"
  class="status"
  data-type="select"
  data-pk="{{ $rating->id }}"
  data-value="{{ $rating->status_id }}"
  data-title="Select status"
  data-url="{{ route('updatebyajax') }}"
></a>

//JS

<script type="text/javascript">

$.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });

$(function() {
    $('.status').editable({
      type:"select",
        source: [
            @foreach($statuses as $status)
                { value: {{ $status->id }}, text: {{ $status->title }} }
            @endforeach
        ],
    });
});
</script>

And here is the result I get:

screenshot5

PS: If I don't use $.ajaxSetup({ headers: {.... and use java code in answer I will get this error

Parse error: syntax error, unexpected ','

Any idea??

Pirozzo answered 12/12, 2017 at 0:27 Comment(20)
What have you done by now?Clover
@Clover so far what you see in my question, that's all i've done.Pirozzo
need more info . show table with exampleNathanaelnathanial
@GauravGupta example of what? If I had example of dynamic value change with x-editable I wouldn't pop this question! Ps: I will include screenshot of my table)Pirozzo
db table it with example dataNathanaelnathanial
@GauravGupta review db or status db?Pirozzo
@GauravGupta updated my question, please take a lookPirozzo
just one more info what do you mean by get info out of statuses table . did you mean db table and change by select ( change in database)Nathanaelnathanial
no i mean dynamic info such as existing one right now id:1 => active, id:2 => deactivate it might be more later on so I want to fetch them all in my dropdown. and when I edit my review with x-editable just change the id of status in my reviews table to selected one. As I mentioned What I want to do is to change status_id column in my tables with help of x-editablePirozzo
do you really have to use x-editable for that? it can be done using simple jquery function.Courtesy
Make it simple! How many statuses do you expect to have? Use activated_at (nullable) timestamp to check active status. Blocked or deleted, i'd make use of deleted_at (soft deletes).Rivers
@Courtesy No i don't have to. any solutions are most welcome :)Pirozzo
@joshuamabina statuses are dynamic just like posts etc. unlimited is crud. that\s why i need to loop it in my javascript code otherwise wasn't any problem. And NO I cannot make activated_at column because as I said this status is general means I use it for all my app to active/deactive users, reviews, products, posts etc.Pirozzo
@Pirozzo is there something missing from my answer?Eulogistic
@Eulogistic Hi bro sorry for delay, I updated my question to answer you what is missing with your answer UDPADE 5 thank you.Pirozzo
@Pirozzo Doesn't look like you added the quotes from my latest answer update?Eulogistic
@Pirozzo you've also left a comma after your source array (invalid syntax to leave one there in an object definition), and you're missing commas after each object (except the last) in the statuses loop (hence my use of the $loop variable in my answer).Eulogistic
@Eulogistic ibb.co/eCUzH6 this is result of your code without i add or change anything at all.Pirozzo
@Eulogistic OK the error caused by commented @ in your js code and when I removed it, page loaded but on change i get some pop up error with many red lines which i can't see it in my browser fully but here is what i could select ` { "file": "C:\\laragon\\www\\xxxxxx\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php", "line": 116, "function": "sendRequestThroughRouter", "class": "Illuminate\\Foundation\\Http\\Kernel", "type": "->" }, { "file": "C:\\laragon\\www\\xxxxx\\public\\index.php", "line": 55, "function": "handle", ]`Pirozzo
@Pirozzo from the screenshot it looks like the Blade engine is parsing the @json I note in my JS comment, which in turn is causing the syntax error because there's no actual parameter being passed to it. Stripping out the comment should be fine. Unfortunately the selected lines you've posted for the pop-up error isn't really enough for me to diagnose any further.Eulogistic
E
8

When using X-edtiable with a <select> option, it's good to look at the documentation, but better to look at official examples and check the FAQ for what the back end needs. You don't need to make your own forms or write your own AJAX requests with X-editable (that's the whole point). Based on what you're asking, it sounds like the code should look similar to this:

RatingController

public function UpdateByAjax(Request $request)
{
    // Note: should probably use a $request->has() wrapper to make sure everything present

    try {
        // you can also use the ID as a parameter, but always supplied by x-editable anyway
        $id = $request->input('pk');
        $field = $request->input('name');
        $value = $request->input('value');

        $rating = Rating::findOrFail($id);
        $rating->{$field} = $value;
        $rating->save();
    } catch (Exception $e) {
        return response($e->getMessage(), 400);
    }

    return response('', 200);
}

Route

Route::post('/updatebyajax', 'RatingController@UpdateByAjax')->name('updatebyajax');

View

Note: I'm not setting the CSRF token below as it should already be set globally for X-editable (e.g. for text fields in screenshot) if required, or via some other mechanism.

<a
  href="#"
  class="status"
  data-type="select"
  data-pk="{{ $rating->id }}"
  data-name="status_id"
  data-value="{{ $rating->status_id }}"
  data-title="Select status"
  data-url="{{ route('updatebyajax') }}"
></a>
<script>
$(function() {
    // using class not id, since likely used with multiple records
    $('.status').editable({
        // Note: cleaner to format in the controller and render using the @json directive
        source: [
            @foreach($statuses as $status)
                { value: '{{ $status->id }}', text: '{{ $status->title }}' }
                @unless ($loop->last)
                    ,
                @endunless
            @endforeach
        ]
    });
});
</script>

Additional reference: see 'Rendering JSON' in the Displaying Data blade documentation

Eulogistic answered 18/12, 2017 at 21:30 Comment(4)
Hi man appreciate your solution, I'm getting this error in js source part Parse error: syntax error, unexpected ',' and i really not sure about a tag you used for blade as i need drop-down (but i should see how it looks like if i can load the page!)Pirozzo
@Pirozzo the syntax error probably from my missing off quotes, will update the answer shortly. Ideally as mentioned it should be formatted from the controller, but without the controller method showing how you're loading $statuses I didn't want to guess too much. The a tag will show up as text in read-only mode (same as the text variety of x-editable), and will be a <select> in edit mode.Eulogistic
hey man, Happy new year. I'm back to work again and here is what i have ibb.co/jKpmsG | ibb.co/npCNXG when i click on check button i get pop up error. PS: all the codes are the one in your answer currently "nothing changed by me).Pirozzo
@Pirozzo How about we discuss this in chat?Eulogistic
C
1

I think this would be useful for you.

  • Put the id of the value that you want to change in the id of the select box
  • ajax function in jquery

    $(".status").change(function() {
        $.ajax({
            type: "PUT", // for edit function in laravel 
            url: "{{url('updatebyajax')}}" + '/' + this.id, // getting the id of the data 
            data: {_token: "{{ csrf_token() }}",status: this.value }, //passing the value of the chosen status
            dataType: 'JSON',
            success: function (data) {
                // some kind of alert or console.log to confirm change of status
            },
            error: function (data) {
                // error message
            }
        });
    });
    

Hope it helps

Courtesy answered 15/12, 2017 at 9:39 Comment(7)
thanks for code but it doesn't work, first of all i changed id into class in order to get all fields working and not only latest entry and here is the code i used: ` $(".status").change(function() { $.ajax({ type: "PUT", url: "{{url('updatebyajax')}}" + '/' + this.id, data: {_token: "{{ csrf_token() }}",status: this.value }, dataType: 'JSON', success: function (data) { .. }, .. console.log('error'); } }); });`Pirozzo
maybe if you can give me complete code base on my form i presented it would work.Pirozzo
sorry about that. I just scraped it in my old code source.Courtesy
success: function (data) { console.log('success'); }, error: function (data) { console.log('error'); }Pirozzo
can you show me the error in your console. is their error 500 in the network or any error in yout console?Courtesy
did you use this code? url: "{{url('updatebyajax')}}" + '/' + this.id,Courtesy
Let us continue this discussion in chat.Courtesy

© 2022 - 2024 — McMap. All rights reserved.