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);
});
}
Related
I'm trying to create href with route laravel. This route contains a parameter, but it always returns Error 404. I don´t know what I´m doing wrong.
I know that my question is very easy, I´m searching in Google for this, but I think that I'm doing well on my route.
My route:
/** SHOW EVENT INFO */
Route::get('event/{url}', 'Web\EventController#showEvent');
My href in file.js:
<a target="_blank" id="button-event-read" href="'+config.url.base_url+'event/'+eventUrl+'" class="btn color2-bg float-btn">Leer más.<i class="fal fa-angle-right"></i></a>
If I click in href, it goes to the correct route but ends up showing Error 404.
My controller:
public function showEvent($url){
echo "here";
}
you can use route name
add a name to your route:
/** SHOW EVENT INFO */
Route::get('event/{url}', 'Web\EventController#showEvent')->name('MyRouteName');
and use the route name in href:
<a target="_blank" id="button-event-read" href="{{route('MyRouteName', 'MyParameter')}}" class="btn color2-bg float-btn">Leer más.<i class="fal fa-angle-right"></i></a>
Get Host url in variable
var url = window.location.protocol + "//" + window.location.host;
and then use it in href like this.
<a target="_blank" id="button-event-read" href="'+url+'/event/'+eventUrl+'" class="btn color2-bg float-btn">Leer más.<i class="fal fa-angle-right"></i></a>
I use October and I have made plugin with builder and I just add notification icon in menu.
I want to show "!" if there is a new item and hide "!" if user click that (it open bootstrap modal). And when I add new item it shows "!" again etc... I don't know exactly what is the best way to do this. Thank you if you can help me with this.
Menu:
<li>
<a data-toggle="modal" data-target="#itemModal"><i class="fa fa-bell"></i>
<span>! {{ Item }}</span></a>
</li>
Code:
function onStart()
{
$this['Item'] = Db::table('items')->count();
}
for this you need db table and you need to save last seen/click date.
so idea here is like you will add current date when user click !, you will show bootstrap modal and fire ajax request and set current date.
fire ajax request at that time and add new date for param.
for this you can use CMS default params table
<?php
use System\Models\Parameter;
....
// something like this in ajax request
Parameter::set('your_plugin_name::items.last_click_date', time() );
// this is when page reload
use System\Models\Parameter;
function onStart()
{
// now
$lastClickDate = Parameter::get('your_plugin_name::items.last_click_date');
if($lastClickDate == null) {
// first time it will just count items directly as user never click on icon
$count = Db::table('items')->count();
}
else {
// new this will call next time as user called that modal and we added click date
// so we compare if any record added after that date if it is then show `!`
$count = Db::table('items')->where('created_at', '>', $lastClickDate)->count();
}
$this['item_count'] = $count;
$this['new_items'] = $count > 0 ? true : false;
}
html
<li>
<a data-toggle="modal" data-target="#itemModal">
<i class="fa fa-bell"></i>
{% if new_items %}
<span>! {{ item_count }} </span>
{% endif %}
</a>
</li
please add comment if you face any problem.
I am a Laravel newbie. While writing and testing my code, I noticed that my destroy method isn't working right anymore and I cannot find the mistake I've made. So I hope you can help me out.
Whats my (software) target? I want to manage "projects". Every project has many reports. So I got a page with all created projects and I got a page with all reports listed in a table with buttons for "modify" and "delete". I finished all the CRUD stuff for projects and reports, when I recognized that, if I am hover over the delete-button of a report or project, the right ID of the chosen report or project is shown. If I am hitting the delete-button a dialog plopps up and a message is shown: "Do you really want to delete..." with "yes" and "no" buttons. So if I am pressing the "yes"-button Laravel is going to delete the last added database entry.
Even the projects as the reports too got their own controller. But both are using the same _messages.php. I think, that my mistake is in that file.
Excerpt from _messages.php:
#if(Session::has('sweet_alert.confirmDeleteReport'))
<div class="alert alert-warning" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div class="row">
<div class="col-xs-12">
<strong>Achtung!</strong> {{Session::get('sweet_alert.confirmDeleteReport')}}
</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-8">
<a class="btn btn-danger" href="{{ route('reports.destroy', $report->id) }}" title="Löschen" data-token="{{csrf_token()}}" data-method="delete">Löschen</a>
<a class="btn btn-default" data-dismiss="alert">Abbrechen</a>
</div>
</div>
</div>
#endif
Excerpt from reportcontroller.php:
public function destroy(Report $report)
{
$report->delete();
Session::flash('sweet_alert.success','Der Bericht vom ' . $report->date . ' mit der Berichtsnummer ' . $report->reportNumber . ' wurde erfolgreich gelöscht.');
return redirect()->route('reports.index');
}
public function delete(Report $report) {
Session::flash('sweet_alert.confirmDeleteReport', 'Soll der Bericht vom ' . $report->date . ' mit der Berichtsnummer ' . $report->reportNumber . ' wirklich gelöscht werden? Dieser Vorgang kann nicht rückgängig gemacht werden.');
return redirect()->route('reports.index');
}
Might there be the fault within the session? I flushed the cache by executing php artisan config:cache but with no luck. Every idea is welcome.
Greetings
If I understand correctly you have a page which lists all reports. Each report has a delete button, and that button route maps to the delete() method you include above. That method flashes a msg to the session, and reloads your report index.
Now on your report index, all reports are listed again, probably inside something like #foreach ($reports as $report). At the bottom of the page, you have the extract you have shown. This uses $report->id, which on this page, after looping through all $reports, is just the last report in that collection. So all it will do is delete the last report.
There are a few solutions I can see:
1) Flash the id of the report you want to delete along with your message in the delete() method. I am not familiar with sweet_alert but can you flash an array, your msg and the id? Something like:
Session::flash('sweet_alert.confirmDeleteReport', [
'id' => $report->id,
'message' => 'Soll der Bericht ...'
]);
And then of course use that id in your alert:
<a class="btn btn-danger" href="{{ route('reports.destroy', Session::get('sweet_alert.confirmDeleteReport.id')) }}" ... </a>
Maybe the syntax is wrong, but I am assuming flashing an array is possible.
2) The way I usually do this kind of thing is use Javascript to populate the alert/modal/whatever with the required data when you click the delete button in the table. Eg your delete buttons (in the main table/list) could have a data-id attribute:
Delete
And some Javascript (pseudo code, implementation depends on how you have things set up):
$('a.delete').on('click', function(e) {
// Prevent the default behaviour of clicking a link
e.preventDefault();
// Find the id of the report clicked
var id = $(this).data('id');
// Update the href of the alert button so it will delete *that* report
$('div.alert a.danger').attr('href', 'reports/' + id);
// ... code to display the alert/modal
});
This way you avoid the page reload to get to your alert/modal. Note this makes your delete() method obsolete, it would not be used any more.
UPDATE
If you need to pass some variable from your view/controller to your external JS file, you can do something like this:
In the view
<script>
var url = "{{ route('reports.destroy', Session::get('sweet_alert.confirmDeleteReport.id')) }}";
</script>
In your external JS (must be loaded after the above inline script)
$('div.alert a.danger').attr('href', url);
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();
<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