Codeigniter route on button click - javascript

Hi I am using codeigniter for this project
I have a button element as below
<div class=" pull-right" id="container">
<button class="btn btn-info">
<a style="text-decoration:none;color:white" href="">Guide</a>
</button>
</div>
This button element is part of a div which is one of the results from the search. When I click on the button, how do i pass the information of the div to the controller I want? The information I want to pass is just the element id of the div which is "container".

Try do like that
<button class="btn btn-info">
<a style="text-decoration:none;color:white" href="control/method/value">Guide</a>
</button>
In your class can do like that
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Control extends CI_Controller {
public function method($value) {
// Your value is in $value;
}
}
[Update]
Getting the parent ID element dynamically
<div class=" pull-right" id="container">
<button class="btn btn-info" onclick="window.location='/controller/method/' + this.parentNode.id;">
<a style="text-decoration:none;color:white">Guide</a>
</button>
</div>

Using jQuery:
$('.btn').click(function () {
$.ajax({
type : "POST",
url : 'controller/method',
data: {id : $(this).parent().attr('id')},
success : function(data) {}
});
});
In your controller:
$id = $this->input->post('id', TRUE);

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')
}
})
}

How to get id from button modal to django views

I want to get the id from the modals button to select the id for the context object get id. the sample script is like this:
<button type="button" class="btn btn-primary see-details" data-toggle="modal" data-target="#exampleModalLong" data-id="{{data.id}}">Detail</button>
and I call the "data-id" from the button to javascript
$(".see-details").on('click', function (){
var id = $(this).data('id');
$(".modal-bodys").html(`
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<h1>{{students.name}}</h1>
</div>
</div>
</div>
`)
})
I want to retrieve the id of the javascript variable to put into get id in the context in views.py
from django.shortcuts import render,get_object_or_404
from profil.models import students,data
def index(request):
ID="get data-id from js"
context = {
'data' : data.objects.all(),
'students' : get_object_or_404(students, id=ID)
}
return render(request,'index.html',context)

Bootstrap 4 Modal PHP Dynamic Variable Access

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.

HTML id in a php loop + modal (jquery)

I used a loop to get and display all the details for each event that a user added. Inside the loop i included a button for a modal. The thing is if i have more than one event, the <button class="btn btn-success" id="read">Read More</button> won't work. How will work around this?
This the php code
<?php
while ($event_row = mysqli_fetch_array($event_data)){
$event_img = $event_row['event_img'];
$img_src = "../admin/eventImages/".$event_img;
echo '<div class="col-sm-6 p0">
<div class="box-two proerty-item">
<div class="item-thumb">
<img src="'.$img_src.'">
</div>
<div class="item-entry overflow">
<h5>'.$event_row['event_name'].'</h5>
<div class="dot-hr"></div>
<span class="pull-left"><b> Date: </b>'.date("Y-m-d h:i A", strtotime($event_row['event_start'])).'</span>
<span class="pull-left"><b>Location: </b>'.$event_row['event_location'].'</span>
<div class="property-icon">
<button class="btn btn-success" id="read">Read More</button>
</div>
</div>
</div>
</div>';
}
?>
and this is my jquery code:
$(document).ready(function(){
$("#read").click(function(){
("#readmore").modal("show");
});
});
Add class selector. Also add some unique attribute to each button for identification.
<button class="btn btn-success read-more" id="read-more-1">Read More</button>
$(document).ready(function(){
$(".read-more").click(function(){
console.log($(this).id);
$("#readmore").modal("show");
});
});
If you have multiple buttons, than you need to use class instead of id as ID is always unique:
Change in HTML:
<button class="btn btn-success readmore">Read More</button>
Change in JQuery:
$(document).ready(function(){
$(".readmore").click(function(){
("#readmore").modal("show");
});
});

Only the first button is reacting to a click event

I have a jquery function attached to a btn-group like this:
<div class="row">
<!-- Vote button row -->
<div class="span8" id="votenumbers">
<div class="btn-group">
<button class="btn" id="votebutton" data-votevalue="1">1</button>
<button class="btn" id="votebutton" data-votevalue="2">2</button>
<button class="btn" id="votebutton" data-votevalue="3">3</button>
<button class="btn" id="votebutton" data-votevalue="4">4</button>
<button class="btn" id="votebutton" data-votevalue="5">5</button>
<button class="btn" id="votebutton" data-votevalue="6">6</button>
<button class="btn" id="votebutton" data-votevalue="7">7</button>
<button class="btn" id="votebutton" data-votevalue="8">8</button>
<button class="btn" id="votebutton" data-votevalue="9">9</button>
<button class="btn" id="votebutton" data-votevalue="10">10</button>
</div>
</div>
</div>
<!-- Vote button row ends -->
and this is the javascript im using to assign a function to each button.
$('#votebutton').each(function(){
$(this).click(function(){
var votevalue = $(this).data('votevalue');
var filename = $('.mainimage').data('filename');
var category = $('.mainimage').data('category');
$.ajax({
type: 'POST',
url: '?category=' + category,
data: {
"votevalue" : votevalue,
"filename" : filename
},
success: function(data){
$('body').html(data);
}
}); // end ajax
}); // end click
}); // end each
Now my problem is that only the first button is reacting to a click event. The other do not. Not sure why.
You assigned the same value for the 'id' attribute to all your buttons. Id attribute is supposed to be unique across the entire HTML page. The selector you used, $('#votebutton'), an id selector, returns a single element. This is why the click handler is only executing for one of your buttons. You should assign a different id value to each button, or no id at all.
You could get rid of the id attributes on the buttons altogether and use a class selector instead, to find the buttons:
$('#votenumbers .btn').each(function() { $(this).click(...) ... });

Categories

Resources