MUSTUFA
MUSTUFA

Reputation: 25

Send Request In Laravel Using AJAX GET Method

Want to Access Show function data through AJAX, but it returns error when i passed id variable in route

Contoller

public function show($id)
{
    $features['UnitFeatures'] = UnitFeatures::find($id);
    return $features;
}

View Blade File

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

var feature_id = $('#unitFeatures').val();

$.ajax({
    url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
    type: 'GET',
    dataType: 'json',
    success: function(response){
      console.log(response);
     }
    });
  });

Please give me a solution

Upvotes: 0

Views: 941

Answers (2)

Aless55
Aless55

Reputation: 2709

The problem is that you cannot access a JS variable in your {{}} PHP code. You will have to get the route uri and replace the placeholder manually in your JS code.

You can get the URI of your Route with this piece of code: \Route::getRoutes()->getByName('unitfeatures.show ')->uri

This returns the uri as a string like that: /sometext/{id}

Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.

var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
    url: origUrl.replace('{id}', feature_id), 
    type: 'GET',
    dataType: 'json',
    success: function(response){
      console.log(response);
     }
    });
  });

Upvotes: 2

Mayank Rai
Mayank Rai

Reputation: 49

Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.

$.ajax({
    url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
    type: 'GET',
    dataType: 'json',
    success: function(response){
      console.log(response);
     }
    });
  });

Upvotes: 0

Related Questions