ashkovg
ashkovg

Reputation: 47

Pass JSON data from JavaScript in view to controller in laravel

I have a web application where I fetch JSON data from a database table, edit it, and want to ultimately insert it back into the database.

tree.blade.php

@extends ('layout')

@section ('content')
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://d3js.org/d3.v5.min.js"></script>

  </head>
  <body>

    <!-- echo JSON data from model to js variable -->
    <script type="text/javascript"> var treeData = <?php echo $family->family_tree ?>; </script>

    <!-- main js file where treeData is edited -->
    <script type="text/javascript" src="{{ asset('js/main.js') }}"></script>

  </body>
</html>
@endsection

Family.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Family extends Model
{
    protected $table = 'families';
}

FamiliesController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use DB;
use App\Family;

//fetch first row from table and pass it to view
class FamiliesController extends Controller {
  public function showTree() {
      $family = Family::where('id', 1)->firstOrFail();

      return view('tree', [
        'family' => $family
      ]);
  }
}

?>

web.php

<?php
use Illuminate\Support\Facades\Route;

Route::get('/tree', 'FamiliesController@showTree');
?>

So my question is: how can I pass the JSON data from treeData to the controller, and then to update the value in the database table? Is there a 'best practice' in doing this?

While googling for solutions I found mainly two ways:

  1. Sending the data with AJAX using XMLHttpRequest, but I found that it needs a link to a php file in which the data is received. But how would that work with laravel structure?
  2. Using an HTML form and a Route::post(..); but apparently laravel v7 doesn't support the Form class...

Upvotes: 0

Views: 1492

Answers (1)

gharabat
gharabat

Reputation: 177

simple XHR request using Axios would do it:

axios.post('/your-route-that-will-handle-the-data', {
  data: {
    json_var // you json data goes here
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
})
.then(function () {
  // always executed
});  

Now Axios use XmlHTTPrequest under the hood, and i would recommend for its easy to use syntax

Upvotes: 1

Related Questions