簡體   English   中英

Ajax表單數據未保存在數據庫中

[英]Ajax form data not saved in database

我試圖在Laravel-5.2中使用Ajax將用戶輸入保存到數據庫中。

這是我的route.php

Route::get('xxxxx/{task_id?}',function($task_id){
$task = App\XXXXX::find($task_id);

return response()->json($task);
});

    Route::put('xxxxx/{task_id?}',function(Request $request,$task_id){
        $task = App\XXXXX::find($task_id);

        $task->Name = $request->Name;//
        $task->Email = $request->Email;
        $task->Telephone = $request->Telephone;

        $task->save();

        return response()->json($task);
    });

在我看來,保存按鈕用作。

<div class="modal-footer">
   <button type="button" class="btn btn-primary" id="btn-save" value="update">Save changes</button>
       <input type="hidden" id="task_id" name="task_id" value="0">
</div>

使用本教程創建的我的js文件
我收到彈出窗口,“ Save按鈕不起作用。
這是怎么了 我是Ajax的新手。
提前致謝。

這是route.php

路線:: match(['get','post'],'my / save-data','MyController @ SaveData');

這是您的html:

保存更改

這是您的Controller文件:MyController.php

公共功能SaveData(Request $ request){$ input = $ request-> all();

  try{ // You can now use the Subscribe model without its namespace // as you referenced it by its namespace in a use statement. $subscribe = new Subscribe(); // If you want to use a class that is not referenced in a use // statement then you must reference it by its full namespace. $otherModel = new \\App\\Models\\Other\\Namespace\\OtherModel(); $otherModel = $input['Name']; $otherModel = $input['Email']; $otherModel = $input['Telephone']; // save $otherModel->save(); } catch (\\Illuminate\\Database\\Eloquent\\ModelNotFoundException $e) { \\Log::error( $e->getMessage(), $context ); } catch (Exception $e){ \\Log::error( $e->getMessage(), $context); } return response()->json( ['status'=>'success', 'message'=>'Completed successfully'] ); } 

這是您的Js文件:save.js

函數save(){getData = {name:“ value”,//來自get element
電子郵件:“ value”,//來自eliment電話:“ value” //來自eliment};

 $.ajax({ type: 'post', // POST Request url: 'localhost/my/save-data', // localhost/my/save-data // Url of the Route (in this case user/save not only save) data: getData, // Serialized Data beforeSend: function (xhr) { // Function needed from Laravel because of the CSRF Middleware var token = $('meta[name="csrf_token"]').attr('content'); if (token) { return xhr.setRequestHeader('X-CSRF-TOKEN', token); } }, success: function (data) { // Successfuly called the Controler // Check if the logic was successful or not if (data.status == 'success') { console.log('alles ok'); } else { console.log(data.msg); } }, error: function (data) { // Error while calling the controller (HTTP Response Code different as 200 OK console.log('Error:', data); } }); 

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM