0

I'm not familiar that much with jquery/ajax and will appreciated some help. I'm trying to make simple ajax search which make curl request and return the result. Everything works fine if I don't use ajax for the search.

This is my controller

function get_curl_content_tx($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

public function getImage(Request $request)
{

$url = get_curl_content_tx('http://example.com/par?url='.$request->input('url'));
$items = json_decode($url, true);
$thumb = $items['thumbnail_url'];

    return view('getImage',compact('thumb'));
}

And here is the form in the blade view

    <div class="container">
        <form method="post" action="getImage" role="form">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <input type="text" id="url" name="url" class="form-control" placeholder="Paste URL.">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <button class="btn btn-success" id="submit">Search</button>
                    </div>
                </div>
            </div>
        </form>

        @if(!empty($thumb))       
            <img src="{{ $thumb }}" style="margin-bottom: 15px;">       
        @else                                              
            <p>There are no data.</p>            
        @endif
    </div>

And this is what I've made for ajax and which I think isn't work

$(document).ready(function() {
    $('#submit').on('submit', function (e) {
        e.preventDefault();
        var url = $('#url').val();
        $.ajax({
            type: "POST",
            data: {url: url},
            success: function( msg ) {
                $("#ajaxResponse").append("<div>"+msg+"</div>");
            }
        });
    });
});

Currently when I press search button the error is

TokenMismatchException

I'm using Laravel 5 and I'm not sure how to do it into laravel

Jason Paddle
  • 1,095
  • 1
  • 19
  • 37
  • 1
    You need to add `csrf_token` in post method – Sagar Gautam Jun 30 '17 at 11:15
  • Okay, I've made it like in this answer https://stackoverflow.com/a/37912362/1158599 but still TokenMissmatch – Jason Paddle Jun 30 '17 at 11:18
  • 1
    Take a moment to view this question might solve your problem https://stackoverflow.com/questions/44819418/ways-to-prevent-tokenmismatch-exception-in-ajax#44819418 – Sagar Gautam Jun 30 '17 at 11:19
  • 3
    Possible duplicate of [Laravel csrf token mismatch for ajax POST Request](https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request) – Niklesh Raut Jun 30 '17 at 11:20

3 Answers3

2

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a HTML meta tag:

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

Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

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

With in your ajax call add this:

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

and try again.

Reference

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
1

You can try this solution.

Add meta tag in Header.

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

While you also need to add this in script.

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

This will resolve your issue in laravel 5.

Saurabh Parekh
  • 441
  • 1
  • 3
  • 11
1

You can try this:

you could add it one time in ajaxSetup and it will affect all calls to $.ajax or Ajax-based derivatives such as $.get() :

$.ajaxSetup({
    headers:
    {
        'X-CSRF-Token': $('input[name="_token"]').val()
    }
});
linktoahref
  • 7,812
  • 3
  • 29
  • 51
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57