ajax octobercms passing value of id - php

<button
type="button"
class="btn btn-small btn-danger icon-trash"
data-request="onDeleteItem"
data-control="popup"
data-request-data="id: " <<<<<<<----
data-trigger-action="enable"
data-stripe-load-indicator>
</button>
in Configurations.php::controller
public function onDeleteItem()
how do i get the value of id in a list? I want to list of all configs in a table, have an custom column, Edit, Delete
i want to click delete, then it will delete the item, but how do i get the ID?

I have used this (referenced from the RainLab.Blog plugin) and it works perfectly:
<button
class="btn btn-default oc-icon-trash-o"
disabled="disabled"
onclick="$(this).data('request-data', {
checked: $('.control-list').listWidget('getChecked')
})"
data-request="onDelete"
data-request-confirm="Are you sure?"
data-trigger-action="enable"
data-trigger=".control-list input[type=checkbox]"
data-trigger-condition="checked"
data-request-success="$(this).prop('disabled', false)"
data-stripe-load-indicator>
Delete all selected
</button>
You can see that this uses jQuery in the onClick handler to get all checked Ids and passes it to the controller.
Then in your controller you can do this:
public function index_onDelete()
{
if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {
foreach ($checkedIds as $modelId) {
if ((!$model = Model::find($modelId)))
continue;
$model->delete();
}
Flash::success('Successfully deleted those items.');
}
return $this->listRefresh();
}
Just make sure to replace model with your actual 'model'. The index_ prefix on the controller method name ensures that we refer to onDelete in the index context (where the list of your models is displayed).

If it's within a controller's action then
<?= $this -> id ?>
should work. Or else you can do something like
<?php
$isDelete = $this->formGetContext() == 'delete';
?>
to initialize it and then use it as
data-request-data="id: <?= (int) $isDelete ?>"
As seen here

Related

Not found page when clicked detail to get data based on id

