1

I'm not sure what's happening with this but when my ajax call is made to my php controller method, I'm getting a 500 error and I'm wondering if it's possibly a data type error or just simply syntax.

The value I'm passing from my form input through tha ajax call and into my function is being passed into a url endpoint in my service.php file.

The ajax itself is calling the function successfully but I can't verify the results from my $searchResults in the function because it seems to fail at the point of passing.

I started typing Test into my input with a breakpoint in the browser and it showed the value for my input as "T". Should I need to strip quotes or anything like that if it's being used in the query of the endpoint?

What else does it look like I could be doing wrong here?a

service.php

public function getSearch($query)
    {
        return $this->get("/search/search?query={$query}" );
    }

I also set a new route for the controller and function

Route::post('autocomplete','Controller@autoComplete');

controller.php

public function autoComplete(Request $request)
{

   $search_result = $request->search_result;

   $service = new service();

   //$search_result = "test"; /*this hard coded value works for passing*/
    $searchResults = $service->getSearch($search_result);

    return $searchResults;
}

view.blade.php

$('#productInput').on('input', function(){
if($(this).val() === ''){
   return;
}else{

   const searchResult = $(this).val(); 

   $.ajax({ url: '/account/autocomplete', 
            data: {
                'search_result':searchResult
            },
            type: 'POST', 
            success: function(response){
                console.log(response);
            }
        });
    }

});
Geoff_S
  • 4,917
  • 7
  • 43
  • 133

1 Answers1

3

Add this to your head

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

and pass the token to ajax:

$('#productInput').on('input', function(){
if($(this).val() === ''){
   return;
}else{

   const searchResult = $(this).val(); 

   $.ajax({ url: '/account/autocomplete', 
            data: {
                'search_result':searchResult
            },
            "_token": "{{ csrf_token() }}", // **** THIS LINE IS ADDED ***** //
            type: 'POST', 
            success: function(response){
                console.log(response);
            }
        });
    }

});

I take the ajax part from this answer, so thanks to Deepak saini. If this answer solved your problem, give his answer a plus.

Rouhollah Mazarei
  • 3,969
  • 1
  • 14
  • 20