I have a javascript function that is triggered when a button is pressed. That function loads an external page with the values of a field.
My problem is that when I refresh the page my clicked button is reset. What I want is to keep that button value when it refreshes so it still loads that page and only reset when another button is pressed.
js code
<script>
$(function() {
$("button.btn").click(function() {
var tip = document.getElementById("tip5").value;
var id_local = document.getElementById("id_local").value;
$("#tipuri_rezervare").load("select_tip_rezervare.php?id=" + id_local + "&tip=" + tip);
});
});
</script>
php code
$stmt = $dbh->prepare("SELECT *
FROM Tip_Rezervare
INNER JOIN Local ON Local.ID_Local=:id_local
INNER JOIN Leg_Tip_Local ON Tip_Rezervare.ID_Tip=Leg_Tip_Local.ID_Tip and Leg_Tip_Local.ID_Local=:id_local");
$stmt->bindParam(':id_local', $id, PDO::PARAM_INT);
$stmt->execute() ;
while ($row = $stmt->fetch()) {
$local = $row['Denumire_Local'];
echo'<button type="button" class="btn btn-danger" id="tip'.$row['ID_Tip'].'" value="'.$row['ID_Tip'].'">'.$row['Nume'].'</button>';
}
?>
</div>
<form id="tip" method="post">
<input type="hidden" name="id_local" id="id_local" value="<?php echo $id;?>">
<div id="tipuri_rezervare"></div>
You need to make an Ajax call & set a session during the result fetch from external page but before page refresh and read the session values after page refreshed & set it on page.
Related
In my portfolio I implemented a PHP script that generate some div that contain images of some works.
When users click on a div, there is a redirect on a details.php page that contains work details. How can I set $_SESSION variable values, in order to use them on details.php?
PHP scipt:
$query2="SELECT * FROM Posts WHERE Category='".$record1['Category']."' ORDER BY data_pubb DESC";
$esito2 = mysql_query($query2);
while($record2 = mysql_fetch_array($esito2))
{
echo "
<div class='col-sm-4 job'>
<div class='container hover-image-container'>
<a href=''>
<img src='".$record2['static_img']."' data-src='".$record2['static_img']."' data-animated-src='".$record2['dinamic_img']."' width='100%' height='100%' />
<div class='overlay'>
<div class='text'>".$record2['title']."</div>
</div>
</a>
</div>
</div>
";
}
You would need to use JavaScript to detect the onclick and use AJAX to start the session.
For starters, add session_start(); to the top of your page.
Then add an onclick event to your div:
<div class='col-sm-4 job' onclick='startsession()`>
Then define the startsession() function:
function startsession() {
$.ajax({
var name = ''; // the name of your session e.g $_SESSION['counters'];
var value = ''; // the value of your session e.g 10
url: "sessionstart.php",
data: {session: name, value: value},
success: function(data){
// your success function
}
});
}
Then on sessionstart.php:
<?php
session_start();
$_POST['name'] = $_POST['value'];
<?
session_start();
//Set session
$name = $_POST['name'];
$_SESSION['user'] = $name;
//Fetch session
echo $_SESSION['user'];
You can perform an AJAX Request on click of the div. Pass the data in this request that you want to set in the Session variable. Once you get the response back you can then visit the details.php and access the Session variable that got set.
For onclick either you can set
<div ... onclick="functionName()" ></div>
Or, set an ID or class and attach an event listener to it.
<div id="myDiv">...</div>
$('#myDiv').on('click',function(){
//perform the ajax request here.
});
I'm trying stop multiple submit buttons.I'm new to php and javascript.I did try lot of different options of stack overflow answers.I did check session token but it is not working for me because i'm submitting the form from JavaScript.You can see the code to disabled button . When i click the button it is disabled and form submited but it is not reaching the btn-paid code of php. Please help.
php code1:
<?php
include('sessionstart.php');
include('session.php');
include('processtransaction.php');
?>
<script src="js/mytransaction.js"></script>
php code1 will call the javascript and javascript has the form submit. If the form is submitted then it disable/(session token process) the button paid and it should call the code of btn-paid.
javascript code mytransaction:
$(document).ready(function() {
var table = $('#myTransactionitems').dataTable(); //Initialize the datatable
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'transactions',
dataType: 'json',
success: function(s){
console.log(s);
table.fnClearTable();
for(var i = 0; i < s.length; i++) {
var disp1 = '';
if (s[i][4] != 'Reserved') {
disp1 = 'display:none;'
}
table.fnAddData([
"<form method='post' action='reservationdetails'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'></input><input type='submit' id = 'btn-bank' name='btn-bank' value = '"+s[i][0]+"' class='btn btn-link'>\
</input></form>",
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
"<form method='post'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'><input name = 'donationid' type='hidden'\
value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\
value='"+s[i][3]+"'></input></input><input type='submit' id = 'btn-paid' name='btn-paid' value = 'Paid' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-success pull-left '>\
</input></form><form method='post'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'><input name = 'donationid' type='hidden' \
value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\
value='"+s[i][3]+"'></input><input type='submit' id = 'btn-cancel' name='btn-cancel' value = 'Cancel' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-danger pull-right'>\
</input></form>"
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
php code2 processtransaction:
<?php
if (isset($_POST['btn-paid'])) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$conn = $db_handle->connectDB();
$query = "update MYTRANSACTION set STATUS =? where DONATION_ID=? AND ID=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("sii",$status,$donation_id, $transaction_id);
$stmt->execute();
$stmt->close();
$db_handle->closeDB($conn);
}
?>
If you want to prevent the user from clicking twice before page ends loading (causing 2 posts), it would better to use javascript. As you are already using jQuery, you can do the following:
$("input[type='submit']").click(function(e) {
e.preventDefault(); // Prevent the page from submitting on click.
$(this).attr('disabled', true); // Disable this input.
$(this).parent("form").submit(); // Submit the form it is in.
});
Edit:
To cater for someone immediately submitting before page loads completely (ie before JS loads), you can make the following changes.
In your HTML form, add disabled to your submit button:
<input type="submit" value="Submit" disabled />
And change your JS to the following:
$("input[type='submit']").attr('disabled', false); // Enable this input.
$("input[type='submit']").click(function(e) {
e.preventDefault(); // Prevent the page from submitting on click.
$(this).attr('disabled', true); // Disable this input.
$(this).parent("form").submit(); // Submit the form it is in.
});
What this does is makes the submit button disabled until JS has loaded. Once JS loads, it will enable the submit button and then remaining things will work as before.
I have a button, when pressed has to call a function from an external php file and load it in a new page.
When I click the "SHOW" button on my index.php page, it shows me the message hold in "mesaj", but displays it in index.php page (that I don`t want!).
What I want to accomplish is when I click on the "SHOW" button on my index.php it shows me the content of the message into another php page, named - for eg - content.php. I want to set the href.
index.php
<input type = "button" class="btn btn-primary" id = "show" onClick = "show()" value = "SHOW"/>
functions.php
function show()
{
database();
$sql = "SELECT title FROM `Articles`";
$titleSql = mysql_query( $sql ) or die("Could not select articles:");
$html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';
while ($title = mysql_fetch_array($titleSql)) {
$html .= '<li class="list-group-item">'.$title["title"].'</li>';
}
$html .= '</ul></div></body></html>';
echo $html;
//die(json_encode(array("mesaj" => "Entered data successfully ")));
}
function.js
function show(){
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
//$(document).html(mesaj);
document.write(mesaj);
});
}
There is no reason (apparently) to go from PHP to JS in your case. You'd use JS $.post if you need a change of the DOM after it loaded. You can just do this:
<a href="function.php" class="btn btn-primary" id="show"/>SHOW</a>
This works without going thru JS.
If you want to use BUTTON and go via JS then do this:
<input type="button" class="btn btn-primary" id="show" value="SHOW"/>
jQuery:
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php';
});
Plain JS:
document.getElementById("show").onclick = function(){
window.location.href = 'function.php';
}
As a note, be careful because <button> if used inside a form when clicked submits the form. That's why the e.preventDefault();
Let's say you have multiple functions in your function.php and you need to call one a specific one, I would do this:
function.php
if(isset($_GET['fn1'])){
function functionOne(){
//do something
}
}
if(isset($_GET['fn2'])){
function functionTwo(){
//do something else
}
}
And call it this way:
<a href="function.php?fn1" class="btn btn-primary" id="show"/>SHOW</a>
or
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php?fn1';
//window.location.href = 'function.php?fn2';
});
When I click a button, I'm trying to get the name of the button to display on the next page. So far, I've managed to display the button name in an alert box but not sure how to get it to appear on another page.
<script>
$(document).ready(function(){
$("#test").click(function(){
alert("Text: " + $("#test").text());
});
});
</script>
The code below gets modules that the logged in user is registered to and displays two buttons. I'm trying to display the button label(subject names) on another page rather than in the alert box. So when I click on a button, the label name appears on the next page.
$sql = DB::getInstance()->get('modules', array('username','=' ,$user->data()->username));
if(!$sql->count()){
echo 'No data';
}else {
foreach ($sql->results() as $sql){ ?>
<p> <?php echo $sql->name; ?></p>
If you are trying to navigate to another page on click, you can just modify your jquery event handler to this and pull it out of the query params on the next page.
$(document).ready(function(){
$("#test").click(function(){
window.location = "your_next_page.php?name=" + $("#test").text();
});
});
on your other page.
<?php
echo $_REQUEST['name'];
?>
Save the $sql->name to session data and use this another page
$sql = DB::getInstance()->get('modules', array('username','=' ,$user->data()->username));
if(!$sql->count()){
echo 'No data';
}else {
foreach ($sql->results() as $sql){
$_SESSION['name'] = $sql->name;?>
<p> <?php echo $sql->name; ?></p>
another_page.php
session_start();
echo $_SESSION['name'];
I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>
change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});
If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.