I have been fixing this trivial problem a few days, but it didn't solve either.
When I click the detail button on the table, it will display a 404 or not found message.
Controller method
public function detail($id)
{
$data = DB::table('lirik_lagu')->where('id', $id)->first();
return view ('admin.detail-lirik');
}
Route
Route::get('lirik-lagu/detail/{$id}', [LirikLaguController::class, 'detail']);
Blade
<a class="btn btn-success btn-sm" href="{{ url('admin/lirik-lagu/detail', $data->id) }}">Detail</a>
I will try to fix what i think it's wrong in your code.
First you should give the $data to your blade file
Controller method
public function detail($id)
{
$data = DB::table('lirik_lagu')->where('id', $id)->first();
return view ('admin.detail-lirik',['data'=>$data]);
}
Second, your should omit the $ in your Route id parameters
Route
Route::get('lirik-lagu/detail/{id}', [LirikLaguController::class, 'detail']);
Third, when you generate the url url(...) it seems to have an admin prefix but not your route declaration.
Blade
<a class="btn btn-success btn-sm" href="{{ url('lirik-lagu/detail', $data->id) }}">Detail</a>
You are not passing the variable to the view. This is how you do it:
return view('admin.detail-lirik', $data);
If you need to pass multiple variables you can pass an array in the second paramter like this:
return view('admin.detail-lirik, ["varname" => $var]);
I see several problems here, so I'm going to point them out. First one, you never returned the data to your view:
return view ('admin.detail-lirik', $data);
The other is the URL in your blade file. You called admin/lirik-lagu/detail but you defined route without admin in your web.php file. You can remove the admin from your url, or create a name for your route and call it that way:
Route::get('lirik-lagu/detail/{$id}', [LirikLaguController::class, 'detail'])->name('lirik-langu');
And then use it like this
<a class="btn btn-success btn-sm" href="{{ route('lirik-langu', $data->id) }}">Detail</a>

laravel - make a search form and show result in same page

in my show method in laravel i have a form that i want to submit and show the result on the same page so here is my show method first of all :
public function show(Property $property)
{
$property = Property::with('propertycalendars')->where('id', $property->id)->first();
foreach ($property->propertycalendars as $prop) {
$end_reserve = $prop->reserve_end;
}
// HERE NEW RELATION
$pdate = Property::with('dates')->get();
return view('users.properties.show', compact('property','pdate','end_reserve'));
}
and in the view of my show which for example is the url of a uniq property like below just as an example :
http://localhost:8000/properties/1
now i have a form to submit to search the Date table and bring me the dates so here is what i have wrote for the search function :
public function search (Request $request,$property_id){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the search has something in it.
if (!empty($request->property_id)) {
$start_date = $request->start_date;
$search_date = Date::all()->where('date',$start_date);
}
return view('admin.properties.show')->with('search_date', $search_date);
}
and
thats my route :
Route::get('/properties/{{property_id}}','PropertyController#search');
and finally my form to submit the search :
<form action="/properties/search" method="get">
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<input type="hidden" value="{{$property->id}}" name="property_id">
<input name="start_date" class="form-control m-input start_date" autocomplete="off"> </div>
<div class="col-lg-5">
<input name="finish_date" class="form-control m-input start_date" autocomplete="off"> </div>
<div class="col-lg-2">
<input type="submit" value="seach" class="btn btn-primary btn-block" autocomplete="off">
</div>
</div>
</form>
but now when i submit the form it returns a 404 not found with a link like below :
http://localhost:8000/properties/search?_token=R8ncSBjeZANMHlWMcbC6o5mYJZfwWgdfTwuviFo1&property_id=1&start_date=1398%2F1%2F12&title=
In your controller, change to the following:
public function search (Request $request){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the search has something in it.
if (!empty($request->title)) {
$results = Property::all()->where('some search here')->get();
}
return view('admin.article.index')->with('results', $results);
}
This will send any (and all) results that your query finds to the view. Now in your view, you'll need to ensure there are actual results, or you'll get an error, so for example:
#if ($results)
//There are results, loop through them
#foeach($results as $item)
{{$item->title}}
#endforeach
#else
//There are no results, show the form maybe?
#endif
Without knowing your table structure, I can't give the exact way to loop through your results, but this should get you started.
Edit: Since OP's question nature changed a fair bit from the original question:
In order to achieve the new flow, you'd need to pass in a URL param in the route, and change it to be a get, since you're no longer posting it from a form:
Route::get('/properties/{search}','PropertyController#search');
This tells Laravel you've got something coming from a website.com/properties/xxxxx request - the xxxxx would contain the search key you'd then pass to your controller to lookup. The {search} portion in the route can be whatever name you want, just ensure the controller's second param matches it.
If you wanted to allow for a posting from your search form, you can (in addition) add the following to your routes:
Route::post('/properties','PropertyController#search');
Then in your controller, fetch whatever came from the form via the Request facade.
Then in your controller, you'd check if this is valid:
public function search (Request $request, $search){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the second URL param has a value
if (!empty($search)) {
$results = Property::all()->where('some search here')->get();
}
return view('admin.article.index')->with('results', $results);
}

How to populate view with database information after AJAX request

Hi there once again SO community. I've been developing a site and so far it's going pretty well. But today after a long day searching for a solution I can't understand nor find what the right path is...
I want to click on a button and a profile page where you can edit the fields appear. I can redirect to the page I want but I don't know how to send the user data so I can populate the fields.
Here is my button code on my view
<button class="btn btn-xs btn-warning dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false" style="border-color: black" id="dados_{{ $user->username }}"> Alterar Dados Pessoais
<i class="glyphicon glyphicon-cog"></i>
</button>
Here is the button AJAX request handler
if((this.id).indexOf("dados") != -1){
var content = this.id.replace("dados_", "");
$.get('callPermissions', {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
And here is my callPermission Controller
public function callPermissions(Request $request)
{
if($request->ajax()){
$usernames = Input::get('usernameSend');
if(isset($usernames)){
$user = User::Where('username', '=', $usernames)->first();
$returnHTML = view('userOptions.settings')->render();
return view('userOptions.settings');
}else{
Log::warning("Username não existe na base de dados.");
}
}
}
and here my Settings Controller
public function settings(Request $request)
{
return view('userOptions.settings');
}
And here is the route
Route::get('/callPermissions', 'SidebarController#callPermissions');
I know the controller is wrong and from what I've read I should verify if the AJAX is successful and if it is handle i on the AJAX request. But from what I've understand I'm not using the Controller at all (even though it goes there). How should I send the user information (in this case the username, then I can get everything from the database) and then send it to the view? I've been searching and trying out stuff that doesn't work...since the return view("your_view") on the Controller doesn't work.
Sorry if I've been confusing and if you need additional information feel free to ask!
Thanks for your help!!
Edit: If I return this on the controller
return view('userOptions.settings', compact('user'));
and do a replace with the Ajax request as show above and add this to the settings view
<p> {{ $user->name }} </p>
I get the following error Undefined variable: user (View: C:\wamp64\www\siteXL\ideiasxl\resources\views\userOptions\settings.blade.php)
Is there anyway to send the parameters with a compact alike or I need to send it through the link? Was avoiding to show the username on the url.
Edit2: For further clarification, this works as intended
<button onclick="window.location='{{url('/settings/' . $user->username)}}'" type="button" id="dadosPessoais" class="btn btn-default">Alterar Dados Pessoais
<i class="glyphicon glyphicon-wrench"></i>
</button>
but I was trying not to send id's and usernames through the URL.
If this is not achievable it's ok, but if there's a way I can't find it, that's why I'm asking
I think you have to add a parameter in the Route and receive the data in the controller function. I'd do something like this:
Route:
Route::get('/callPermissions/{user}', 'SidebarController#callPermissions');
Controller:
public function callPermissions(Request $request, $user)
{
//get data related to $user
}
Ajax call:
$.get('callPermissions/'+userIdVariable, {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
This would send the user id through the route.
To get the user id with JavaScript, you can make a hidden field in the Blade file and set the user id as the value. For example, if you using Form helper:
{{ Form::hidden('user_id', $user->id, array('id' => 'js-user-id')) }}
And then, in the JavaScript, you can get the value using something like this:
var userIdVariable = $('#js-user-id')->val();

Laravel 5 MethodNotAllowedHttpException

I am using a form with PATCH method and I have a button link(since i already have a submit button and using same form for both store and update) as
<a class="btn btn-default" href="{{ URL::to( 'pages/edit/' . $vehicle -> id) }}">EDIT</a>
And my route is
Route::patch('/pages/edit/{id}', ['uses' => 'VehicleProcessController#update']);
Controller
public function update($id)
{
$vehicle = Vehicle::find($id);
$input = Input::all();
$vehicle->update($input);
return $input;
}
When i click to link $input returns null and i am getting
MethodNotAllowedHttpException
I am trying to get familiar with L5, how can i fix this ? Any help would be appreciated.
Your <a> link will trigger a GET request, not a PATCH request. You can use JS to have it trigger a PATCH request, or use a <button> or <input type="submit"> to issue one.

Get correct index with Splice()

I'm attempting to delete items from my AngularJS view. From the view, I'm passing the index & the ID. In the JS controller, I splice(index) from the AngularJS array/model. And I pass the ID to a $http.get to call a delete to my database. This all works.
....
Until I make a request to refresh my page. Every 5 seconds I make a request to update the Angular model and I concat any new data to it. But what I'm finding is it screws up my index values. I assumed it was reordering my index: and reading this StackOverflow thread helped confirm that.
What would happen is that I push delete for the 3rd item on the page, and it deletes that ID from the DB. But it splices the wrong item from the page until I refresh the page.
How do I make sure that I'm always passing the correct index?
View
<li ng-repeat="new in news | filter:query | orderBy:orderProp">
<div class="newsitem" id="newspost{{new.id}}">
<h4 ng-model="news.title">{{new.title}} </h4>
<p ng-model="news.text">{{new.text}}</p>
<a class="btn btn-info" ng-click="visible = true">View article</a>
<a ng-click="deleteNews(index,new.id)" class="btn btn-danger btn-mini">Delete</a>
</div>
</li>
controllers.js
$scope.deleteNews = function(index, id) {
$http.get('/ci/index.php/news/delete_news_ajax/'+id).success(function(){
$scope.news.splice(index, 1);
});
};
Instead of passing the index and id, pass new:
<a ng-click="deleteNews(new)" ...>
Then use indexOf in your controller function:
$scope.deleteNews = function(newsItem) {
$http.get('/ci/index.php/news/delete_news_ajax/' + newsItem.id)).success(function() {
$scope.news.splice($scope.news.indexOf(newsItem), 1);
});
}

Categories