0

How can I update one field in MySQL table after user clicks on checkbox. I have this:

<div style="float: right"><input type="checkbox" class="tvSync" data-toggle="toggle" data-onstyle="success" onclick="myFunction({{$spot->spotid}})"></div>

and

function myFunction(id)
  {   
  var  spotid=spotid;  
    $.ajax({
      type:'post',
      url:'updateTvSync',
      data:{spotid: spotid},
      success:function(msg){
        console.log(msg)
 }
 });

}

I created the route /updateSync and included it in controller:

public function updateTvSync(Request $request)
    {
        $id = $request->spotid;

        TV::where('spotid', $id)->update(['delayed' => 1]);
    }

but when I click on checkbox nothing happens. Does this <div> need to be in form or am I missing something here?

2
  • have you checked what is in your actual html? as in inspect element and see if it actually inserted the $spot->spotid Commented Jan 17, 2018 at 10:10
  • Yes. I have onclick="myFunction(469871)" for example. Commented Jan 17, 2018 at 10:11

2 Answers 2

4
 var  spotid=spotid; 

should be

 var  spotid=id; 

spotid is undefined

Sign up to request clarification or add additional context in comments.

13 Comments

I fixed it but still nothing happens. Also I get nothing in console.
or data:{spotid: id}, and remove the extra var
If you put a console.log(id); as first line of the function, it should give a error or log in the console, either the function is not defined or the console.log shows
The onclick could be prevented by other js code, so yes it could be the problem
oh yeah that makes sense. Maybe make a listener like in SaurabhMistrys answer but instead of listening to 'click', listen to 'change' ?
|
0

try to give id to your checkbox and remove onclick function

<input id="{{$spot->spotid}}" type="checkbox" class="tvSync" data-toggle="toggle" data-onstyle="success">

Add this JQuery , you are calling wrong route /updateTvSync instead of /updateSync . in your ajax url.

<script>
$(document).on('click','.tvSync',function(){
  var id=$(this).attr('id');
  alert(id);

      $.ajax({
         type:'post',
         url:'/updateSync',
         data:{spotid: id},
         success:function(msg){
           console.log(msg)
         }
      });

 });
</script>

5 Comments

why would onclick be wrong? Ididn't see the url mistake :-)
I would not put the spotid in the id attr: there can be only one of the same id on a page! using data-spotid would be better
data-toggle="toggle"is preventing the ajax call. Any solutions?
just remove that
But I need it :D... I don't want to have simple checkbox but the one from bootstraptoggle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.