using jquery in php post method - javascript

I am not very experienced in jquery and ajax but I need the following. After users have successfully logged in they can download pdf files from the page. The site has a collapse div from where they can choose which file to download. Everything is done in php and works ok. However, if the file is not found the collapse div is closed back. In other words the web page gets reloaded. So the user has to make a new selection newly which is inconvenient. So I would the following. If the file is not found then the div should stay collapsed and the previous value in the input field 's' on the form. I know this should be done via jquery or javascript. I have tried the following but it does not work.
//PHP
<?php
//if download is clicked
if (isset($_POST["download"])) {
$data = $_POST["s"];
//if file is found
if (fileexists($data){
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile($data);
}
//else the div should remain open
else{
echo "<script> if ($('#collapseOne').is(':hidden')) {
$('#collapseOne').show();
}</script>";
}
}
?>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form id='searchForm' method="post" action=''>
<p><label>Select Month</label></p>
<input id='s' name = 's' type='text' required><br><br>
<button type="submit" id='download' name='download' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download
</button>
<br> <br>
<button id='download1' name = 'download1' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download All
</button>
</form>
</div>
</div>

In short, you echo PHP into Javascript
<script>
$(document).ready(function(){
var hasDownload = "<?php echo $_POST['download']; ?>";
var oldInput = "<?php echo $_POST['s']; ?>";
if(hasDownload == false) {
$('#collapseOne').show();
$('input#s').val(oldInput);
}
})
</script>
When the server serves your file, those values will be present for your Javascript. Place you're jQuery at the bottom in another if statement & a doc ready block so that the dom is loaded first and echo your PHP variables into Javascript variables to perform your jQuery logic.
<?php
if (isset($_POST["download"]) && fileexists($_POST["s"]) {
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($_POST["s"]);
}
?>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form id='searchForm' method="post" action=''>
<p><label>Select Month</label></p>
<input id='s' name = 's' type='text' required><br><br>
<button type="submit" id='download' name='download' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download
</button>
<br> <br>
<button id='download1' name = 'download1' class='btn btn-default btn-lg'>
<span class='glyphicon glyphicon-download-alt'></span> Download All
</button>
</form>
</div>
</div>
<?php if(isset($_POST["download"]) == false && fileexists($_POST["s"] == false) : ?>
<script>
$(document).ready(function(){
var hasDownload = "<?php echo $_POST['download']; ?>";
var oldInput = "<?php echo $_POST['s']; ?>";
if(hasDownload == false) {
$('#collapseOne').show();
$('input#s').val(oldInput);
}
})
</script>
<?php endif; ?>

Try using this!
$.ajax({
url:"/path/to/your/script/",
type: "post",
data: //fetch the data which you want to pass
}).done(function(status){
//status is the data returned from the script called
});

Related

Pass Javascript variable in PHP query

I've created a table with data and auto-generated buttons. When i click in 1 button .add_task, a modal opens, which display another table according to retrieved key: user_id of button.
The functionallity of button is shown below:
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"actions/fetch_jobs.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
$('#jobModal').modal('show');
$('.modal-title').text("Jobs");
`$('#vis_id')`.val(user_id);
$('#show_inseredjobs').html(data);
}
})
});
The problem is that i want to take value $('#vis_id') or user_id and put it in a php query of opened modal.
<div id="jobModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" />
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
</div>
More specifically, i want to do that: $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
How can i pass that js variable in php?
I tried different combinations of expressing variable, but the code crashes. If i try to give manually numbers, the code works. To conclude, how can i pass value $('#vis_id') or user_id in $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
Your modal is static and you can't run PHP code in the modal.
I think you must do this.
First change:
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
To:
<div id="job_desc"></div>
And then, in the actions/fetch_jobs.php file when you return data:
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = '".$_POST["user_id"]."' AND job_desc='Fumes'");
if ($result->num_rows == 1) {
$response = "";
foreach ($result as $row) {
$response .= '<span class="glyphicon glyphicon-print"></span>print button';
}
}
return json_encode([YOUREPREVIOUSRETRUN,$response]);
And then in ajax part you must parse json data first variable [YOUREPREVIOUSRETRUN] your previous data and second data you must put it on $("#job_desc").html(second data).
Or, you can use an iframe for this part but I don't suggest that.
From what I can tell by looking at the structure of your modal, you seem to be using Bootstrap, though I am unclear on the version. If it's Bootstrap 5, read on. If not, please add that information to your question, and let me know.
Here's how you can do it all in one call.
First, change the page from which you are opening the modal, so that the modal isn't a part of it. You need to make a separate file to hold the modal contents. Let's call that file remote-file.php. This would be inside that file.
<?php
// your PHP logic goes here - parse the received $_POST parameters, prepare your query - if needed, query your database
// retrieve the data, and place it in variables for later display
require 'conn.php';
$jvid = isset($_POST['jvid'] ? (int)$_POST['jvid'] : 0;
$result = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$result->bind_param("i",$jvid);
$result->execute();
if($result && $result->num_rows == 1) {
// row found, do stuff
$output = '<span class="glyphicon glyphicon-print"></span>print button';
} else {
$output = "Nothing found";
}
?>
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" value="<?=$jvid?>">
<?php
echo $output;
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
Some notes about previous code:
it is assumed that jvid in your database is an INT type colum. Because of that, we could do (int)$_POST['jvid']
if jvid is not an INT but another type of column, we wouldn't do the (int)$_POST['jvid'] bit, and our binding would be slightly different
// prepare the query
$jvid = $_POST["jvid"];
$results = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$results = $conn->bind_param("s",$jvid);
$result->execute();
Next, in the original page, where your buttons are (and where your modal's HTML was), you would need this line of code for the modal.
<div class="modal fade" id="jobModal"></div>
This is going to be a wrapper for your modal content. All the rest will be going inside the remote-file.php. Also, your button element, the one that's opening the modal on click? That button doesn't need to have a data-bs-target attribute, because the following code will work (since you're using jQuery and all).
<button class="btn btn-lg btn-success add-task" id="btn" data-id="1234">Open modal</button>
<div class="modal fade" id="jobModal"></div>
<script>
$(document).ready(function() {
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$('#jobModal').load('remote-file.php',{'jvid':user_id },function(){
var jobModal = new bootstrap.Modal($('#jobModal')[0], {
backdrop:"static",
show:true
});
jobModal.show();
});
});
});
</script>
Final notes:
jQuery version: 3.6.3
Bootstrap version: 5.3.0

How to pass the id from url in php function without refreshing the page?

I have a div which contains a button(Book it).When I press the button I want to add to the current url the id of the item I clicked on.Then get that id to pop up a box with clicked item data without refreshing the page, because I need to pop up in the current page.
Here it gets the treatments Id
<div class="treatments">
<ul>
<?php
global $treatments;
foreach($treatments as $treatment){
echo ' <li>'.$treatment['name'].'</li>';
};
?>
</ul>
<div class="line"></div>
</div>
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" id="hidden_input" name="id_item" value="'.$item['id'].'">
<a class="bookBtn" id="btn"><button>BOOK IT</button></a> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
</div>
Pop up box
<div class="bookDetails">
<div class="details">
<?php
global $iController;
$itemm;
if(isset($_GET['id_item'])){
$itemm = $iController->getItemById($_GET['id_item']);
}
echo'
<h1>Book your treatment</h1>
<p>Treatment Name : '.$itemm['name'].'</p>
<p>Treatment Time :'.$itemm['time'].' </p>
<p>Treatment Price : '.$itemm['price'].'</p>
';
?>
<form action="" method="POST">
<label for="date">Choose your date:</label>
<input type="date" for="date" name="date"><br>
<input type="submit" value="Cancel" id="cancel">
<input type="submit" value="Book Now">
</form>
Jquery code
$(".bookBtn").click(function(){
$(".bookDetails").show();
})
getItemById function
public function getItemById($id){
$sql="SELECT * FROM treatments_item WHERE id=$id";
echo $id;
$items = mysqli_query($this->connection,$sql);
$returnArray = array();
if($items){
while($row = mysqli_fetch_assoc($items)){
array_push($returnArray, $row);
}
return $returnArray[0];
}else{
echo'It doesn't work';
}
}
You can use ajax or mix php and javascript like this:
<script>
$(document).ready(function() {
<?php session_start(); ?>//Remove session_start
if (!<?php $_GET(['id'])?'true':'false'; ?>) {
alert something
} else {
something ..
}
});
</script>
hope this was helpful. :)
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" class="id_item" value="'.$item['id'].'">
<div class="bookBtn"><button>BOOK IT</button></div> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
Note: Never use id same name in one Page i.e., id="hidden_input" // In for loop same name will be generated. It will create bug down the line. Same goes for Input name, instead use class.
$(document).ready(function(){
$('body').on('click','.bookBtn',function(){
var treatmentID = $(this).siblings('.id_item').val();
// $(this) --> it will read the data of the property you have clicked
// .siblings --> adjacent class with name ('.id_item')
$.ajax({
url: 'treatments.php',
type: "get", //send it through get method
data: {
treatmentID: treatmentID
},
success: function(response) {
//operation to show the data in div
//e.g., $('#divId').html(data.name);
$(".bookDetails").show();
}
});
})
})

