Home > Blockchain >  Unable to pass parameter through Ajax in Laravel using GET method
Unable to pass parameter through Ajax in Laravel using GET method

Time:11-16

I am trying to pass a parameter through Ajax using GET method in Laravel. For testing purpose, I am trying to get the same parameter value in the response. But the response I am getting is {code}.

$.ajax({
    type: "GET",
    url: "{{ url('helpers/get-item-details/{code}') }}",
    data: {
        code: 100390,
    },
    success:function(response) {
        console.log(response);
        $('input[name="hs_code"]').val(response.hs_code);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("Invalid response");
        console.log(jqXHR.responseText);
        alert(jqXHR.responseText);
    }
});

Controller:

class Helper
{
    public static function getItemDetails($itemId){            
        return $itemId;
    }
}

Not sure where it is going wrong. I tried to call the URL on the browser like following which returns the parameter value as expected.

helpers/get-item-details/100390

Thanks in advance for any help.

Route:

Route::get('/helpers/get-item-details/{id}', 'App\Helpers\Helper@getItemDetails');

CodePudding user response:

try this

Route::get('/helpers/get-item details/{id}','App\Helpers\Helper@getItemDetails')->name('yourRouteName');

you are passing your code statically so, you can use something like this

url: "{{ route('yourRouteName', 100390) }}",

and if you want to use dynamic code then you can define a data-herf attribute to your a tag or you can access the form attribuites in ajax like below.

data-href="{{ route('yourRouteName', $code) }}"

and then access like this

let url = $(this).attr('data-href');
url: url,

you can also read here

CodePudding user response:

Got the issue with my code at last. This code was working in another project for me. What I got wrong is in my controller. There I had to take the parameter as a Request object in the function definition. Instead I had set it as a variable.

Correct Controller Code:

class Helper
{
    public static function getItemDetails(Request $request){
        return $request->code;
   }
}

Thanks for all of your contribution.

  • Related