My view Codeigniter is like this :
<form id="search_form_hotel" name="search_form" method="post">
...
</form>
...
<script>
...
$.ajax({
url: base_url + 'hotel_booking/hotel/search_hotel',
type: "post",
...
</script>
This :
url: base_url + 'hotel_booking/hotel/search_hotel',
hotel : controller name in laravel framework
search_hotel : method name in laravel framework
Whether it can call a function in the laravel controller from codeIgniter view?
Any help much appreciated
Cheers
No, you can not. Inject controller's function in views are completely outside of arquitectura. Also, laraval does not register the routes in the same way as codeigniter does.
In codeigniter the url pattern defines the structure of a controller, however in laravel you are need to register every route separately without taking in consideration the url format.
Related
in a component, I am getting data for a current user with Axios. I get URL for an avatar in this format: avatars/1/mNpxJNRrRPbbWSx0kuIL40JQJIF5SM5dscTq3zpv.jpeg
I need to insert it into Storage::disk("s3"). So how would I let the variable avatar in my component?
I tried like this: <img :src="'Storage::disk("s3")->url(' + this.user.avatar + ')'"> But I get an error...
Post 2022 answer:
It's best to use this package: https://github.com/tighten/ziggy
It allows you to use call route() in vue files.
2017 answer:
I'm not sure if you are using Storage in the blade view or the component. For clarity, one can't use the Storage facade in Vue components. It's only for Laravel.
You have two options: allow the component to accept a prop or create a Laravel route that returns the URL with the help of Storage facade.
#Option 1 - Prop passing
In your blade view,
<my-component :src="'{{ Storage::disk("s3")->url(' + this.user.avatar + ')' }}">
#Option 2 - Laravel route
Create a simple route, something like
Route::get('api/my-avatar', UserController#getAvatar')
In your the UserController
public function getAvatar()
{
return Storage::disk("s3")->url( auth()->user()->avatar );
}
and call that route from axios.
I'm using RESTful controller and passing variables (using forms) works just fine here.
Now for some reason I need to use simple link, created with action() and dedicated route for #create action.
My view creates few similar links with different parameters:
<a href="{!! action('\App\Http\Controllers\Admin\Franch\Category\SubCategoryController#create', array('mainCategoryName' => $mainCategoryName)) !!}">
It works, because I can see this in URL:
/create?mainCategoryName=some_sample_name
But the route doesn't pass variables to the #create action OR controller doesn't recieve it for somereason:
Route::get('admin/franch/sub_categories/create', ['uses' => 'Admin\Franch\Category\SubCategoryController#create');
I wonder how can I pass variables from views to specific controllers, using GET and POST methods?
And this is my #create controller:
public function create($mainCategoryName = false)
{
dd($mainCategoryName);
....
Which is always gives false.
Well You can create a function on the link and in that function user Ajax
$.ajax({
type: "POST",//Or Get
url: url,
data: {"var_name":variable},
success: success,
dataType: dataType
});
Now you can send you variables in the data. and then you can get value of the variable in your controller by:
Input::get('var_name');
It would be much better if you make all your "calculations" in the controller and pass a resulting value to the view like so
class SomeController() extends Controller
{
public function getView():View
{
$mainCategoryName = "fix";
$formUrl = action('\App\Http\Controllers\Admin\Franch\Category\SubCategoryController#create', array('mainCategoryName' => $mainCategoryName));
return view('view.show', compact('formUrl'));
}
...
Your mistake is in keeping meaningful data in the view, when the view should only have processed values:
<a href="{!! $formUrl !!}">
And if you really want to go "nuts", you can create a class that would generate HTML using a blade-view and the controller data and then you can execute this class in the controller to have your "partial" ready to be incorporated in a view as HTML. But not the other way round. Keep the calculations out of your views.
I am building a store locator for a website that I am building in Laravel. Since the blade file calls the js file tht is on the assests folder. It doesn't recognize the URL like this
$.ajax({
url: '{{ URL::action('getLocation') }}',
// ...
});
This is how I have my route.php
Route::post('/getLocation', array('as'=>'getLocation','uses'=>'FrontController#getLocation'));
So it doesn't find the file. How can I call this function in the ajax URL?
Here is a demonstration of how i would achieve this
I might be late here. This is just a sample code to help understand people
who visit this question. Hope this helps anyone who visits here.
in my routes.php i define a named route
Route::post('getLocation',array(
'as'=>'getLocation','uses'=>'FrontController#getLocation')
);
added name route as data-url in my somehtmlform.blade.php file
{!! Form::open() !!}
{!! Form::text('input-name',null,array('class'=>'form-control search-input','data-url'=> URL::route("getLocation") ))
{!! Form::close() !!}
my search.js file catches the data-url and use it as post url
$('.search-input').each(function(){
$(this).on('change',function (e) {
search(this)
});
});
function search(self) {
var query = $(self).val();
$.ajax({
url: $(self).attr('data-url'),
type: 'post',
data: {'q':query, '_token': $('input[name=_token]').val()},
success: function(data){
console.log(data);
},
error: function(data){
// Not found
}
});
}
You can use this package, it gives almost all laravel helper functions which can be used in js files too.
You may try this:
// Add this in your filtes.php file (feel free to store where you like)
View::composer('layouts.master', function($view) {
$ajaxUrl = json_encode(array('url' => URL::action('getLocation')));
$view->with('ajax', $ajaxUrl);
});
Add this in you master.blade.php file's (master layout) <head></head> section (place it before your js file):
<script>var ajax = {{ $ajax or 'undefined' }}</script>
Now you can use this as:
// ajax.url
console.log(ajax.url);
Read here, similar thing.
It looks like you're using the wrong method for generating the URL.
Try switching from URL::action() to URL::route().
URL::action() is used to generate a URL to a given controller action, but then you need to write it like this:
URL::action('FrontController#getLocation')
URL::route() generates a url to a route which is named in the route definition, using "as" => "routeName". In your case:
URL::route('getLocation')
Hope this helps!
If you call your ajax function from a .js file,
try to change the blade part '{{ URL::action('getLocation') }}' to '/getLocation'
or pass a full url like: 'http://domain.com/getLocation' and it should work.
in js file, you can't not use the Url::action for route
just do
url:"/getLocation"
I'm trying to make a custom page in the adminpanel of Prestashop where the shopowner can fill in his upcoming events that will appear in a column in the header.tpl page. The templates and controller are working so far, with a structure based on an answer here at Stack Overflow:
How to create a new page in prestashop admin panel?
Now I have made in the content.tpl (with the added custom JavaScript and CSS files) the form with the input fields. The next step is to send it to the controller to save it in the database. But I'm stuck this part. I can't find how I can nicely submit the form to the controller. First I tried it with an Ajax function but I couldn't find the right way. Also without Ajax no success.
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseUri + '?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data:{
processEvents: true,
ajax: 'true',
controller: 'AdminEvents',
token: static_token
},
//success: function(jsonData){
//}
});
This is an example of an Ajax function that I tried. My questions:
How does other tpl or js files receive the baseUri, where is that
variable set?
What is the function of the ?rand date and time in that line? A kind
of security token?
What is the url of the controller? Also the url when I use
I guess the processEvents : true and Ajax : true is for security
reasons and to check if the form is submitted by Ajax or not?
Why is it necessary to send the controller name?
Where does the token come from?
Questions about the controller:
Which (Prestashop default functions) can or do need to use? For
example:
if (Tools::isSubmit('name')){
etc.
if (Tools::getValue('create_account')){
etc.
Can I use that functions anywhere or maybe only in an Init function?
A lot of questions, feel free to answer only a part of it, I just need a good push in the right direction, searching and reading in the online documentation and on the internet doesn't brought me the solution and brainwashed me a little.
EDIT:
I made a little progress by myself:
Where does the token come from?
What is the url of the controller? Also the url when I use
With the tools getAdminTokenLite and the controller name I generated the controller url:
$token = '?controller=AdminEvents&token='.Tools::getAdminTokenLite('AdminEvents');
The url to post to is the token plus the domain, admin directory and index.php.
With the tool getValue I get the POST data like in PHP with $_POST["name"].
Tools::getValue('event_name')
So its working but I guess it can be better with other Presta default tools.
I know that it's very late to answer you, but for sure it will help other mates with same problem.
Here is an example about how to implement ajax calls in Prestashop 1.6 on Admin panel using ANY Controller from BackOffice (if you want also, you can use ajax.php controller, but I'm using for this AdminImportController() )
tpl part:
$('#mybtn').click(function(e) {
var data = $('#datalist').val();
// Ajax call with secure token
$.post( "{$current|escape:'html':'UTF-8'}&token= {$token|escape:'html':'UTF-8'}",
{ ajax: true, action: "MyFunction", mydata: data } );
});
And in admin controller side:
public function ajaxProcessMyFunction()
{
// Get param
$mydata = (int)Tools::getValue('mydata');
$answer = 0;
if( $mydata > 0 ) {
$this->importProfList = Db::getInstance()->executeS(
"SELECT * FROM .... LIMIT 1"
);
...
$answer = $someOperationResult;
}
// Response
die(Tools::jsonEncode(array(
'answer' => htmlspecialchars($answer)
)));
}
Tested and working like a charm.
Regards
I am trying to get the URL i see on my browser after i do an ajax request but the problem is that it changes the URL with the Ajax URL.
ex.
i am on domain.com/user/username
and the ajax URL that i call is in domain.com/posts/submit
when i echo $_SERVER['REQUEST_URI'] on the posts controller in submit function it will display the second URL and not the first... how can i assure and get the first inside the ajax function that its 100% valid and not changed by the user to prevent any bad action?
Thanks
There is HTTP_REFERER but I don't know if that works for javascript requests. Another problem of this: It won't work for all browsers.
You could try the following:
1.) As the user visits domain.com/user/username the current URL is saved with a token - let's say 5299sQA332 - into the database and the token is provided through PHP to Javascript
2.) The ajax request will send this token along with the other variables needed to the controller through POST
3.) In your ajax controller you search the database for the given token 5299sQA332 and there you have your first URL and you can be damn sure, that it hasn't been manupulated
:)
If I understand you correctly, you want to make sure the ajax call is coming from the page it is supposed to be on? In that case just pass a token with the call.
In the controller function set a token variable in session;
public function username() {
$this->session->set_userdata('ajax_token', time());
}
Then in the view with the js;
$.ajax({
url: '/user/username',
type: 'post',
data: 'whatever=bob&token='+<?php echo $this->session->userdata('ajax_token'),
success: function( data ) {
},
error: function( data ) {
}
});
Then in you form validation, do a custome callback to check they are the same.
Have you looked at CodeIgniter's Input Class ?
$this->input->get('something', TRUE);
i used javascript for it and it seems to work... hope not to have any problems in the future with it...
ps: i dont get why my other answer was deleted.. thats the answer anyway.