skip to Main Content

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}', 'AppHelpersHelper@getItemDetails');

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. try this

    Route::get('/helpers/get-item details/{id}','AppHelpersHelper@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 do something like this,

    var code = 100390; //whatever your code is
    var url = '{{ route("yourRouteName", ":code") }}';
    url = url.replace(':code ', code );
    

    and in ajax

     url: url,
    

    you can also read here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search