assign value to php variable using jquery [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i am working on website with buttons each button fire up a bootstrap modal contain data from mysql database i pass a variable from the jquery that fire up the model into a mysql query inside the modal the problam is the php variable cannot get the data send it from the jquery any hints please ?!
i am passing data through jquery post to ajax.php file
the modal code
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<span id="codeElem"></span>
<?php
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode ");// WHERE Code IN ('".$codeArrayStr."')
?>
<?php
$i=0;
$row3 = mysqli_fetch_array($resultHead);
?>
<h4 class="modal-title"><?=$row3['CoopName'];?></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php
$result = mysqli_query($con,"SELECT DISTINCT * FROM reports WHERE host = $getCode GROUP BY host DESC");
?>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<div class="card card-figure has-hoverable">
<figure class="figure">
<img class="img-fluid" src="http://www.iroof.tv/screenshots/<?=$row['screenshot'];?>" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"><?=$row['host'];?></h6>
<p class="text-muted mb-0"> <?=$row['timestamp'];?> </p>
<?php
// Assign JSON encoded string to a PHP variable
$statusJson = $row['status'];
// Decode JSON data into PHP associative array format
$arr = json_decode($statusJson, true);
// Call the function and print all the values
// $result2 = printValues($arr);
echo "<hr>";
echo "<h3> Player </h3>";
// Print a single value
echo "Status: ".$arr["player"]["status"] . "<br>";
echo $arr["player"]["filename"] . "<br>";
echo "<hr>";
echo "<h3> Graphics </h3>";
echo "Display: ".$arr["video"]["display"] . "<br>";
echo "Resolution: ".$arr["video"]["resolution"] . "<br>";
echo "Colors: ".$arr["video"]["colors"] . "<br>";
echo "<hr>";
echo "<h3> System </h3>";
echo "CPU: ".$arr["cpu"] . "<br>";
echo "Ram: ".$arr["ram"] . "<br>";
//echo "Temprature: ".$arr["temperature"] . "<br>";
echo "Fan: ".$arr["fan"] . "<br>";
?>
</figcaption>
</figure>
</div>
<?php $i++;
}
?>
</div>
<!-- Modal footer
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>-->
</div>
the jquery script
<script>
$(document).ready(
function() {
setInterval(function() {
$('.card');
}, 5000); //Delay here = 5 seconds
var gen;
$(".btn").click(function(){
gen = $(this).attr("data-code");
//$.post("ajax.php", {"code": gen},function(data){console.log(data);});
});
$('#myModal').on('shown.bs.modal', function () {
$.post("ajax.php", {"code": gen},function(data){console.log(data);});
//var phpCode = "<? $getCode = $_POST["code"]; ?>";
//$('#codeElem').html(phpCode);
})
});
</script>
ajax.php file
<?php
if(isset($_POST['code']) && isset($_POST['code'])){
//$_SESSION["code"] = $_POST["code"];
$_SESSION['header'] = $_POST['code'];
$getCode = $_POST["code"];
echo $_SESSION['header'];
}
?>
i expect the variable $getCode to get the code from jquery to complete the mysql query inside the modal :
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode");

I dont think its possible to post variables to a modal, I didnt see example like that when I was searching for popup modal login.
guess you need an action page to forvard infos to modal.
This is the solution to post variables:
Change variables to your needs..
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var post_id =$("#mail-id").val();
var name =$("#mail-name").val();
var email =$("#mail-email").val();
var message =$("#mail-message").val();
var type =$("#mail-type").val();
var captcha_code =$("#captcha_code").val();
var submit =$("#mail-submit").val();
$(".form-message").load("heads/comment.php",{
post_id: post_id,
name: name,
email: email,
message: message,
type: type,
captcha_code: captcha_code,
submit: submit
});
});
});
you probably need some thing like this to show variables in popup
<p class="form-message"></p>
Or you can check Bootstrap modal table :
Here

Related

how can i send and get messages from database using AJAX JQUERY

