Send value from jquery to php - javascript

I have a web page that displays several albums and the following html code for an album icon that should allow the user to change the access settings to the specific album ($row holds the response values from a db query that returns info on albums)
<a data-title="'.$row['title'].'" data-description="'.$row['description'].'" data-id="'.$row['photoCollectionId'].'" class="open-update_dialog2" data-toggle="modal" href="#update_dialog2">
<i class="ace-icon fa fa-eye"></i>
</a>
and if the user clicks on it, a modal shows up
<div class="modal fade" id="update_dialog2" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<ul id="check-list-box" class="list-group checked-list-box">
<?php
foreach (getFriends($email) as $row) {
$flag = checkAccessRights($row['email'],1)['value'];
echo '<li class="list-group-item" data-checked='.$flag.'>'.$row['firstName'].' '.$row['lastName'].'</li>';
}
?>
</ul>
</div>
</div>
</div>
.js
$(document).on("click", ".open-update_dialog2", function () {
albumName = $(this).data('title');
$(".modal-body #albumName").val(albumName);
albumDescription = $(this).data('description');
$(".modal-body #albumDescription").val(albumDescription);
albumId = $(this).data('id');
});
My problem is that each modal would need to fetch different data depending on the album the user clicked on and thus I want to replace the value of 1 in checkAccessRights($row['email'],1) with the value of the variable albumName.
Is there a way to get the value from jquery to php? Any tip would be greatly appreciated!

You can use ajax,
This (Ajax) help you to create dynamic album.

JQuery it is a client side, PHP it is a server. So you should send request to the server with albumId parameter.
$(document).on("click", ".open-update_dialog2", function () {
albumName = $(this).data('title');
$(".modal-body #albumName").val(albumName);
albumDescription = $(this).data('description');
$(".modal-body #albumDescription").val(albumDescription);
albumId = $(this).data('id');
$.get("yourPhpFile.php", {albumId:albumId}).done(function(resp) {
//
});
});
and on your server you need get this parameter and put in your loop
<div class="modal fade" id="update_dialog2" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<ul id="check-list-box" class="list-group checked-list-box">
<?php
$albumId = $_GET['albumId'] ? $_GET['albumId'] : 1;
foreach (getFriends($email) as $row) {
$flag = checkAccessRights($row['email'], $albumId)['value'];
echo '<li class="list-group-item" data-checked='.$flag.'>'.$row['firstName'].' '.$row['lastName'].'</li>';
}
?>
</ul>
</div>
</div>

Related

Modal window will not open after paginating retrieved data from the database

I have built an image gallery using the Bootstrap framework, php, SQL and jQuery where users can click a thumbnail to see their selected image enlarged inside a modal window. All the images are stored in a database. The code worked as expected until I paginated the gallery. Now, when a thumbnail is clicked, the modal window does not open. Can anyone suggest a fix for this problem? I have tried some solutions myself but none have worked so far. Many thanks.
gallery.php code:
<div class='row' id='pagination_data'>
<!--Fetch and display images from database -->
<?php ?>
</div>
<!--Bootstrap modal window -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal"><span aria- hidden="true">×</span><span class="sr-only">Close</span></button>
<img src="" class="imagepreview" style="width: 100%;" >
</div>
</div>
</div>
</div>
<script>
//PAGINATION SCRIPT
$(document).ready(function(){
//when fucntion is called fetch data from gallery table
load_data();
function load_data(page) {
$.ajax({
url:"pagination.php",
method: "POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function() {
var page = $(this).attr("id");
load_data(page);
});
});
</script>
<script>
//MODAL SCRIPT
$(function() {
$('.pop').on('click', function() {
$('.imagepreview').attr('src', $(this).find('img').attr('src'));
$('#imagemodal').modal('show');
});
});
</script>
pagination.php code:
$record_per_page = 18;
$page = ''; //store current page number
$output = '';
//check if page variable is present
if (isset($_POST["page"])) {
//ajax function
$page = $_POST["page"];
} else {
$page = 1;
}
$start_from = ($page - 1) * $record_per_page;
$query = "SELECT * FROM gallery ORDER BY id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$img = $row["path"];
$uploadDate = $row["uploadDate"];
$img = "<img id='modalImg' src='useruploads/" . $row['path'] . "' style='max-width: 100%; height: auto;'/>";
$output .= "
<div class='col-md-4 mainGalleryImg'>
<div class='myImg'>
<div class='pop'>
$img
</div>
<br>
</div>
</div>
";
}
$output .= "<div class='col-md-12' align='center'> <nav aria-label='Page navigation example'>
<ul class='pagination justify-content-center'> <li class='page-item'>
<a class='page-link' href='#' aria-label='Previous'>
<span aria-hidden='true'>«</span>
<span class='sr-only'>Previous</span>
</a>
</li>";
$page_query = "SELECT * FROM gallery ORDER BY id DESC";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for ($i=1; $i <=$total_pages; $i++) {
$output .="<span class='pagination_link page-link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
$output .= " <li class='page-item'>
<a class='page-link' href='#' aria-label='Next'>
<span aria-hidden='true'>»</span>
<span class='sr-only'>Next</span>
</a>
</li></ul>
</nav> </div>";
echo $output;
Bootstrap version: 4.4.1
jQuery version: https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
$('.pop').on('click', function() { only attaches the handler to elements currently in DOM. Since you call it before you even retrieved the images it does nothing.
You need to use delegated event handlers.
$(document).on('click', '.pop', function() {

Clear an automatic Setinterval to open a modal

I have a list update part in my php where the ajax will update the list. The list is generated through sql queries and in a while loop. So it creates n number of list based on database values. Now I have a button on every list which will open up a modal box.
The update is done through set interval function below
var int = startinterval();
function startinterval() {
interval = setInterval(fetch_list, 1000);
return interval;
}
function fetch_list() {
var action = "fetch_data";
$.ajax({
url: "list.php",
method: "POST",
data: {
action: action
},
success: function(data) {
$('.list').html(data);
}
})
}
My Html where the data is updated to the list class
<div class="col-lg-12 list" style="overflow-y: auto;height: 400px;">
Now my problem is when i click the button on the list (as mention earlier) which should normally open up the modal box. Due to setInterval constantly updating the list every sec, the modal when open dissapears and goes hidden.
So what I'm trying is when I click the button to open the modal, it should stop the setinterval function. The setinterval should come back running once I click the cancel button inside the modal.
I tried many ways to clearinterval(), but no success. So expecting someone's help for me to get the wheels rolling.
Thanks in advance.
UPDATE:
my list would look like the below screenshot.
My list.php
if($_POST["action"] == "fetch_data")
{
echo fetch_list($connect);
}
function fetch_list($connect)
{
if(!$_SESSION['id']){
$output = '<ul class="list-unstyled"><h4>Please Select a Programme</h4></ul>';
return $output;
}else{
$query = "
SELECT * FROM list_programme
WHERE pid = '".$_SESSION['id']."'
ORDER BY pid ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<ul class="list-unstyled">';
foreach($result as $row)
{
if($row["user"] == $_SESSION["uid"])
{
if($row["pstatus"] == '2')
{
$tickstatus = 'color:white';
$pcontrol = 'bg-success';
$pname = $row["pname"];
$border = 'border-color:#999;';
$pid = $row['pid'];
$notification = 'incomplete';
}
else
{
$pname = $row["pname"];
$pid = $row['pid'];
$notification = 'complete';
}
}
else
{
}
$output .= '
<div class="x_panel">
<button class="btn btn-round button-pcontrol '.$pcontrol.'" id="'.$pid.'" value="'.mb_strimwidth($pname, 0, 21, "...").'" data-notification="'.$notification.'" onClick="markcheck(this.id,this.value,this.dataset.notification)" style="'.$border.'"><i class="material-icons" title="Mark Completed" style="'.$tickstatus.'">check</i></button><span class="pname">'.$pname.'</span>
<span class="pcontrolbuttons">
<button class="btn btn-round button-pcontrol" id="programme" onClick="stopinterval()" data-id="'.$pid.'" data-toggle="modal" data-target="#programme'.$pid.'"><i class="material-icons" title="Assign users">person_add</i></button>
<button class="btn btn-round button-taskcontrol" data-id="'.$pid.'" data-value="'.mb_strimwidth($pname, 0, 21, "...").'" onClick="deleteprgm(this.dataset.id,this.dataset.value)"><i class="material-icons" title="Delete Task">delete</i></button>
</span>
</div>
<!--Modal -->
<div id="programme'.$id.'" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center">Add to this programme</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Some Input elements, Drop downs, etc.,
</div>
<div class="submit-section">
<button type="button" class="btn btn-success submit-btn" id="addnusers"><i class="glyphicon glyphicon-plus"></i> Add Users</button>
<button type="button" class="btn btn-primary submit-btn" id="closeassignee" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- /Modal -->';
}
$output .= '</ul>';
return $output;
}
}
So what I'm trying is when I click the button to open the modal, it
should stop the setinterval function.
You always should stops the functions execution, otherwise it will call the AJAX once per second and change the content of the modal.
document.getElementById('#button').addEventListener('click', function(event) {
event.preventDefault();
clearInterval(int);
// open modal
});
The setinterval should come back running once I click the cancel
button inside the modal.
document.getElementById('#cancel').addEventListener('click', function(event) {
event.preventDefault();
startinterval();
});
After searching for many resources, I had no luck to fix my issues with SetInterval.
So instead I modified my code to use setTimeout function. And the main drawback is this will not do live updates but once some button are clicked to modify the contents, the ajax success will call the setTimeout function and my list will be updated. So for time being the purpose is served.
Thanks for all the response.
Below is the single piece of code I Modified instead of a setInterval function
setTimeout(fetch_list, 1000);

How to create multiple modals in a document using jQuery and Bootstrap?

The following function is able to open only one modal since it uses element ID.
How do I expand this function to open multiple modals?
HTML / PHP part of the code (Notice the that is supposed to open the model)
$getUsers = 'SELECT * FROM users';
$result = $pdo->prepare($getUsers);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($row['usergroup'] === "Admin") {
echo "<tr class='table-danger'>";
} else {
echo "<tr>";
}
echo "<td><center>" . $row['username'] . "</center></td>";
echo '<td><center>View</center></td>';
echo "</tr>";
}
Modal
<div class="modal fade" id="userInfoModal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Info</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="userModalBody" class="modal-body">
</div>
</div>
</div>
</div>
Javascript
$(document).ready(function() {
$('#openUserInfoModal').on('click',function(){
var dataURL = $(this).attr('data-href');
$('#userModalBody.modal-body').load(dataURL,function(){
$('#userInfoModal').modal({show:true});
});
});
});
Once again, the first row that is displayed, you can click the a href and it will open the modal and display the user info. After the first row, clicking the a href does nothing, and does not open the modal.
Also if you delete the first row / delete the user, and the second row now becomes the first one, you can click the a href and it'll display the users data.
I'm really not sure what is causing this issue, but thanks for any help.
The reason for this, is that you are duplicating the id of the a element. So, when you click on any of them, jQuery is actually using only the first one. So, you would need to change it, so as instead of using an id, you would use a class to open the modal.
PHP
$getUsers = 'SELECT * FROM users';
$result = $pdo->prepare($getUsers);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($row['usergroup'] === "Admin") {
echo "<tr class='table-danger'>";
} else {
echo "<tr>";
}
echo "<td><center>" . $row['username'] . "</center></td>";
echo '<td><center>View</center></td>';
echo "</tr>";
}
jQuery
$(document).ready(function() {
$('.openUserInfoModal').on('click',function(){
var dataURL = $(this).attr('data-href');
$('#userModalBody.modal-body').load(dataURL,function(){
$('#userInfoModal').modal({show:true});
});
});
});

Show database on bootstrap modal with Ajax in Laravel

I'm new at Laravel and ajax, I want to show database from mysql to Bootstrap modal, follow this
I use Laravel framework, this is the table
<tbody>
<?php
$result = DB::select('SELECT * FROM thongtinlodat');
foreach ($result as $key) {
echo '<tr>';
echo '<td>'.$key->TenNhaDauTu.'</td>';
echo '<td>'.$key->SoNhaDauTu.'</td>';
echo '<td>'.$key->NgayCapNDT.'</td>';
echo '<td>'.$key->NoiCapNDT.'</td>';
echo '<td>
<a class="btn btn-small btn-primary"
data-toggle="modal"
data-target="#exampleModal"
id="getUser"
data-whatever="'.$key->ID.' ">VIEW</a>
</td>';
echo '</tr>';
}
?>
</tbody>
Modal
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="memberModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="memberModalLabel">View info</h4>
</div>
<div class="dash">
<!-- Content goes in here -->
</div>
</div>
</div>
</div>
This is javascript with ajax
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
var modal = $(this);
var id = recipient;
var dataString = 'id=' + recipient;
$.ajax({
type: "GET",
url: "editdata",
data: dataString,
cache: true,
success: function (data) {
console.log(data);
modal.find('.dash').html(data);
},
error: function(err) {
console.log(err);
}
});
});
File editdata.php, get id from ajax and select data from mysql
<?php
$id = $_GET['id'];
$members = DB::table('thongtinlodat')
->where('ID', $id)
->first();
?>
In the routes, how can I get id to insert to the URL, like this Route::get('/editdata{?id=}', 'adminController#test');?
Thanks for helping!!!
In the routes, how can I get id to insert to the URL?
Like this:
Route::get('my/route/{arg1}', 'MyController#show')->where('arg1', '[0-9]+');
And in your controller:
public function show(arg1){...}
The "where" clause allows you to tell the route what to expect as an argument. For example in the lone above, the arg1 must be positive integer.
Looking at your code, I can only recommend you to look at laravel doc :). It's really well written and you will see how to improve your code.
More info: https://laravel.com/docs/5.6/routing#route-parameters

