Lluís Puig Ferrer
Lluís Puig Ferrer

Reputation: 1146

How to pass token in ajax post request laravel?

someone can show me how to pass all the data of one form in ajax on laravel?

I will put my an example, i can't pass it cause token miss.

Javascript code:

$(document).ready(function(){

    $("#buttoncreate").click(function(){
        $("#listall").hide();
        $("#form1").fadeIn(1000);

    });

    $("#createprojectsubmit").click(function(){
        $("#myForm").submit();
    });

    $("#myForm").submit(function(e){
        e.preventDefault();
        $.ajax({
            url:'/admin/projects/postUpload',
            type:'post',
            data:$('#myForm').serializeArray(),
            success: function(){
                $("#form1").fadeOut(1000);
                $("#form2").fadeIn(1000);
            }
        });
    });
});

Blade code:

@extends('cms.public.layouts.default')
@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">

<div class="col-md-10">
    <h3 style="letter-spacing:40px;text-align:center;color:f15d5e;">PROYECTOS</h3>
</div>

<div id="listall"> <!-- DIV TO LIST ALL THE PROJECTS START HERE -->
        <div class="col-md-2" style="padding:20px;">
          <button type="button" id="buttoncreate" class="btn btn-danger">Crear Proyecto</button>

        </div>
                      <table class="table">
                  <thead style="color:white">
                    <tr>
                      <th>Id</th>
                      <th>Slug</th>
                      <th>Order</th>
                      <th>Public</th>
                      <th>Path header</th>
                      <th>Path home</th>
                      <th>Fecha creación</th>
                      <th>Fecha ultima actualización</th>
                      <th><span class="glyphicon glyphicon-cog"></span></th>
                    </tr>
                  </thead>
                  <tbody style="color:white">
                  @foreach ($projects as $key => $project)
                    <tr>
                      <th>{{$project->id}}</th>
                      <td>{{$project->slug}}</td>
                      <td>{{$project->order}}</td>
                      <td>{{$project->public}}</td>
                      <td>{{$project->pathheader}}</td>
                      <td>{{$project->pathhome}}</td>
                      <td>{{ date('M j, Y', strtotime($project->created_at))}}</td>
                      <td>{{ date('M j, Y', strtotime($project->updated_at))}}</td>
                      <td><a href="{{ route('admin.projects.show', $project->id)}}" class="btn btn-info btn-sm">View</a> <a href="{{ route('admin.project.edit', $project->id)}}" class="btn btn-success btn-sm">Edit</a>
                  @endforeach
                    </tr>
                  </tbody>
                </table>
  <br><br>
</div>  <!-- DIV TO LIST ALL THE PROJECTS END HERE -->

<div id="form1" style="display:none;" class="col-md-8"> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 START HERE-->
    <div>
    <h3>Crear nuevo proyecto</h3>
    </div>
    <div id="formcreateproject">
        <form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data" id="myForm" name="myForm">
        {{ csrf_field() }}
          <div class="form-group">
            <label name="title">Slug:</label>
            <input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
            <label name="order">Order:</label>
            <input type="number" id="order" name="order" class="form-control form-control-sm">
            <label name="public">Public:</label>
            <input type="number" id="public" name="public" class="form-control form-control-sm">
             <label name="body">Header</label>
            <input type="file" name="pathheader" id="pathheader"  class="form-control-file" aria-describedby="fileHelp"><br>
            <label name="body">Home</label>
            <input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>

            <input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
            <input type="hidden" name="_token" value="{{ Session::token() }}">
            <br><br><br>

          </div>
        </form>

      </div>
</div> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 END HERE-->

<div id="form2" style="display:none;" class="col-md-6">
<div class="col-md-">
    <h3>Crear nuevo proyecto</h3>
    </div>
      <form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data">
          <div class="form-group">
            <label name="title">Slug:</label>
            <input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
            <label name="order">Order:</label>
            <input type="number" id="order" name="order" class="form-control form-control-sm">
            <label name="public">Public:</label>
            <input type="number" id="public" name="public" class="form-control form-control-sm">
             <label name="body">Header</label>
            <input type="file" name="pathheader" id="pathheader"  class="form-control-file" aria-describedby="fileHelp"><br>
            <label name="body">Home</label>
            <input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>

            <input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
            <input type="hidden" name="_token" value="{{ Session::token() }}">
            <br><br><br>

          </div>
        </form>
</div>

</div>
@stop

Any help will be appreciate a lot! I check others questions in stackoverflow but can't fix it, let's see if with my code someone can. If need more information please, ask it. The url function works!

Also i try

https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token

It only works if i put in the exception of middleware but i think it's not a good idea.

Upvotes: 2

Views: 5128

Answers (1)

Sletheren
Sletheren

Reputation: 2486

- Potential Fix N°1:

In your first form, delete the

 {{ csrf_field() }}

and Put this directly after <form>

<input type="hidden" name="_token" value="{{ Session::token() }}">

- Potential Fix N°2:

Make sure inside your config/session.php the value of domain is null.

and delete cache from storage/framework/sessions/ and storage/framework/views/

- Potential Fix N°3:

use {!! csrf_token() !!} instead of {{ csrf_token() }}

- Potential Fix N°4:

If on linux or mac, make sure the Session dir has permission: a sudo chmod -R 777 Storage will do the job.

- Potential Fix N°5:

Add to your master layout in the head:

<meta name="csrf-token" content="{{ csrf_token() }}">

and configure all your ajax requests to use the CSRF token, that way you don't need to attach it everytime in the forms u're submitting You can add as the first tag in your master layout.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

- Potential Fix N°6:

If all fails, then allow access-control by adding these lines into your VerifyCsrfToken.php middleware file.

$response->headers->set('Access-Control-Allow-Origin' , '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');

Upvotes: 3

Related Questions