I'm building a website using PHP and AJAX JQUERY. And inside this website, there is texting system, like whatsapp, telegram ...etc.
and I'm wanna get all the messages from the database after the user send a message, using jQuery AJAX. so far I have been able to send the text to the database successfully but I fail when I try to get the messages.
I Have this following code when first the page is loaded:
<div class="messaging-frame">
<div class="Title-in-message">
<h4 class="title-message"><?php echo $index['Title'] ?></h4>
</div>
<div class="messaging-box" id="messages">
<?php
// THE MESSAGE FROM MESSAGE TABLE
foreach ($messages as $key => $value) {
if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='sent'>
<p id='send-bubble'> <?php
echo $value['Message'] ?> </p>
</div>
</div>
</div>
<?php
} else { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='recived' id="recieved-bubble">
<p id='recived-bubble'><?php echo $value['Message'] ?></p>
</div>
</div>
</div><?php
}
}
?>
</div>\
Than this code in AJAX jQuery get executed when ever the user send a new message in messaging box:
$(document).ready(function() {
$('#sending_text').click(function() {
var report = $('#report_num').val()
var reportInt = parseInt(report);
var text = $('#text_sent').val();
var encodeText = encodeURIComponent(text);
$.ajax({
url: "<?php echo base_url() . 'DisplayTicket/sendNewText' ?> ",
type: "POST",
data: {
text: text,
reportNum: reportInt
},
success: function() {
$('#messages').load("<?php echo base_url() . 'DisplayTicket/getNewMessages' ?>", {reportNum: reportInt}, function() {
var texts = " <?php foreach ($messages as $k => $val) { if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='sent'>";
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>";
texts += "<?php } else { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='recived' id='recieved-bubble'>"
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>"
texts += "<?php }
} ?>";
texts += "</div>";
$('#messages').html(texts);
})
},
});
});
})
Keep in mind that the $('#messages').html(texts);
is actually get executed but the newest messages in not added
I see you are using .load() method to fill the #messages .
Normally the first argument to this method is the response you wanna insert,and the this is just a callback after success, and you are using a php variable $messages instead of using the response from the request.
I see already 2 ways of doing this:
1 - remove the callback from load() and make sure the response is well written in html as youy want
2 - get rid of load() function, and call another ajax inside success of the first ajax to accomplish so.
The second method is just to make you understand what is wrong. So the best way to do it is to fix load() method accordingly

modals showing blank after ajax call

I am developing a page in php that has multiple dynamic modals for displaying pdf files in the page itself with respective title and author names. All the data comes from a database designed in MySQL. The trigger buttons are also meant to be dynamic. I have tried the following code. The problem is I am getting the modals blank. I am able to print the data in fetch-reader.php page itself. I think I am doing something wrong in AJAX or modal part. Please guide me through it.
<?php $sqlGal = "select * from articles where year = '2019'";
$queryGal = $con->query($sqlGal);
if ($queryGal->num_rows > 0) {
while ($row = $queryGal->fetch_array()) { ?>
<div class="col-md-3 gallery-grid">
<h3 style="height: 200px; vertical-align: bottom; margin: 0; display: table-cell;"><?php echo($row['title']) ?></h3>
by<h4><?php echo($row['name']) ?></h4>
<i class="fa fas fa-book-open"></i> Read
</div>
<?php }
}
?><div class="clearfix"></div>
<div class="modal fade" id="myReader" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 id="articleName"></h3>
<h4 id="name"></h4>
<h6 id="position"></h6>
<h6 id="address"></h6>
</div>
<div class="modal-body">
<object data="" id="reader" width="100%" height="450px"></object></div>
</div>
</div>
</div>
</div>
in <script> part
$(document).ready(function() {
$('#myReader').on('show.bs.modal', function(e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type: 'get',
url: 'include/fetch_reader.php',
data: 'rowid='+rowid,
dataType: 'json',
success : function(response) {
$('#articleName').text(response.title);
$('#name').text(response.name);
$('#position').text(response.position);
$('#address').text(response.address);
var add = "uploads/articles/" + response.yearSl + ".pdf";
$('#reader').prop('data', add);
}
});
});
});
in fetch-reader.php
<?php
require_once('connect.php');
if ($_GET['rowid']) {
$id = $_GET['rowid'];
$sql = "SELECT `title`, `name`, `position`, `address`, `yearSl` FROM articles WHERE `id` = '".$id."'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array();
}
$connect->close();
header('Content-Type: application/json');
echo json_encode($row);
}
Please guide me any other way which can serve my purpose, but I don't want to use any third-party tools for the purpose.
I think you are sending the wrong data in ajax. Try this into your "$ .ajax" call:
data: { 'rowid': rowid }
And try checking into browse console if the request shows any error. Into your ajax call you check only for success return, not for fail.

Bootstrap modal confirmation delete

