Bootstrap 4 Modal PHP Dynamic Variable Access - javascript

I have a PDO object with a certain number of DB entries. I'm looping through every result generating HTML content. Furhtermore, if a user is logged in, I am displaying extra buttons to edit and delete the content, like so:
if (isset($_SESSION['login']) and $_SESSION['idMembre'] == $id_utilisateur) { ?>
<br>
<a class="btn btn-outline-secondary btn-sm" href="" id="modify" data-toggle="modal" data-target="#modifierRecette" data-id="<?=$recette->idRecette;?>" onclick="modifierRecette(<?= $recette->idRecette; ?>)">Modifier</a>
<span>|</span>
<a class="btn btn-outline-danger btn-sm" href="" value="submit" onclick="supprimerRecette(<?=$recette->idRecette;?>)">Supprimer</a>
<?php } ?>
When the user clicks on "Modifier", a modal pops-up. Idea is that user can change some data inside the modal and click on a "Save Changes" button to commit the changes to the DB.
However, I have a hard time accessing to my PDO loop-through from within the modal.
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="sauvegarderRecette(<?= $recette->idRecette; ?>)">Sauvegarder</button>
</div>
Idea being in every loop-through, the function "sauvegarderRecette()" would get the unique ID of the data object I am working with. This in turn fires off an AJAX script to send the data to the DB:
function sauvegarderRecette(idRecette) {
let request = $.ajax({
'url' : 'ajax/sauvegarderRecette.php',
'type' : 'POST',
'data' : {
'idRecette' : idRecette
}
});
The issue now is that every loop-through, the ajax function sends off the same idRecette to the PHP script.
Any ideas on how I can dynamically access variable from JavaScript so it 'preserves' the value from the loop-through?
I thank you in advance for your help.

Related

Accessing dynamically created variable in onclick

I have a foreach loop, enumerating my models to create a table. In this table, i need to have an edit button for each model where i call a javascript function to show a modal.
I need to pass the model into the javascript function, but i can't get this to work. I've worked out how to dynamically create the variables, but not how to use it as input.
Right now, it's just hardcoded to use 'department1', which is just the first created. I need toggleManageDepartmentModal to be called with (department + #department.Id)
Creating the table
#foreach (var department in Model.PaginatedDepartments())
{
<tr>
<td>#department.Name</td>
<td>#department.Description</td>
<td class="min">#department.Created.ToLocalTime().ToString("dd-MM-yyyy")</td>
<td class="min">
<div class="text-nowrap">
<script>
//Dynamically create variables for each department
eval('var department' + #department.Id + '= #Json.Serialize(department);');
</script>
<button type="button" class="btn btn-secondary btn-sm" onclick="toggleManageDepartmentModal(department1)">
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
</div>
</td>
</tr>
}
Javascript function to show modal
function toggleManageDepartmentModal(department) {
var model = {
department : department,
controller : 'Admin',
action : 'ManageDepartment'
};
$.ajax({
type: "Post",
url: "/Modals/ShowManageDepartmentModal",
data:model,
success: function (data) {
$("#loadModal").html(data);
$('#modal-manage-department').modal('show')
}
})
}
I would like to do something like this:
<button type="button" class="btn btn-secondary btn-sm" onclick='toggleManageDepartmentModal(Eval("department" + #department.Id))'>
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
I am not exactly familiar with the tool (a templating engine?) you are using to build your HTML, but I will try to help.
Traditionally, before the JS framework takeover, the way to attach data to HTML elements was to use data-attributes. In your case, I would use something like data-department. I would dare to say that it's much better way then using script tags + eval()
The simplest way would be to attach the data to the button. Probably like a serialized JSON:
<button data-department="#DataGoesHere" type="button" class="btn btn-secondary btn-sm">
Rediger</button>
How about the onclick function? You can get the button's reference by using this argument:
<button onclick="toggleManageDepartmentModal(this)" data-department="#DataGoesHere" type="button" class="btn btn-secondary btn-sm">
Rediger</button>
Then, you can access the data by querying this.dataset.department:
function toggleManageDepartmentModal(targetElement) {
// `this` is event's target element
const department = targetElement.dataset.department;
// or rather JSON.parse(targetElement.dataset.department)
// or targetElm.getAttribute('data-department')
…
}
There's one caveat – because data-attributes are part of the 'public' markup, you really should not put anything confidential in there (but I guess that this is not the case).
I ended up taking a little different approch which works very well.
#foreach (var department in Model.PaginatedDepartments())
{
<tr>
<td>#department.Name</td>
<td>#department.Description</td>
<td class="min">#department.Created.ToLocalTime().ToString("dd-MM-yyyy")</td>
<td class="min">
<div class="text-nowrap">
<script>
//Store model JSON in localStorage
localStorage.setItem('department' + #department.Id, JSON.stringify(#Json.Serialize(department)))
</script>
<button type="button" class="btn btn-secondary btn-sm" onclick="toggleManageDepartmentModal(#department.Id)">
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
</div>
</td>
</tr>
}
function toggleManageDepartmentModal(id) {
var modelJSON = localStorage.getItem('department' + id);
var model = {
department : JSON.parse(modelJSON),
controller : 'Admin',
action : 'ManageDepartment'
};
$.ajax({
type: "Post",
url: "/Modals/ShowManageDepartmentModal",
data:model,
success: function (data) {
$("#loadModal").html(data);
$('#modal-manage-department').modal('show')
}
})
}

Javascript how to identify button clicked

I have a page with many articles. Each article has a delete button. How can I identify the button clicked for the article?
Currently I have this:
<button type="button" id="delete-article" class="btn btn-small btn-danger">Delete</button>
$('#delete-article').on('click', function(e) {
console.log('Test delete article');
});
This logs 'Test delete article' according to the number of articles on the page.
You can attach the event on button and use this object to refer the currently clicked button:
$('button').on('click', function(e) {
console.log(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="delete-article" class="btn btn-small btn-danger">Delete</button>
<button type="button" id="delete-article-2" class="btn btn-small btn-danger">Delete</button>
You can use your event variable to get the target of the event (that is, the element responsible) and from there get its id, like this:
let btnId = event.target.id;
However, for that to work properly you should assign unique ids to your buttons. If you want to provide other data (or you don't want to use id) you can append custom attributes, like data-value or similar, and use it like this:
let myValue = event.target.getAttribute('data-value');
You need to establish relation between article and corresponding button, one way to implement is by using HTML5 data attribute.
assign data-articleId to article id in button element and when you click the button you can access which button was clicked by using Jquery .data() function.
<button type="button" data-articleId='123' class="btn btn-small btn-danger delete-article">Delete</button>
$('.delete-article').on('click', function(e) {
$(this).data('articleId'); //will return 123;
console.log('Test delete article');
});
If all the buttons have this markup
<button type="button" id="delete-article" class="btn btn-small btn-danger">Delete</button>
Then the DOM sees them as just one button, you should find a way to attach unique ids to your buttons
You can get an object of clicked button then you can get any details from that object like an index or whatever you want.
$('#delete-article').click(function(){
console.log($(this));
console.log($(this).index());
});
You can directly achieve it by using the JavaScript.
document.addEventListener('click',(e)=>{
console.log(e.target.id)
})
<button type="button" id="delete-article1" class="btn btn-small btn-danger">Delete1</button>
<button type="button" id="delete-article2" class="btn btn-small btn-danger">Delete2</button>
<button type="button" id="delete-article3" class="btn btn-small btn-danger">Delete3</button>
<button type="button" id="delete-article4" class="btn btn-small btn-danger">Delete4</button>
<button type="button" id="delete-article5" class="btn btn-small btn-danger">Delete5</button>
<button type="button" id="delete-article6" class="btn btn-small btn-danger">Delete6</button>
<button type="button" id="delete-article7" class="btn btn-small btn-danger">Delete7</button>

implement bootstrap notification or profile

good morning:
<html>
<button type="button" class="btn btn-primary">Notifications <span class="badge badge-light">4</span>
</button>
<button type="button" class="btn btn-primary">Profile <span class="badge badge-light">9</span>
<span class="sr-only">unread messages</span>
</button>
</html>
now how I implement these ?
for example like facebook when i click the notification appear a little submenu
anyone can help me ?
thanks
You can get the notifications from the database in your controller, put them in a variable, and pass it to a view.
In the view itself you can do something like this:
// $notificationsCount is the variable with number of notifications you passed to the
view in your controller
<button type="button" class="btn btn-primary">Notifications
<span class="badge badge-light"><?php echo $notificationsCount ?></span>
</button>
If you don't want to refresh the page, you could use ajax or some kind of event.
Example:
$('#someElement').on('click', function () {
//change value of the notification btn
});

How to create a customised pop up using JavaScript

I have a SendMail button which on click calls the JavaScript function. Which upon validating gives the alert message. But that is a default alert which I am using. How can I create a customised alert in JavaScript.
My HTML Code:
<div id ="sendmail" style="display: none;">
<div class="container">
<div style="text-align:right; width:100%; padding:0;">
<button id ="cancel" style='margin-right:16px' class="btn btnprimary btn-lg pull-right" a href="javascript:window.history.back()">Cancel</button>
<button id ="sendMail" style='margin-right:16px' class="btn btn-primary btn-lg pull-right" onclick="sendMail()">SendMail</button>
And this is my index.js file
function sendMail(){
console.log(employee_id);
var employeeid = employee_id;
$.ajax({
url:'http://localhost:8088/JirasTrackingApp/reporter/
Reportees/JiraNames/'+employeeid,
type:'GET',
success: function(Jiranumbers){
alert("Mail is sent successfully"); //here I need to be able to call the customized alert instead of that default alert
},
error: function(Jiranumbers){
alert("Mail is not sent successfully");
}
});
Please advice, Thanks.
Your question very similar to this and I know you got your answer in this query.
how to change the style of alert box

Delete button show only user which book event and Admin in fullcalendar.js

I'm making event booking system using fullCalendar.js with the backhand of codeigniter, first there is 2 role user and Admin, User can book the event and delete the event but i want to show delete button only Admin and user which book the event. So can anyone please tell me how this can be possible.The delete button in modal box and show on eventClick in Calendar.My Html and javascript are
<div id="calendarModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Event Details</h4>
</div>
</div>
<input type="hidden" id="eventID"/>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="submit" class="btn btn-danger" id="deleteButton">Delete</button>
</div>
</div>
//----------------------Javascript-------------------------------
$('#deleteButton').on('click', function(){
// delete button
doDelete();
});
function doDelete(){
$("#calendarModal").modal('hide');
var eventID = $('#eventID').val();
var baseUrl = document.location.origin;
$.ajax({
url: baseUrl+'/mrbs/api/post_api',//
data: 'action=delete&id='+eventID,
type: "POST",
});
$('#calendar').fullCalendar('refetchEvents');
}
Thanks in advance ........:)
You should probably control display of the delete button on the server-side, not in Javascript on the client. That means using Codeigniter when rendering the modal, so for example:
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<?php if ( ... test if user is admin ... ) { ?>
<button type="submit" class="btn btn-danger" id="deleteButton">Delete</button>
<?php } ?>
</div>
You should also confirm in your controller method (/mrbs/api/post_api) that the user is an admin before actually doing the delete.
UPDATE
If you want to display only events created by the current user, you should handle that on your server-side event source. You have not posted your Fullcalendar code, but you must have something like:
$('#calendar').fullCalendar({
// ... code
events: "some/path/to/server-side-json",
});
In your some/path/to/server-side-json controller method, check the user id of the user making this query, and only return events created by that user.

Categories

Resources