0

I have an AJAX request which is a GET request.

/**
 * AJAX Like function
 */
$(".like").click(function (e) {
    e.preventDefault(); // you dont want your anchor to redirect so prevent it
    $.ajax({
        type: "GET",
        // blade.php already loaded with contents we need, so we just need to
        // select the anchor attribute href with js.
        url: $('.like').attr('href'),
        success: function () {
            if ($('.like').hasClass('liked')) {
                $(".like").removeClass("liked");
                $(".like").addClass("unliked");
                $('.like').attr('title', 'Like this');
            } else {
                $(".like").removeClass("unliked");
                $(".like").addClass("liked");
                $('.like').attr('title', 'Unlike this');
            }
        }
    });
});

Where the URL is: http://127.0.0.1:8000/like/article/145

And is grabbed via the href attribute of .like, the markup of which looks like this:

<div class="interaction-item">

    @if($article->isLiked)
    <a href="{{ action('LikeController@likeArticle', $article->id) }}" class="interactor like liked" role="button" tabindex="0" title="Unlike this">
    @else
    <a href="{{ action('LikeController@likeArticle', $article->id) }}" class="interactor like unliked" role="button" tabindex="0" title="Like this">
    @endif
        <div class="icon-block">
            <i class="fas fa-heart"></i>
        </div>
    </a>

</div>

The LikeController looks like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Like;
use App\Article;
use App\Event;
use Illuminate\Support\Facades\Auth;

class LikeController extends Controller
{
    /**
     * Display all liked content for this user
     */
    public function index()
    {
        $user = Auth::user();

        $articles = $user->likedArticles()->get();
        $articleCount = count($articles);

        $events = $user->likedEvents()->get();
        $eventCount = count($events);

        return view('pages.likes.index', compact('articles', 'articleCount', 'events', 'eventCount'));
    }

    /**
     * Handle the liking of an Article
     *
     * @param int $id
     * @return void
     */
    public function likeArticle($id)
    {
        // here you can check if product exists or is valid or whatever
        $this->handleLike(Article::class, $id);

        return redirect()->back();
    }

    /**
     * Handle the liking of an Event
     *
     * @param int $id
     * @return void
     */
    public function likeEvent($id)
    {
        // here you can check if product exists or is valid or whatever
        $this->handleLike(Event::class, $id);

        return redirect()->back();
    }

    /**
     * Handle a Like
     * First we check the existing Likes as well as the currently soft deleted likes.
     * If this Like doesn't exist, we create it using the given fields
     *
     *
     * @param [type] $type
     * @param [type] $id
     * @return void
     */
    public function handleLike($type, $id)
    {
        $existingLike = Like::withTrashed()
        ->whereLikeableType($type)
        ->whereLikeableId($id)
        ->whereUserUsername(Auth::user()->username)
        ->first();

        if (is_null($existingLike)) {
            // This user hasn't liked this thing so we add it
            Like::create([
                'user_username' => Auth::user()->username,
                'likeable_id'   => $id,
                'likeable_type' => $type,
            ]);
        } else {
            // As existingLike was not null we need to effectively un-like this thing
            if (is_null($existingLike->deleted_at)) {
                $existingLike->delete();
            } else {
                $existingLike->restore();
            }
        }
    }
}

I think it's extremely bad practice to update a database via a GET request

So, I changed the Route to use POST and updated the AJAX call to:

/**
 * AJAX Like function
 */
$(".like").click(function (e) {
    e.preventDefault(); // you dont want your anchor to redirect so prevent it
    $.ajax({
        type: "POST",
        // blade.php already loaded with contents we need, so we just need to
        // select the anchor attribute href with js.
        url: $('.like').attr('href'),
        data: {
            _token: '{{ csrf_token() }}'
        },
        success: function () {
            if ($('.like').hasClass('liked')) {
                $(".like").removeClass("liked");
                $(".like").addClass("unliked");
                $('.like').attr('title', 'Like this');
            } else {
                $(".like").removeClass("unliked");
                $(".like").addClass("liked");
                $('.like').attr('title', 'Unlike this');
            }
        }
    });
});

As you can see, I've changed the method and added in the CSRF token, however, I get an error:

POST http://127.0.0.1:8000/like/article/145 419 (unknown status)
send @ app.js:14492
ajax @ app.js:14098
(anonymous) @ app.js:27608
dispatch @ app.js:10075
elemData.handle @ app.js:9883
app.js:14492 XHR failed loading: POST "http://127.0.0.1:8000/watch/article/145".

What is the best way to debug what's going on?

Update

By adding: <meta name="csrf-token" content="{{ csrf_token() }}"> would it interfer with my normal use of `@csrf' in my forms?

Also, I added a fail callback to the request

}).fail(function (jqXHR, textStatus, error) {
    // Handle error here
    console.log(jqXHR.responseText);
});

Another update

As you have all kindly pointed out, in the documentation here, it does indeed say, set the meta CSRF attribute, I even had an error in my console saying this wasn't defined, but I misinterpreted the error.

Why though, in some tutorials, do people add the CSRF token to the data array?

Jesse Luke Orange
  • 1,949
  • 3
  • 29
  • 71

2 Answers2

3

Look at this. You can't use {{ csrf_token() }} in your JS.

Try this in your html :

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

And this in your JS :

headers: {
   'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
  • I saw this in the documentation but every video tutorial I saw sent the token in the data array. Why is this? – Jesse Luke Orange Jun 01 '18 at 09:35
  • You can also pass it the data array (not sure) but you need to have the meta and get in your js with `.attr` because `{{ csrf_token() }}` is a Laravel thing and you can't call it on your JS, Actually you are sending a string which contain `{{ csrf_token() }}` – Dessauges Antoine Jun 01 '18 at 09:37
  • Ah, so if I were to have dumped out the data variable, it literally would've been a string? I think I just need to go away and improve my JavaScript knowledge – Jesse Luke Orange Jun 01 '18 at 09:40
  • Yeah, it's a string. It's just you can't call PHP like `{{ csrf_token() }}` in your JS so it's not executed. It's why you need to pass by a html tag `meta` – Dessauges Antoine Jun 01 '18 at 09:41
  • @JesseOrange it's easy to understand: it is a PHP function (and it needs to be) that generates a token that is bound to your session. The examples show a version where the javascript is build in PHP (as a string). This is pretty ugly code, because generating JS in PHP is not needed at all. – online Thomas Jun 01 '18 at 09:52
  • So, where possible, keep things separate? – Jesse Luke Orange Jun 01 '18 at 10:06
1

If you have multiple ajax call in single file then you can do via this. The following code will working for all your AJAX requests.

Try this in your html :

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

And this in your JS :

$(document).ready(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
});
Dwarkesh Soni
  • 289
  • 3
  • 16