Laravel 4: URL :: route vs jquery

(As a new laravel user) I am trying to create an ajax call url via laravel URL :: class:

$.ajax( { url: '{{ URL::route('getUser', ['3']) }}', success: function(results) { alert(results); } }); 

routes.php:

 Route::get('admin/getUser/{user_id}', array( 'as' => 'getUser', 'uses' => ' AdminController@getUser ' )); 

Instead of hard-coded 3 this parameter should come from jquery (for example, $(this).attr('user_id') ).

Can someone tell me how to create a URL dynamically?

It seems that because of the route definition, the function URL::route needs the hardcoded parameter or in the form of php varaible.

I hope this is +/- clear ...

Thanks for the help anyway!

+4
source share
3 answers

You can keep the URL clean and pass the variable as data in your ajax call.

 var urlGetUser = "{{ URL::route('getUser') }}", userId = $(this).attr('user_id'); $.ajax({ type: "POST", url: urlGetUser, data: { id: userId } }).done(function( msg ) { alert( msg ); }); 

This way you do not have to create ajax calls for all possible user IDs. Something and other current solutions also offer.

Disclaimer: A colleague of ajer without much experience at Laravel: /

+2
source

I use URL :: to () for my Ajax calls. I had some problems. But if you use URL :: to (), you can use javascript variables. try the following:

 $id = 3; "{{URL::to('getUser/'".$id.")}}" 

Hope this helps, I'm new too. if you find a better way to do this awesomely let me know;)

+1
source

Since PHP actually processes the file before passing it to the browser, it may not be possible to dynamically use the php variable directly, but this is the way around it. This can work ONLY if you did not specify the user_id route user_id for a specific definition.

 // Add a placeholder which we'll use jQuery to swap out later urlTo = "{{ URL::route('getUser', ['%userid%']) }}"; // swap out the placeholder dynamically using jQuery urlTo = urlTo.replace('%userid%', $('#someElement').attr('user_id')); $.ajax({ url: urlTo, success: function(results) { alert(results); } }); 

What we did here is to create a placeholder in our url created using the route, so we will probably have a url like http://localhost/app/profile/%userid% after processing PHP Then we use jQuery to replace the placeholder with our actual dynamic value.

+1
source

Source: https://habr.com/ru/post/1486022/


All Articles