Adam Silva Adam Silva - 2 months ago 8
Ajax Question

Laravel 5 jQuery Using AJAX

I'm using Laravel 5 and I'm doing some filters on some collections in my controller. The problem is using AJAX to be the bridge between the blade template and Controller. Here is my jQuery code:

function listCreatedBy(str) {
$.ajax({
headers : {
'csrftoken' : '{{ csrf_token() }}'
},
url: '{{ url("search") }}',
type: "get", //send it through get method
data:{txt:str},
success: function(response) {
console.log("ola");
$('#results').html(response);
},
error: function(xhr) {
console.log(xhr);
}
});
}


Here is my route:

Route::get('/search/{txt}', 'PrestashopController@search')->name('search');


And here is my method in the controller:

public function search($searchText){
var_dump($searchText);

return "results"; //Just to see if it's returning correctly
}


This method is empty for now because I only want to see if I can complete the ajax code first. But it's returning a 404 code, Not Found. Any idea what I'm doing wrong?

Answer

Add this to your ajax call

headers : {
    'csrftoken' : '{{ csrf_token() }}'
}

edit

i see you use the route

Route::("/search/{txt}" ...

Witch corresponds to

http://example.com/search/random%20text

What is probably happening is that you're using the route wrong the ajax call you're making will create an uri like this

http://example.com/search/?txt=some%20text

try this

$.ajax({
      headers : {
         'csrftoken' : '{{ csrf_token() }}'
      },
      url: "{{ url("search") }}/" + encodeURIComponent(str),
      type: "get", //send it through get method
      success: function(response) {
        console.log("ola");
        $('#results').html(response);
      },
      error: function(xhr) {
        console.log(xhr);
      }
});