简体   繁体   English

在Laravel中使用Ajax将数据插入MySQL

[英]Insert data to MySQL with Ajax in Laravel

I have a JS variable which store a JSON value in my blade view and I want to insert it to MySQL in Laravel project. 我有一个JS变量,它将JSON值存储在刀片视图中,我想将其插入Laravel项目中的MySQL中。 But I don't know how to write it right. 但是我不知道该怎么写。 This is what I tried in my blade view: 这是我在刀片视图中尝试的方法:

 <body> <div id="fb-editor"></div> <div id="saveToDatabase"> <button id="saveBtn" type="button">Save To Database</button> </div> </body> <script> var formBuilder = $('#fb-editor').formBuilder(); $("#saveBtn").click(function() { var mFormData = formBuilder.actions.getData(); //my JSON data $.ajax({ type: 'POST', url: '/saveToDatabase', data: {"mFormData":mFormData} }).done(function (msg) { alert("Data saved!"); }); }); </script> 

But when I run it, it appear error said: jquery.js:8630 POST http://localhost/saveToDatabase 404 (Not Found). 但是,当我运行它时,出现错误消息:jquery.js:8630 POST http:// localhost / saveToDatabase 404(未找到)。

How I can fix this? 我该如何解决?

Thank you very much! 非常感谢你!

First, enter your database details on .env file. 首先,在.env文件上输入数据库详细信息。

You need to use two routes. 您需要使用两条路线。 One for the blade file to render and another for the api request. 一个用于刀片文件呈现,另一个用于api请求。

On routes/web.php, define your route, 在route / web.php上,定义您的路线,

Route::get('/', function(){ return view('app');});

Create app.blade.php in resources/views/ folder with your HTML code. 使用您的HTML代码在resources / views /文件夹中创建app.blade.php。

On routes/api.php, define your route like this 在routes / api.php上,像这样定义您的路线

Route::post('saveToDatabase','HomeController@saveToDb')

Next, you need to create saveToDb method on the HomeController. 接下来,您需要在HomeController上创建saveToDb方法。

Open App\\Http\\Controller\\HomeController.php 打开App \\ Http \\ Controller \\ HomeController.php

Create a new method 创建一个新方法

public function saveToDb()
{
  // Database Insertion Code goes here

}

Laravel Provide CSRF Protection to the POST request. Laravel为POST请求提供CSRF保护。 So add Exception to this route by adding it in the App\\Http\\Middleware\\VerifyCSRFToken.php 因此,通过在App \\ Http \\ Middleware \\ VerifyCSRFToken.php中添加此路由,将异常添加到此路由

  protected $except = [
        'api/*'
    ];

For the insertion operation, we can do this with the help of the model. 对于插入操作,我们可以在模型的帮助下完成此操作。

So first create Form.php in App\\ folder. 因此,首先在App \\文件夹中创建Form.php。

Inside that, we specify the fields of the database. 在其中,我们指定数据库的字段。

<?php

use Illuminate\Database\Eloquent\Model;

class Form extends Model
{
    protected $fillable = [
        "key", "data"
    ];

    protected $hidden = [];

}

Next, we can use this model to insert data to the Form table. 接下来,我们可以使用此模型将数据插入到Form表中。

In your HomeController.php at the top 在顶部的HomeController.php中

use App\Form;
use Request;

Now we can update the saveToDb function that we write before. 现在,我们可以更新我们之前编写的saveToDb函数。

public function saveToDb()
{
  // Request all the post data
  $req = Request::all();    
  // From that post data store key and data part to form table
  Form::create($req);
}

If you have any issue in route, controller or model. 如果您在路线,控制器或型号方面有任何问题。 Refer Laravel official docs: https://laravel.com/docs/5.8/routing 请参阅Laravel官方文档: https ://laravel.com/docs/5.8/routing

And this one is also useful to get started to laravel. 而且这对于入门laravel也很有用。 https://laracasts.com/series/laravel-from-scratch-2018 https://laracasts.com/series/laravel-from-scratch-2018

The route is not selected correctly. 路由选择不正确。 http://localhost/saveToDatabase is not find for do something 找不到http:// localhost / saveToDatabase做某事

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM