AJAX in the Laravel

Asked

Viewed 488 times

1

I am trying to send data to my controller using AJAX but am getting the following error:

AJAX error: error : Not Found

What can I be doing to solve this problem?

follows the codes:

route:

Route::post('/update/{postdata}', 'ReportsController@updateReport');

controller:

    public function updateReport()
{   

    dd('Chegou no controller');

    }

Javascript:

<script>
                          function mudar(obj){
                          var selecionado = obj.checked;
                          if (selecionado) {
                            var id = '1';
                            $.ajax({
                            method: 'POST', // Type of response and matches what we said in the route
                            url: '/update', // This is the url we gave in the route
                            data: {"_token":"{{csrf_token()}}", 'id' : id}, // a JSON object to send back
                            success: function(response){ // What to do if we succeed
                                console.log(response); 
                            },
                            error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                                console.log(JSON.stringify(jqXHR));
                                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                            }
                            });
                            alert('fechado');
                          } else {
                            alert('aberto');
                          }
                          }
                      </script>
  • 2

    The route needs a parameter /update/{postdata} in your ajax you’re only sending update.

1 answer

0

Hello one way you can do this is by using Axios which is an http client created in js. but if I just say it will become very vague then I’ll make a very simple example.

Step 1: Create a model and its respective Migration

php artisan make:model Report -m

Step 2: put some data into your Migration

//não esqueça de importar sua model se for inserir aqui, sem criar seeders
public function up()
    {
        Schema::create('reports', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });

        Report::create([
            'name' => 'Jão das Goiabas',
            'description' => 'João planta goiabas vermelhas que são saborosas',
        ]);
        Report::create([
            'name' => 'Zézinho das mangas',
            'description' => 'Zezinho compra manga para sua família',
        ]);


    }

Step 3: Run the Migration.

php artisan migrate

Step 4: let’s create our routes, I put the creation methods on the routes, but note that this is an example, do this on your controller

use \App\Report;
use Illuminate\Http\Request;

Route::get('/', function () {
    $reports= Report::all();
    return view('crud')->with('reports', $reports);
});

//--CREATE a Reports--//
Route::post('/reports', function (Request $request) {
    $report= Report::create($request->all());
    return Response::json($reports);
});

Now that we have this data we go to the js

Step 5: Download or use a DN AXIOS

Step 6: file for Ubmit form, this file will be crud.blade.php

<heade>
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- outros imports pertinents -->
</heade>
<div>
<form enctype="multipart/form-data">
<div>

    <input type="text" id="name" name="name"
        placeholder="Enter name" value="">

</div>

<div>
<div>
    <input type="text" id="description" name="description"
        placeholder="Enter Description" value="">
</div>
</div>
</form>
</div>
<div>
<button onclick="saveData()" id="btn-save" value="add"></button>
</div>
<script src="{{url('seu_arquivo_axios')}}"></script>

Step 7: creation of js

axios.defaults.headers.post['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
saveData = function () {
    let selectReportName = document.querySelector('input[name="name"]')
    let reportName = selectReportName.value
    let selectDescription = document.querySelector('input[name="description"]')
    let description = selectDescription.value
    axios.post('/reports', {
            name: reportName,
            description: description
        })
        .then(function (response) {
            if (response.status == '200') {
                window.location.href = "/"
            }
        })
        .catch(function (error) {
            console.log(error);
        });
}

that should work. Inspiration link: crud ajax Laravel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.