I am new to Laravel, and I am using this Jeffrey Way script to submit a DELETE request without a form.
My link:
<a class="btn btn-danger btn-sm delete" href="files/<?=$file->id?>" data-method="delete">
<i class="fa fa-check"></i> Yes I'm sure
</a>
The script, which for now is in the view file is as follows:
$(document).on("click", ".delete", function() {
var laravel = {
initialize: function() {
this.methodLinks = $('a[data-method]');
this.registerEvents();
},
registerEvents: function() {
this.methodLinks.on('click', this.handleMethod);
},
handleMethod: function(e) {
var link = $(this);
var httpMethod = link.data('method').toUpperCase();
var form;
// If the data-method attribute is not PUT or DELETE,
// then we don't know what to do. Just ignore.
if ( $.inArray(httpMethod, ['PUT', 'DELETE']) === - 1 ) {
return;
}
// Allow user to optionally provide data-confirm="Are you sure?"
if ( link.data('confirm') ) {
if ( ! laravel.verifyConfirm(link) ) {
return false;
}
}
form = laravel.createForm(link);
form.submit();
e.preventDefault();
},
verifyConfirm: function(link) {
return confirm(link.data('confirm'));
},
createForm: function(link) {
var form =
$('<form>', {
'method': 'POST',
'action': link.attr('href')
});
var token =
$('<input>', {
'type': 'hidden',
'name': 'csrf_token',
'value': '<?=csrf_token();?>' // hmmmm...
});
var hiddenInput =
$('<input>', {
'name': '_method',
'type': 'hidden',
'value': link.data('method')
});
return form.append(token, hiddenInput)
.appendTo('body');
}
};
laravel.initialize();
});
This is the exact script as pulled from the Gist, the only change I made is that I added the trigger $(document).on("click", ".delete", function().
The problem that I am running into is that when I click on the link to delete, I get sent to another page (like /files/6 or whatever the file id is). It is treating the <a> tag like a regular link as opposed to a DELETE request, as I would like to happen. Does anyone know why this is happening?
The default action for an anchor is to navigate, you will need to prevent it inside your click handler.
$(document).on("click", ".delete", function(e) {
e.preventDefault();
...
I found a solution - I had two issues.
First - you may need to include an additional slash in your href, for me I had to change
href="files/<?=$file->id?>" to href="/files/<?=$file->id?>"
Secondly, I was running into problems because my link was inside of a Bootstrap popover (within data-content) and this was further complicating matters. I reverted the script to the original one as provided by Jeffrey Way (using $(function() { instead of $(document).on("click", ".delete", function() {). Then I created a hidden link element outside of the popover:
And then I triggered a click on that link using jQuery (both elements were under parent <div class="panel-body">:
$(document).on("click", ".delete", function(){
$(this).closest(".panel-body").find(".delete-file").trigger("click");
});
Related
I'm using Laravel 5.8 and I'm trying to make a pagination using AJAX and it's working 50% of the time. Actually, when I click on the links page at the bottoms, it renders the data perfectly, but my problem is that, the second time I press a pagination link at the bottom, it resfreshes the page. I don't want the page to reload half the time I click on pagination pages.
Here's my code for that:
ManagerController.php
public function index()
{
$users = User::paginate(30);
if (Request::ajax()) {
return Response::json(View::make('manager.usersTable', compact('users'))->render());
}
$user = User::find(Auth::user()->id);
$leagues = League::all();
$usersCount = DB::table('users')->count();
return view('manager.index', compact('user', 'leagues', 'users', 'usersCount'));
}
index.blade.php
$(window).on('hashchange', function() {
if (window.location.hash) {
var page = window.location.hash.replace('#', '');
if (page === Number.NaN || page <= 0) {
return false;
}else{
getData(page);
}
}
});
$(document).ready(function() {
$('.leagueModal').on('shown.bs.modal', function (event) {
var href = $(this).find('#href_link').val();
$(this).find('#leagueModalBtn').click(function() {
window.location.href = href;
});
});
$('.pagination a').on('click', function (e) {
e.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var page = $(this).attr('href').split('page=')[1];
getUsers(page);
});
});
function getUsers(page) {
$.ajax({
url : '?page=' + page,
type: 'GET',
dataType: 'json',
}).done(function (data) {
$('.usersTable').empty().html(data);
location.hash = page;
}).fail(function () {
console.log('Users could not be loaded.');
});
}
......... Down below is where I put my data .........
<div class="row">
<h3>Utilisateurs ({{ $usersCount }})</h3>
</div>
<div class="row">
<div class="usersTable" style="width: 100%">
#include('manager.usersTable')
</div>
</div>
usersTable.blade.php
Whatever there is in this file is not really important but I got this at the end of it:
{!! $users->render() !!}
Current situation: Causes a page reload on the second time I click on a pagination link.
What I want: To not reload the page when I click on pagination links.
What I've tried: I actually followed this source code: https://gist.github.com/tobysteward/6163902
Thanks :)
You are attaching click method to .pagination a once document is ready, however if you create a new element with same class will not have same functionality. To achieve this you have to force script to check document dynamically. Please see below example.
$(document).on('click', ".pagination a", function() {
e.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var page = $(this).attr('href').split('page=')[1];
getUsers(page);
});
In laravel if you are using yajra datatable add below function
function reload_table(){
table.ajax.reload(null,false);
}
and call reload_table() instead table.draw() it will not create whole table but only reload
I have a problem with my delete action inside the datatables. My delete function won't working on second page after pagination.
I did $(this).off().on('click', '.btn_btn-danger_act-delete-member-maillinglist' , function(){ but it doesn't working and my button on first page also won't work.
$('.act-delete-member-maillinglist').each(function() {
$(this).off().on('click', '.btn_btn-danger_act-delete-member-maillinglist', function() {
var email = $(this).attr('data-email');
var list = $(this).attr('data-list');
Polaris.deleteMemberMailingList(list, email, function() {
$('.container_list_member_mailinglist').html('<i class="fa fa-spinner fa-spin"></i>');
Polaris.fetchDataMemberMailingList(lname, function() {
$('#popupmembermailing').find('.container-loader').hide();
});
});
});
});
I'm sure this is going to be simple well i hope it is. After racking my brain for days I have finally sorted my last problem thanks you someone on here, But now I have a new problem. I am dynamically creating blogs hundreds of them. I'm using JQuery to load a editor into a simple modal window like so
<a class="blog_btns" id="edit" data-id="$b_blog_id" href="">Edit</a>
then the JQuery
jQuery(function($) {
var contact = {
message: null,
init: function() {
$('#edit').each(function() {
$(this).click(function(e) {
e.preventDefault();
// load the contact form using ajax
var blogid = $(this).data('id');
$.get("../_Includes/edit.php?blogid=" + blogid, function(data) {
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%", ],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
});
},
open: function(dialog) {
dialog.overlay.fadeIn(200, function() {
dialog.container.fadeIn(200, function() {
dialog.data.fadeIn(200, function() {
$('#contact-container').animate({
height: h
}, function() {
$('#contact-container form').fadeIn(200, function() {
});
});
});
});
});
},
show: function(dialog) {
//to be filled in later
},
close: function(dialog) {
dialog.overlay.fadeOut(200, function() {
$.modal.close();
});
},
};
contact.init();
});
the problem I have is i have hundreds of
<a class="blog_btns" id="edit" data-id="$b_blog_id" href="">Edit</a>
but I want the all to run the same jQuery function above.
Can anyone help? Is there a simple way of doing this?
...many elements with same id...
That's the problem, you can't have multiple elements with the same id.
You probably want to use a class:
<a class="blog_btns edit" data-id="$b_blog_id" href="">Edit</a>
<!-- Added ---------^ -->
Then:
$('.edit').each(...);
// ^---- ., not #, for class
But you probably don't want to use each, just do:
$('.edit').click(function(e) {
// ...
});
There's no need to loop through them individually.
Another approach you might consider is rather than hooking click on each individual "edit" link, you might want to use event delegation. With that, you hook the event on an element that contains all of these "edit" links (there's bound to be a reasonable one, body is always possible as a last resort), but tell jQuery not to notify you of the event unless it passed through one of these on its way to that element in the bubbling. That looks like this:
$("selector for the container").on("click", ".edit", function(e) {
// ...
});
Within the handler, this will still be the "edit" link.
Use class instead of id as according to HTML standards each element should have a unique id.
id: This attribute assigns a name to an element. This name must be unique in a document.
class: This attribute assigns a class name or set of class names to an
element. Any number of elements may be assigned the same class name or
names. Multiple class names must be separated by white space
characters.
http://www.w3.org/TR/html401/struct/global.html
so use class instead of id
<a class="blog_btns edit" data-id="$b_blog_id" href="">Edit</a>
and refer to it with $('.edit')
I have a anchor tag in my page for logout.
<a href="/logout/" id="lnk-log-out" />
Here I am showing a Popup for confirmation with jQuery UI dialog.
If user click Yes from dialog it has to execute the link button's default action, I mean href="/logout".
If No clicked a Popup box should be disappeared.
jQuery Code
$('#lnk-log-out').click(function (event) {
event.preventDefault();
var logOffDialog = $('#user-info-msg-dialog');
logOffDialog.html("Are you sure, do you want to Logout?");
logOffDialog.dialog({
title: "Confirm Logout",
height: 150,
width: 500,
bgiframe: true,
modal: true,
buttons: {
'Yes': function () {
$(this).dialog('close');
return true;
},
'No': function () {
$(this).dialog('close');
return false;
}
}
});
});
});
The problem is I am not able to fire anchor's href when User click YES.
How can we do this?
Edit: Right now I managed in this way
'Yes': function () {
$(this).dialog('close');
window.location.href = $('#lnk-log-out').attr("href");
}
In the anonymous function called when 'Yes' is fired, you want to do the following instead of just returning true:
Grab the href (you can get this easily using $('selector').attr('href');)
Perform your window.location.href to the url you grabbed in point 1
If you want the a tag to just do it's stuff, remove any preventDefault() or stopPropagation(). Here I have provided two different ways :)
Don't use document.location, use window.location.href instead. You can see why here.
Your code in the 'Yes' call should look something like, with your code inserted of course:
'Yes': function () {
// Get url
var href = $('#lnk-log-out').attr('href');
// Go to url
window.location.href = href;
return true; // Not needed
}, ...
Note: Thanks to Anthony in the comments below: use window.location.href = ... instead of window.location.href(), because it's not a function!
I have used this in many of my projects so i suggest window.location.href
'Yes': function () {
$(this).dialog('close');
window.location.href="your url"
return true;
},
I'm trying to learn jQuery by implementing a simple menu. I've got <div> elements that act as buttons and have links in them. I'm trying to add onclick events to the divs that navigate the browser to the link's address in the div. This is basically my pseudo-code. What would the real code be? How can I improve this? Any feedback appreciated!
// Iterate over each menu button
$('.masterHeaderMenuButton').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var url = $('a', this).attr('href');
this.click(function () {
window.location.href = url;
});
// If the user is on the page for the current button, hilight it
if (window.location.href === url) {
$('a', this).addClass("masterHeaderMenuButtonSelected");
}
});
Try this untested example:
$('.masterHeaderMenuButton a').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var _this = this; // save this ref for click handler.
$( this ).parent().click(function () {
window.location.href = $(_this).attr('href');
});
// If the user is on the page for the current button, highlight it
if (window.location.href === url) {
$(this).addClass("masterHeaderMenuButtonSelected");
}
});
I don't actually use jQuery for such a simplistic task, especially if it involves page redirection. So unless you're looking to do some AJAX-style page loading, stick with standard HTML.
For that task, I use this sweet combo:
$('#nav_links li').live('click', function() {
var ajax_link = $(this).attr('rel');
loadLink(ajax_link);
});
function loadLink(link){
$('#content_window').css('position','relative');
$('#content_window').animate({
'left': '20px',
'opacity': '0'
}, 500, "swing", function() {
$.ajax({
url: '../sections/' + link,
dataType: 'html',
success: function(html) {
$('#content_window').html(html);
}
});
});
}
Awesome, right?
Here's the HTML:
<ul id="nav_links">
<li rel="setting-up.html"><span class="green">|</span>setting up<br></li>
<li rel="features.html"><span class="purple">|</span>features<br></li>
<li rel="more-uses.html"><span class="blue">|</span>more uses<br></li>
<li rel="troubleshooting.html"><span class="yellow">|</span>troubleshooting</li>
</ul>
Have a fun.