Viewed   107 times

I do an ajax call but I keep getting this error:

419 (unknown status)

No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this.

my call:

$('.company-selector li > a').click(function(e) {
     e.preventDefault();

     var companyId = $(this).data("company-id");


      $.ajax({
          headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {},
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });
  });

My route:

Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');

My controller method

/**
 * Fetches a company
 *
 * @param $companyId
 *
 * @return array
 */
public function fetchCompany($companyId)
{
    $company = Company::where('id', $companyId)->first();

    return response()->json($company);
}

The ultimate goal is to display something from the response in a html element.

 Answers

1

Use this in the head section:

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

and get the csrf token in ajax:

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

Please refer Laravel Documentation csrf_token

Tuesday, November 1, 2022
1

@Chris's comment is correct :)

You simply need to remove the / from the end of your url. Your ajax request should go to http://domain.com/backend/get_subdirectories.

The reason is, because within the public/.htaccess file it will 301 redirect all urls with a trailing slash to the same url without one. The code that does it is here:

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

Now the real issue is, the client will preform a GET request to the URL specified by the 301 redirect.

Wait! Why would it do this???

Well, we can look to RFC7231 for the answer. It says

6.4.2. 301 Moved Permanently

The 301 (Moved Permanently) status code indicates that the target
resource has been assigned a new permanent URI and any future
references to this resource ought to use one of the enclosed URIs.
Clients with link-editing capabilities ought to automatically re-link references to the effective request URI to one or more of the new
references sent by the server, where possible.

The server SHOULD generate a Location header field in the response containing a preferred URI reference for the new permanent URI. The
user agent MAY use the Location field value for automatic
redirection. The server's response payload usually contains a short
hypertext note with a hyperlink to the new URI(s).

  Note: For historical reasons, a user agent MAY change the request
  method from POST to GET for the subsequent request.  If this
  behavior is undesired, the 307 (Temporary Redirect) status code
  can be used instead.

A 301 response is cacheable by default; i.e., unless otherwise
indicated by the method definition or explicit cache controls (see
Section 4.2.2 of [RFC7234]).

Now what's interesting is the note at the bottom that specifies that the user agent MAY change the request method from POST to GET. And it seems most user agents from browsers to frameworks, seem to follow that rule.

Thursday, October 27, 2022
 
5

Try this

$.ajax({
  type: "POST",
  headers: {
  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
  url: "http://localhost/shago/register/submit",
  data: {// change data to this object
     _token : $('meta[name="csrf-token"]').attr('content'), 
     user_firstname:user_firstname
  }
  dataType: "text",
  success: function(resultData) { alert("Save Complete") }
});
Friday, September 2, 2022
 
4

I just removed the trailing slash in the Ajax request URL and everything worked as planned.

Thursday, August 25, 2022
 
2

Your backend code must include some explicit handling for OPTIONS requests that sends a 200 response with just the configured headers; for example:

if ($request->getMethod() == "OPTIONS") {
    return Response::make('OK', 200, $headers);
}

The server-side code also must send an Access-Control-Allow-Headers response header that includes the name of the token request header your frontend code is sending:

-> header('Access-Control-Allow-Headers', 'token')

but then why with Postman work fine?

Because Postman isn’t a web app and isn’t bound by the same-origin policy restrictions browsers place on web apps to restrict them from making cross-origin requests. Postman is a browser bolt-on for convenience of testing requests in the same way they could be made outside the browser using curl or whatever from the command line. Postman can freely make cross-origin requests.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS in contrast explains how browsers block web apps from making cross-origin requests but also how you can un-block browsers from doing that by configuring your backend to send the right CORS headers.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains why the browser is sending that OPTIONS request your backend needs to handle.

Thursday, November 10, 2022
 
janbom
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :