Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JoaoHamerski's avatar

Problem when using 'window.location.href' in JavaScript to get edit route

I'm using jQuery Ajax to update data, so i use window.location.href in 'url' parameter to get the route, and the method i set to patch, which is the same as my route file, but, seems jQuery is sending the wrong url, i don't understand why.

THE CURRENT URL: http://localhost:8000/clients/1/edit

THE ROUTE FILE:

Route::prefix('clients')->group(function() {
   Route::name('clients.')->group(function() {
       .
       .
       .
       Route::patch('/{client}/edit', 'ClientsController@update')->name('update'); 
    });
}

MY JAVASCRIPT CODE:

$("#btn-update").on('click', function(e) {
      e.preventDefault();
     
      // here i get the data object i need
      let data = getData($("input").is("[name=cpf]"), false);

      $.ajax({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        type: 'PATCH',
        url: window.location.href,
        data: data,
        success: function(data) {
          console.log(data.responseText);
        },
        error: function(data) {
          console.log(data.responseText);
        }
      });

But, here is the error i get:

PATCH http://localhost:8000/clients/1 405 (Method Not Allowed) 

It seems that Query is not sending the complete URL, it should send http://localhost:8000/clients/1/edit (the CURRENT URL), but just sends http://localhost:8000/clients/1

So, why this bug is happening? I already try to check the url using console.log(window.location.href) and it returns the right URL, but when i sendo via ajax jQuery parameter its sends wrong (without the 'edit' at the end), why?

0 likes
6 replies
jlrdw's avatar

url: window.location.href,

Use the route here, you don't need window.location.href, Use that if editing, and after complete you are redirecting somewhere.

JoaoHamerski's avatar

Route? Do you mean {{ route('route.name') }}? I already tried even hardcode the route, and jQuery just keeps returning the wrong URL, without the 'edit' in the end, i tried using axios too, but had the same problem.

JoaoHamerski's avatar

Just found the problem, it was on my controller, i was returning the route return redirect()->route('clients.show', $client); instead of a return response()->json(['redirect' => route(...)]) and redirect via JavaScript.

artcore's avatar

How about a different way to tackle this

<button id="btn-update" data-id="{{ $data->id }}"></button

$("#btn-update").on('click', function(e) {

const id = e.target.getAttribute('data-id');

$.ajax({
        url: `/client/${id}/edit`, //or {{ route('update', ['id'=>$data->id]) }} but mixing js and php should be avoided

Please or to participate in this conversation.