Home > OS >  How do I redirect with ajax to a dynamic link in laravel
How do I redirect with ajax to a dynamic link in laravel

Time:01-07

I'm trying to return a view with some data in it with ajax

I tried like this:

            $.ajax({
            url: '/canvas',
            data:{
                size:data.drawing['canvas_size'],
                name: data.drawing['name'],
                id: data.drawing['id']
            }
           });`

and this is the route:

Route::get('canvas/{size}/{name?}/{id?}',[DrawingController::class,'canvas'])->name('canvas');

it just gives the 404 error,can you help me please?

CodePudding user response:

Either send the data in the uri using the route

Route::get('canvas/{size}/{name?}/{id?}',[DrawingController::class,'canvas'])->name('canvas');

like this

.ajax({
    url: '/canvas/'  data.drawing['canvas_size']   '/'   data.drawing['name']   '/'    data.drawing['id'],
});`

Or send the data in the body / url query string using the route

Route::get('canvas',[DrawingController::class,'canvas'])->name('canvas');

using

$.ajax({
    url: '/canvas',
    data:{
        size:data.drawing['canvas_size'],
        name: data.drawing['name'],
        id: data.drawing['id']
    }
});

and get the variable inside your controller with

DrawingController

public function canvas($request)
{
    $size = $request->size;
    $name = $request->name;
    $id = $request->id;

    //...
}

CodePudding user response:

Note: This answer will only work in a blade.php file.

Route parameters are used for readable urls. Do this your request with request GET parameters. So update your route:

Route::get('canvas',[DrawingController::class,'canvas'])->name('canvas');

And use:

url: "{{ route('canvas') }}"

You can also follow a directive like this if you want to use it with route parameters. But putting variables from javascript here can mess things up:

url: "{{ route('canvas', [$var1, $var2, $var3]) }}",
  • Related