I just want to pass variable with JavaScript to another new PHP page. My php page name are changed through .htdaccess and are not ending with .php example [http://localhost/ahlain_new/budget_by_mi?&b_year=2022].
I have tried to search with google but unfortunate get answer
I am getting error while sending variable to new page "Notice: Undefined index: b_year in C:\xampp\htdocs\ahlain_new\views\modules\budget_by_mi.php on line 37"
My code is
.htdaccess
RewriteRule ^([\w-]+([^/]))$ index.php?rute=$1
php when any page is clicked
if (isset($_GET["rute"])) {
if (
$_GET["rute"] == "budget_by_mi"
}
include "modules/".$_GET["rute"].".php";
}else {
include "modules/404.php";
}
JavaScript to send variable
$('body').on('click','#by_mi',function openWin(){
var b_year = document.getElementById('budget_year').value;
var url = "/ahlain_new/budget_by_mi?&b_year=" + b_year;
myWindow = window.open(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button class="btn btn-outline-secondary" id="by_mi" type="button" style="height: 28px">Budget BY MI CAT</button>
<!-- -------NEW Page ----- ?>
<?php
$b_year = $_GET['b_year'];
echo $b_year;
?>
Thank you in advance for your support
Related
I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}
I'm building a photography portfolio. Some of my images have nudity, so I want to hide those by default until the user clicks a "Toggle Worksafe Mode" button.
I can do it with a standard form post (and sessions), but that causes "confirm form resubmission" errors when the user backs or reloads. I'm trying to figure out an AJAX post instead to avoid that.
UPDATE: This is the working code. Please note that this does NOT work with the "slim" jQuery distro; that's one of the main reasons I was having trouble.
Image Index Page:
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'] {
$_SESSION['Worksafe_Mode'] = 1;
}
?>
<!-- other page content -->
<script src="scripts/jquery-3.2.1.min.js"></script>
<!-- other page content -->
<button type="button" id="Worksafe_Button" name="Worksafe_Button">
Toggle Worksafe Mode
</button>
<script>
$('#Worksafe_Button').click(function() {
$.post("worksafe_mode_toggle.php")
.done(function(data) {
window.location.href = window.location.href;
});
});
</script>
<!-- other page content -->
<?php
$Connection = Connect();
$query = mysqli_query($Connection, 'SELECT uri, name, nsfw FROM images ORDER BY uri');
while($row = mysqli_fetch_assoc($image)) {
if ($_SESSION['Worksafe_Mode'] == 1 && $row['nsfw'] == 1) {
echo 'If you are over 18, toggle Worksafe Mode to view this image';
}
else {
echo '<img alt="'.$row['title'].'" src="../'.$row['uri'].'/s.jpg" srcset="../'.$row['uri'].'/m.jpg 2x">';
}
}
?>
worksafe_mode_script:
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 1) {
$_SESSION['Worksafe_Mode'] = 0;
}
else {
$_SESSION['Worksafe_Mode'] = 1;
}
}
I think ajax is a good approach in your case.
I might do something like display a page of SFW images as the default, along with the toggle button.
When they click the button it triggers an ajax request to the back-end that sets/un-sets the session value in toggleWorksafe.php. Finally it triggers a page refresh.
During the page refresh the PHP code checks whether the session variable is set and shows either the filtered or unfiltered set of images, and changes the button's text to match.
To implement:
Include jQuery in the <head> section (jQuery simplifies the ajax call):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'])) {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
<button id="workSafe" type="button" name="Worksafe_Toggle_Button">
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo 'Hide NSFW images';
}
else {
echo 'Include NSFW images';
}
?>
</button>
<!-- display safe images by default -->
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo '<br/><br/>Showing NSFW images';
}
else {
echo '<br/><br/>Showing safe images only';
}
?>
<!-- any other page content here -->
<script>
$('#workSafe').click(function() {
// ajax request to page toggling session value
$.post("/toggleWorksafe.php")
.done(function(data) {
window.location.href = window.location.href; // trigger a page refresh
});
});
</script>
</body>
</html>
toggleWorksafe.php:
<?php
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 'yes') {
$_SESSION['Worksafe_Mode'] = 'no';
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
there are a couple of ways to do this and it related to how you hide or load you images.
1. simple method
if you don't care about the user's age, and just need to toggle, then you can do it with just a js variable, a cookie, and two version of link. with this, you don't hide images, but loads them. the filtering is done in the server, where you can use database query or a simple folder separation. for example:
var nsfw = read_cookie('nsfw', false); // not an actual js function, search for how to read cookie in js --- read cookie value, default to false
function loadImage(nsfw){
if (nsfw){
$.get('nsfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
} else {
$.get('sfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
}
}
and in you button click event:
nsfw = !nsfw;
// clear the image first if needed
$('#container').empty();
loadImage(nsfw);
2. another simple method, but not as simple as the #1
you can also do it with only one link that returns a list of images with the type of it, such as nsfw or other things.
note: this method still uses cookie
for example the returned list is like this:
[
{"url": "some-image-1.jpg", "nsfw": "true"},
{"url": "some-image-2.jpg", "nsfw": "false"},
{"url": "some-image-3.jpg", "nsfw": "true"},
{"url": "some-image-4.jpg", "nsfw": "false"},
{"url": "some-image-5.jpg", "nsfw": "false"},
{"url": "some-image-6.jpg", "nsfw": "true"}
]
then you just render it when the conditions are met.
function renderImage(nsfw){
$.get('image-list-url', function(resp){
list.forEach(function(val, key){
if (nsfw || !val.nsfw){
$('#container').append('<img src="' + val.url + '/>');
}
});
});
}
and many other methods that are too long to explain, such as using Angular, React, or Vue
still uses cookie for between reloads or backs, and does not regard user's age.
as for the session based approach, you only need that if you need to verify your users age
that is if you have a membership functionality with DOB (date of birth) data in your site, if so, you can use #KScandrett 's answer
Confirm form resubmission happens because you do not perform a redirect after a successful form submission.
Take a look at this wiki page to see how to do it right. https://en.wikipedia.org/wiki/Post/Redirect/Get
I would like to recreate several like button that saves count in a file.txt but that doesn't work :/
<?php
function getClickCount()
{
return (int)file_get_contents("counter.txt");
}
function incrementClickCount()
{
$counter = getClickCount() + 1;
file_put_contents("counter.txt", $counter);
}
?>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks = 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()" title="Vous aimez la couverture?" class="btn"><img id="heart" src="https://trello-attachments.s3.amazonaws.com/568304b85fa72dcb958a1edf/584acfc48b82595af77f2030/6257bf1efec79d5baf22309f8f327ce5/favorite.png" /></button>
<p><a id="clicks"><?php echo getClickCount(); ?></a></p>
DEMO HERE
Thanks in advance for your help, I am looking since days on the web to find it but I don't...
Alexander
counter.php
<?php
function getClickCount() {
return (int)file_get_contents("counter.txt");
}
function incrementClickCount() {
$counter = getClickCount() + 1;
file_put_contents("counter.txt", $counter);
}
if(!empty($_POST)) {
if($_POST['click'] == 'true') {
incrementClickCount();
echo getClickCount();
} else {
echo getClickCount();
}
}
?>
counter.txt
0
index.php
<html>
<head>
<title>Click Counter</title>
</head>
<body>
<button type="button" onClick="onClick()" title="Vous aimez la couverture?" class="btn"><img id="heart" src="https://trello-attachments.s3.amazonaws.com/568304b85fa72dcb958a1edf/584acfc48b82595af77f2030/6257bf1efec79d5baf22309f8f327ce5/favorite.png" /></button>
<p><a id="clicks"></a></p>
<script>
function onClick() {
loadClicks(true);
}
function loadClicks(isClicked) {
var click = isClicked === true ? true : false;
$.ajax({
url: 'counter.php',
type: 'POST',
data: {
'click': click
},
success: function(response) {
$('#clicks').text(response);
}
});
}
loadClicks(false);
</script>
</body>
</html>
Code Explanation
Whenever you click the button, there is an ajax request sent asynchronously in the background to counter.php. This PHP file receives request and process accordingly.
Here in the code, we send a single data to the PHP file in the ajax POST request which is a boolean data that is set based on the condition like if the button is clicked.
In PHP file, you will check a condition if the request is happened by button click or else other. If it is by button, you will increment the click and send the click counter value in response else you will only send the value.
You will notice I've called loadClicks function with the parameter true in onClick function and false outside the function meaning that I first call the loadClicks(false) as soon as the script is started its execution to load only the clicks value and later when I click the button loadClicks(true) is invoked meaning increment and fetch the value.
You will understand the code when you go through them carefully.
At first glance, I see 3 problems with your script.
1) You are mixing JavaScript and PHP. JavaScript runs on browsers and PHP runs on servers. If you want to exchange data between those parts of your script you need to make a server call from the JS part to the server, e.g. by using AJAX. A simple HTML request in JavaScript to a PHP script will work too.
2) Also your <button> tag needs to be embedded in a <form> should point to a script to be executed (can be the same script).
3) You never seem to call incrementClickCount(), at least not in the part shown here.
Suggestions
The would code everything in PHP and then address the other two points. Or you need to implement some form of client / server communication.
This PHP code works when I use HTML <input type="file">, but not when I use the jQuery file upload script at the very bottom.
I believe all .js & .css files are accounted for and working (tested)
I believe the uploadUrl: 'doc_upload.php', fileInputName: 'userfile' are correct. Don't know 'cause no errors are showing.
Using echo getcwd();, I believe I'm using correct paths
I'm only uploading a 1 kb .TXT file
I get no errors and all error reporting is on and maxed
One thing that is also not working, which I'm saying to possibly give a clue, is the upload & cancel buttons next to the file name are not showing all though clicking on them does seem to work.
Echo'ing $_POST shows me nothing on submit, but I think that's a javascript thing; not sure as I'm a beginner (3-months).
PHP page
$filename = $_FILES['userfile']['name'];
$tmpname = $_FILES['userfile']['tmpname'];
$filesize = $_FILES['userfile']['size'];
$filetype = $_FILES['userfile']['type'];
$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()) {
$filename = addslashes($filename);
}
$filename = preg_replace('/[ ]/', '~', $filename);
$document_folder = $_SESSION['users_id'];
$destfile = "../_documents/".$document_folder."/".$_FILES['userfile']['name'];
move_uploaded_file( $_FILES['userfile']['tmpname'], $destfile );
HTML page
<link type="text/css" rel="Stylesheet" href="../jqx.base.css" />
<script type="text/javascript" src="../scripts/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxfileupload.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#jqxFileUpload').jqxFileUpload({ width: 300, uploadUrl: 'doc_upload_jquery.php', fileInputName: 'userfile', autoUpload: true });
});
$('#jqxFileUpload').on('uploadStart', function (event) {
var fileName = event.args.file;
$('#log').prepend('Started uploading: <strong>' + fileName + '</strong><br />');
});
$('#jqxFileUpload').on('remove', function (event) {
var fileName = event.args.file;
$('#log').prepend('Removed file: <strong>' + fileName + '</strong><br />');
});
$('#jqxFileUpload').on('uploadEnd', function (event) {
var args = event.args;
var fileName = args.file;
var serverResponce = args.response;
});
</script>
</head>
<body>
<div id="jqxFileUpload">
</div>
<div id="log" style="margin-top: 20px;"></div>
<br />
</body>
</html>
mdpalow -
You probably aren't getting any errors or output because of the if statement at the top:
if (isset($_POST['submit']) && $_FILES['userfile']) {
Try putting this at the top to output all of your post variables so that you can determine what post variables are actually being sent (if any):
print_r($_POST);
I have done file uploads before but not with this specific library - my guess is that its just sending mulipart data instead of POST variables. Looking at the preview headers in the browser developer tools will also shed light as to what data is being sent.
The problem is that jQuery plugin uploads file via AJAX. In order to fix the issue please follow next steps:
Keep your HTML and PHP code in separate files.
In new PHP file remove isset($_POST['submit']) validation as there is no submission.
I am trying to learn jsp. I know a little bit java and I dont know much about html tags so I simple use java codes as much as I can. What I am trying to do there is getting data from variables from text boxes and using them as string.
var text1 =<% request.getParameter("locationId"); %>;
<%
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>
Scriptlet is executed before any data about webpage get sent from server to client. Whatever you want to do you need to send postback to server (with forms or ajax call). I usually use jQuery so my answer will use it but feel free to modify it to use native JS code. First, I would create a page on server called something like createJsonObject, call it from client with $.ajax (type: "POST") and passed my argument as object
{varID: varID}
On server I would place my JSP on that page, read argumants upon page load, execute function and return object with data to client. In .done() I would do something with that data (display them in form, save them in JS variables...).
Hope this helps you out.
Example (Just showing how you can use Ajax with form example)
HTML form:
<form name="formName" method="post" action="">
<input type="text" name="name" id="firstName" value="" />
<input type="text" name="lastName" id="lastName" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
Ajax Post:
$("#update").click(function(e)
{
e.preventDefault();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var dataObject = {};
dataObject.firstName = firstName;
dataObject.lastName = lastName;
$.ajax({
type:'POST',
data:dataObject,
url:'returnData.php',
success:function(data)
{
alert(data);
}
});
});
PHP:
<?php
$receivedObject = json_decode($_POST['data'], true);
$name = $receivedObject['firstName'];
$lastName = $receivedObject['lastName'];
echo $name . ' ' . $lastName;
?>
I've not test this, so there might be somewhere i've gone wrong. But try something like my example and just ask if you need any help.
Ali, you can not use a javascript variable into jsp scriplate.
<%
String locationId=request.getParameter("locationId");
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>
but vise versa is possible you can use JSP variable into you javascript code.like this.
<script>
var locationId='<%=request.getParameter("locationId")%>';
alert(locationId);
</script>