如何提交切换数据以通过Ajax更改我的mysql中的布尔值的状态?
问题描述:
I would like to change the status of my boolean in my msql5.7 when I click a button in my view.
I want that when I click on my button, the value of my boolean is switched( toggled between 0 and 1)
Here is my ajax code (my Dashboard.blade.php)
function reply_click(clicked_id){
$(function() {
$('#openButton').on('click', function(data) {
$.get("test.php", {clicked_id);
});
});
}
my DashboardController.php
class DashboardController extends Controller
{
public function index() {
return view('dashboard');
}
}
my migration file
public function up()
{
Schema::create('chaves',function (Blueprint $table){
$table -> increments('id');
$table -> string('nome');
$table -> boolean('alugado');
$table -> timestamps();
});
}
my route
Route::get("dashboard", "DashboardController@index")->name("dashboard")->middleware('auth');
当我单击视图中的按钮时,我想在msql5.7中更改布尔值的状态。 p>
我希望当我点击我的按钮时,我的布尔值会切换(在0和1之间切换) p>
这是我的ajax code(my Dashboard.blade.php) p>
function reply_click(clicked_id){
$(function(){
$('#openButton')。on(' 单击',函数(数据){
$ .get(“test.php”,{clicked_id);
});
});
}
code> pre>
\ n my DashboardController.php p>
class DashboardController扩展Controller
{
公共函数索引(){
返回视图('dashboard');
}
}
code> pre>
我的迁移文件 p>
public function up()
{
Schema :: create('chaves',function(Blueprint $ table){
$ table - > increments('id');
$ table - > string('nome');
$ table - > boolean( 'alugado');
$ table - > timestamps();
});
}
code> pre>
我的路线 p>
Route :: get(“dashboard”, “DashboardController @ index”) - > name(“dashboard”) - > middleware('auth');
code> pre>
div>
答
JQuery
function reply_click(clicked_id){
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#openButton').on('click', function(data) {
$.ajax({
type: "PATCH",
url: "/dashboard"
})
.done(function(data){
console.log(data);
})
.fail(function(data){
console.log('Error:', data);
});
});
});
}
Controller
use App\Chave; //use this if you have model
use Illuminate\Support\Facades\DB; //use this if you don't have model
class DashboardController extends Controller
{
public function index() {
$dashboard = Chave::first(); //use this if you have model
$dashboard = DB::table('chaves')->first();
$dashboard->alugado = 1;
$dashboard->save();
return view('dashboard');
}
}
Router
Route::patch("dashboard", "DashboardController@index")->name("dashboard")->middleware('auth');
I think that you have to use method Patch and not using Get in your router.. because in this case, you are trying to do update but not update all..
Put method is used to update partial resource
答
$(document).on('click', '.update', function() {
var user_id = $(this).attr("id");
function () {
$.ajax({
url: "{!! url('your_url' ) !!}" + "/" +id,
method: "POST",
data: {id: id, "_token": "{{ csrf_token() }}", _method: 'PATCH'},
success: function (data) {
}
});
},
function () {
return false;
});
});