Hello guys I'm trying to delete a record/row from my table using a modal delete confirmation. This is what I've tried so far:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
</script>
<table class="table table-bordered">
<?php
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
<tr>
<td><a href="project-detail.php?code=<?php echo $project; ?>">
<?php echo $project; ?></a></td>
<td><?php echo $desc; ?></td>
<td><a href="update-project.php?code=<?php echo $project; ?>" title="Update record">
<i class="icon-edit icon-white">
</i>
</a></td>
<td><a href="#<?php echo $project; ?>"
id="<?php echo $project; ?>"
data-id="<?php echo $project; ?>"
class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i></a></td>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
</div>
</div>
</tr>
<?php
}
?>
</table>
But the problem is, when I am about to delete the last row the one that gets deleted is the first row. Why is it like that? Any ideas? Help is much appreciated. Thanks.
The problem lies in the modal generation and passing the $project value.
You are using a loop as
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
And inside the above loop you are generating the modals so basically you will have many modals which are equal to the num of rows in the query.
Now all of them are having the same "id" i.e. "dialog-example" and once you click on the delete it pop ups the first modal from the DOM and is deleting wrong data.
Solution
For each modal you give the id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the blow code
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
Get the id of the element using attr("id") and append this at the end of
"dialog-example_"+{id you received}
The same thing you need to do for the hide modal as well.
UPDATE ON HOW TO DO IT
Give the modal div id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the click function to as
$(".btn-show-modal").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('show');
});
Change
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
to
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="<?php echo $project ;?>">Yes<a>
AND finally
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
to
$(".btn btn-danger").click(function(e) {
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('hide');
});
because you generate modal for every row this is wrong !
and show modal(first modal show) this is wrong!(this delete first row)
create one modal and set parameter with jquery e.g
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
$("#dialog-example #btn-delete").attr('href','delete-project.php?code='+$(this).attr('data-id'));
});
good luck
On topic
Problem is you have multiple modals. But select it on 1 id. So jQuery will select the first value.
A solution would be to put the delete url in an hidden input field. Then when the user clicks the open delete modal you select the url and put it in the a tag.
Example time
JavaScript Part
$(function(){
$(".btn-show-modal").click(function(e){
// put the right url in the delete
$("#dialog-example .delete-url").attr('href', $(this).attr('data-delete-url');
$("#dialog-example").modal('show');
return e.preventDefault();
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
PHP part
I assume $stmt is prepared etc
<ul>
<? foreach($stmt->fetchAll() as $record) : ?>
<li>
delete
</li>
<? endforeach; ?>
</ul>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a class="delete-url btn btn-danger">Yes<a>
</div>
</div>
Code explaind
It is not handy to put an bootstrap modal in an foreach/for/while unless you change the id. But then again lot of duplicate code.
What the code does it changes the delete-url on the fly depending on which a the user clicked
Off topic
I highly recommend using the foreach for your iteration of the data records instead of a for loop.
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){ /** code **/}
would be
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
foreach($stmt2->fetchAll() as $record){}
Because when you open the modal, it open the first #dialog-example div.
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$(this).parent().find("#dialog-example").modal('show');
});

Jquery event won't fire when element is displayed via mysql

I have some content that is fed in from mysql that, when clicked should fire an alert()...
however, this is not working...
here is my code for the code that is fed in from php/get_answers.php
<?php session_start(); ?>
<?php require_once("../includes/include_all.php"); ?>
<?php $answers = $question->get_answers_for_question($_GET['id']); ?>
<?php while($row = $answers->fetch_array()){ ?>
<!-- ALL ANSWERS HERE -->
<div class = 'answer-row'>
<div class = 'answer-side'>
<div class = 'arrow-contain-answer' type = 'answer' id = 'arrow-up' answer-id = '<?php echo $row["id"]; ?>'></div>
<div class = 'answer-votes-contain'>
<?php echo $row['popularity']; ?>
</div>
<div class = 'arrow-contain-answer' id = 'arrow-down'answer-id = '<?php echo $row["id"]; ?>'></div>
</div>
<div class = 'answer-content'>
<?php
echo $row['content'];
?>
</div>
<div class = 'actions'>
<a href = '#' class= 'add-comment' id = '<?php echo $row["id"]; ?>'> add comment </a>
</div>
</div>
<?php } ?>
and here is the jquery on the page that it is displayed on:
$(".arrow-contain-answer").click(function(){
alert();
});
What I want to happen is when someone clicks the element with the class of 'arrow-contain-answer' an event will occur..
I think I have had problems before when elements are being 'fed' into the page via mysql/php.
$(document).on("click", ".arrow-contain-answer", function(){
alert();
});
Try this way for dynamic added elements!
even better(performancewise) if you delegate it with the closest static element(parent) which is present in the document when dynamic fed element is added.
$('.answer-row').on("click", ".arrow-contain-answer", function(){
alert('clicked');
});
to read more about on delegated event

How to pass msg_id into jquery modal form?

I have a following data where I am showing data from database. When i click Comment a dialog appear, there i need to show data in modal from db. but for getting data from db i need msg_id in modal form.
<?php
$msg_id = $data['message_id'];
?>
<a data-toggle="modal" href="msg_id=<?php echo $msg_id; ?>#example" class="link_comment">Comment</a>
So here I want to pass msg_id to jquery modal form, where i can get data from db on the base of msg_id for that specific message and show it in modal box.
<div id="example" class="modal" style="display: none; ">
Your Message id : <?php echo $msg_id; ?>
</div>
So how can I pass $msg_id into jquery modal form.
php
<?php
$msg_id = 123; // testing mode
?>
html
<a data-toggle="modal" href="msg_id=<?php echo $msg_id; ?>#example" class="link_comment">Comment</a>
<div id="example" class="modal" style="display: none; ">
Your Message id : <span class="msg_id">?</span>
</div>
<script type="text/javascript">
$('a.link_comment').click(function(event) {
event.preventDefault();
var a = $(this);
var msg_id = 'fetched id'; // parse msg_id from a.attr('href')
$('div.' + a.attr('data-toggle')).show().find('span.msg_id').text( msg_id );
});
</script>

Categories