Modals Laravel 5.1

I have this code:
<!-- line modal -->
<div class="modal fade" id="squarespaceModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="lineModalLabel">Prašymas Dėl Pakvietimo</h3>
</div>
<div class="modal-body">
<!-- content goes here -->
#if($errors->any())
#foreach($errors->all() as $error)
<ul class="list-unstyled">
<li class="alert alert-danger">{{$error}}</li>
</ul>
#endforeach
#endif
{!! Form::open(['url' => 'sukurti', 'id' => 'frm']) !!}
#include('components.forma')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
Want I want to do here is to show errors without closing the modal. Because if now I leave blank spaces and press submit, the modal shuts down and if I'm press one more time on button to show modal than I can see the error. How to make make that when spaces blank I press enter the modal wont close and just stay but with errors ?
To Work like that you have to make few adjustment in your code .
Jquery will handle your submit action . Make a submit event like ;
$('#frm').submit(function(e){
//stop default submit
e.preventDefault();
//make checks here now check for space .
var field = trim($('fieldname').val());
//of course you can apply some jquery validation library here too .
if(field.length > 0){
//submit form but you need to perform ajax for saving data here
//on ajax success close you modal
//here if you have some server side validation error then show them here without closing modal
//laravel give you error in json array form . foreach and append them on ul tag .
//$error = []; $.each(errors , function(val){$error[] = "<li>"+val+"</li>";}); $('ulid or class').html(error);
//empty html of this ulid or class if there is no error
// $('#squarespaceModal').modal('hide');
}else{
//show error
$('ulid or class').html('<li>This is error</li>');
}
})
That is the basic idea , how you can achieve your goal .

Categories

Resources