How to get values from Input tag using JAVASCRIPT ,the value of the input tags are fetched from mysql database using php

the JS alert need to appear whenever i'm submitting the box,the alert message need to consists an value which is get from the input tag,the value of the input tags are fetched from mysql database using php,whenever i'm submitting the form the JS alert displays an message with the first value of the table,whenever i'm submitting the remaining form,also it gives an first value from the table without giving the related values
HOW to get it?
my code is below, check it. php while loop with html tags
<?php
include "connection.php";
$sqlll="SELECT * FROM feedback";
$result=mysqli_query($conn,$sqlll);
$count=mysqli_num_rows($result);
if($count > 0)
{
while($row=mysqli_fetch_assoc($result))
{
?>
<div class="msgshare">
<div class="contentt">
<div class="userr">
<h3><i class="fa fa-user-circle"></i><?php echo $row["username"] ?></h3>
<h5><?php echo $row["img_location"] ?></h5>
</div>
<div class="imgg">
<img src="../images/feedback/<?php echo $row["img_file"] ?>" height="400px" width="400px">
</div>
<div class="likes">
<form class="likeform" onsubmit="likeso()" method="POST" action="likes.php">
<input type="hidden" id="imgile" name="imaggg" value="<?php echo $row["img_file"] ?>">
<?php
$imga=$row['img_file'];
$sql="SELECT * FROM likes WHERE `username`='$user11' AND `image`='$imga' AND `likes`='true';";
$reslt=mysqli_query($conn,$sql);
$row1=mysqli_num_rows($reslt);
$sql3="SELECT * FROM likes WHERE `image`='$imga';";
$rslt=mysqli_query($conn,$sql3);
$count=mysqli_num_rows($rslt);
if($row1 > 0)
{
echo '<button style="cursor:pointer;" name="like" type="submit" id="likepost" class="like-btn"><i id="empty" class="fa fa-heart pink"></i></button> '.$count.' likes';
}
else
{
echo '<button style="cursor:pointer;" class="willlike" name="like" type="submit" id="likepost" class="like-btn"><i id="empty" class="far fa-heart"></i></button> '.$count.' likes';
}
?>
</form>
</div>
<div class="descriptionn">
<p><span class="desc">DESCRIPTION : </span><?php echo $row["img_description"] ?></p>
</div>
</div>
</div>
<?php
}
}
else
{
echo "<p>There is no more Feedbacks are shared...</p>";
}
?>
the following is an JAVASCRIPT code for an onsubmit event.
<script>
function likeso()
{
var iage=document.querySelector('input').value;
var val="imagge=" + iage;
alert(val);
}
</script>
If you change the function call by adding event
<form class="likeform" onsubmit="likeso(event)" method="POST" action="likes.php">
And alter the function itself to use the event
function likeso(e)
{
var iage=e.target.querySelector('input').value;
var val="imagge=" + iage;
alert(val);
}
Also, you cannot duplicate ID values so
<input type="hidden" id="imgile" name="imaggg" value="<?php echo $row["img_file"] ?>">
should be changed to ( remove ID, it's not needed )
<input type="hidden" name="imaggg" value="<?php echo $row["img_file"] ?>">
The same holds for any element to which you assign an ID - it MUST be unique. If the purpose of the ID is to facilitate easy selection in Javascript using document.getElementById then having duplicate IDs makes a nonsense of that because which element should it select? Generally you can achieve most tasks without using an ID so in many cass it is best to remove them - especially when added in a loop.

How to delete values from JSON object array in php?

I have a PHP code and JSON as shown below:
PHP Code:
<?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
$output = array();
$output['en_desc']=$_POST['en_desc'];
$output['code']=$_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
}
?>
<?php if($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<input type="hidden" id="savechanges" name="savechanges" value="1">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else { echo 'Cannot read JSON settings file'; }?>
JSON:
{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}
The following DOM is generated through the PHP/JSON code above:
DOM (HTML):
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
<input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
<input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
The following JS code deletes a row from the DOM on click of a delete button. On refreshing the page,
the deleted row comes back again as everything is rendered through JSON.
JS code:
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
Problem Statement:
The above JS code is deleting the row (on click of a delete button) from the DOM but on refresing the page, everything is rendered again.
I am wondering what PHP code I need to add so that it delete the values from the JSON on saving the form when row is deleted from DOM through JS.
Step 1: User delete the row from the DOM on click of a delete button.
Step 2: On saving the form and rendering the page, that deleted row should not be present.
I know I have to use unset function in order to remove the values from the JSON but I am not sure how I can integrate it in the form.
unset($data->code);
unset($data->en_desc);
You have a typo here:
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
it should be
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
Look at the "s" :)
Edit: you also were saving the new file without actually checking if there is a post happening, here is the full code:
<?php
if (isset($_POST['submit'])) {
$output = array();
$output['en_desc'] = $_POST['en_desc'];
$output['code'] = $_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_committees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if (file_exists('../feeds/ptp-ess_landing_committees.json')) {
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
}
?>
<?php if ($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit" name="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else {
echo 'Cannot read JSON settings file';
} ?>
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>

error filling in testfield using mysql and php javascript ajax

slightly varied question but I have a script that runs and gets data from a mysql db. The end result shows them as buttons, when i click the buttons it gives me an alert with the correct id number correspsonding to whats selected, but when i try to put that into a textfield is isnt the same, its basically the last in the mysql? WHy would the alert show the correct and the updated textfield so totally different information??
The working php that alerts the correct info is :
<?php
include('config.php');
$action = $_REQUEST['action'];
if($action=="showAll"){
$stmt=$dbcon->prepare('SELECT product_id, product_name FROM products ORDER BY product_name');
$stmt->execute();
}else{
$stmt=$dbcon->prepare('SELECT product_id, product_name FROM products WHERE cat_id=:cid ORDER BY product_name');
$stmt->execute(array(':cid'=>$action));
}
?>
<div class="row">
<?php
if($stmt->rowCount() > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<div class="col-xs-3">
<div style="border-radius:3px; border:#cdcdcd solid 1px; padding:22px;"><button type="button" class="btn btn-default" onclick="alert('<? echo $product_id; ?>')"><?php echo $product_name; ?></button></div><br />
</div>
<?php
}
}else{
?>
<div class="col-xs-3">
<div style="border-radius:3px; border:#cdcdcd solid 1px; padding:22px;"><button type="button" class="btn btn-default" onclick="alert('<? echo $product_id; ?>')"><?php echo $product_name; ?></button></div><br />
</div>
<?php
}
?>
</div>
<div>
text : <input id="textField1" type="text" value="0" align="right" size="13"/><br>
</div>
<script>
function display()
{
document.getElementById("textField1").value = "<? echo $product_name; ?>";
}
</script>
But if change the button to use the 'display script' it just shows last in database?

Categories