This function enables every object's display needed to display an image and it's title, caption, etc in a modal. I need the argument directory in order to make an mysqli request to display the title, caption, etc.
function imageModal(directory)
{
document.getElementById("modal").style.display = "block";
document.getElementById("imageImg").src = directory;
document.getElementById("image").style.display = "flex";
document.getElementById("imageDirectory") = directory;
}
So, with this container I have I want to pass the src given to imageImg to a php variable that I can use to make this mysqli request using the image's directory.
<!-- Picture Container -->
<article id="image" method="post" name="form">
<section id="imageContainer">
<img id="imageImg">
</section>
<section id="imageInformationContainer">
<p style="color: white;"> <?php echo $imageDirectory; ?> </p>
</section>
</article>
this question asked many times. you can search your problem in google and solve your problem. here this is a solution
How do I pass JavaScript variables to PHP?
in short
JS is running on Client Side so JS variables are accessible in Client Side.
PHP is running on Server Side so PHP variables are accessible in Server Side.
if you want to send data from JS to PHP , use AJAX
for functions data, you can initialize variable out of the function scope then use references parameters to change it value inside the function. then use AJAX for send this variable(s) to PHP
Suggest: use array for store variables and send this array to PHP script file.
As I know there is no direct way to pass the Javascript variable or a HTML element value to php variable, as php is server side script and Javascript is client side.
The easiest way to pass the value of directory to php variable would be to submit it to php file or if wanna say it as posting the value to php file.
So my idea is to have a hidden form to store the directory or src value in the hidden field and submit the form then handle the request in php
The HTML elements
<article id="image" method="post" name="form">
<section id="imageContainer">
<img id="imageImg">
</section>
<form name="myform" action="" method="post">
<input type="hidden" name="directory" value="" id="directoryVal">
</form>
<section id="imageInformationContainer">
<p style="color: white;"> <?php echo $imageDirectory; ?> </p>
</section>
</article>
The Javascript function
function imageModal(directory)
{
document.getElementById("modal").style.display = "block";
document.getElementById("imageImg").src = directory;
document.getElementById("image").style.display = "flex";
document.getElementById("imageDirectory") = directory;
document.getElementById("directoryVal").value = directory;
document.forms['myform'].submit();//I am submitting the form here you can do it wherever you want.
}
Now the php
<?php
if(isset($_POST['directory']) $imageDirectory = $_POST['directory'];
//now you can use this $imageDirectory wherever you want and for querying DB aswell
?>
Related
I am completely new to PHP and HTML. I want to send a session variable from PHP to client-side i,e HTML so that I can show which user is currently present.
If I just pass the variable to another php file present at the same location it does happen but I want to exchange the variable from server residing at local host to client at some other location Can any one help me in this
Thanks
let suppose you have a form in html
<form method="post" action="any.php">
<input type="text" name="fname" id="fname">
<input type="submit" value="Submit">
</form>
now in php you are getting input value
<?php
if isset($_POST["name"]){
$_SESSION["sessionname"] = $_POST["name"];
}
?>
so far you have taken input value from html and have stored in session with the name sessionname now you are going to show it in html again
<h1>welcome user : <?php echo $_SESSION["sessionname"]; ?> </h1>
you will need session_start(); on the very beginning of all php pages otherwise you will lose the scope of session variable.
for more information here is link wschools session
To put it simply, I tried to make a website where the user can make an element, and then put it in a div element with the id "box". The js script works perfectly fine, and p elements can be created.
And then, I made a php script where it saves the innerHTML of the "box" div and then save it in a .txt file.
Now, the problem is, the script returns the innerHTML value as the original value, before p elements were added in there.
Here's my php script:
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
I'd suppose the question is already pretty clear. Which is how to get the CURRENT value instead of the ORIGINAL one.
Here's the entire code if it helps:
<html>
<head>
<script>
//The javascript function to add a "para" into a div with the id "box"
function addstuff() {
var parag = document.createElement("P"); // Create a <button> element
var t = document.createTextNode("Lorem Ipsum"); // Create a text node
parag.appendChild(t);
document.getElementById("box").appendChild(parag);
}
</script>
</head>
<body>
<!--Button to call the funtion-->
<button onclick="addstuff()">Add it</button>
<!--The form for the button to work-->
<form action="" method="post">
<!--The div to put the "para"s in. The style only adds borders-->
<div id="box" style="border: 2px solid black;">
<!--A pre-existing paragraph-->
<p>This was here before</p>
</div>
<!--The button to call the php-->
<input type="submit" name="use_button" value="Store in file" style="width:100%;" />
</form>
<!--The PHP-->
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
</body>
</html>
This is not possible:
PHP generates HTML which is then send to the browser.
The browser executes javascript in the page.
There is no PHP in the browser! and server can't know about anything the user does in the browser!!
you can do an AJAX calls with javascript to send data to the server.
Please refer to this answer: https://stackoverflow.com/a/6009208/1275832
You seem to be confused on how <form> element's work. Just adding HTML code to a form client side does not send that HTML code as form data to the server upon form submission. Nor does it automatically update some PHP file.
You would need to add the HTML code to some input control (input, textarea, etc) that is part of the <form>. Then that input's value will be sent to the server on submission at which point you can then use that sent data.
So on the client side you could have a hidden input that will hold the html that is to be sent. Updating it every time you need to change the html
HTML
<form action="" method="post">
<input id="boxinput" type="hidden" name="boxinput"/>
<!--- Rest of form -->
</form>
JS
//cache these so you don't need to call getByElementById every call
var box = document.getElementById("box");
var boxinput = document.getElementById('boxinput');
function addstuff() {
var parag = document.createElement("P");
var t = document.createTextNode("Lorem Ipsum");
parag.appendChild(t);
box.appendChild(parag);
//update the input field
boxinput.value = box.innerHTML;
}
And then on server side, get the input data from the $_POST global and use it as needed
if(isset($_POST["use_button"])) {
$boxHtml = $_POST['boxinput'];
//..
fwrite($file,$boxHtml);
//..
}
Obligatory note: if you are going to be using this saved html in some way, eg echoing it back on some new page, you should sanitize it before saving/using it. Or only showing it in a sandboxed frame (kinda like how Stack Overflow has sandboxed its Stack Snippets)
This is not possible.
But you can handle it manually by using query parameters that are same in php and javascript
Generate your page elements by query parameters.
For example when you got test.php?div=box generate a page that contains a <div id='box'>
There is so many solutions like this
I'm searching for the best solution to display information which I store in PHP variable (which I get from a MySQL DB).
I was thinking to use jQuery. My questions:
With the input field I receive the number of the Member.
I store a new variable called $imgMember with the img name.
Questions:
I want to display this image each time a user enters a number at <div class="boxImageMember"> (which I already validated through PHP and made a variable ($imgMember) of it.
How should I access it? Do I need to store those variable with AJAX? Internal/external jQuery? Or do I need to think otherwise? Im stuck in my head.
Im totally stuck with the way I how to process this.
HTML:
<div id="header">
<div class="header-content">
<img src="img/logo-dqmih.png" width="60px">
</div>
</div>
<div class="container">
<div class="boxImageMember">HERE I WANT TO DISPLAY A USER IMAGE</div>
<div class="boxInformationMember"></div>
<form action="" method="post">
<input type="text" id="MemberNumberEntry" name="staffNumber">
<button type="submit" name="action">
</form>
</div>
jQuery:
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
console.log(MemberNumberEntry);
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
Your jQuery script would do something like this
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
//console.log(MemberNumberEntry);
$.ajax({
url: '/your-php-script.php',
method: 'POST',
data: {
MemberNumberEntry: MemberNumberEntry
},
success: function(response){
//If call goes well, you use the image here.
}
});
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
You're basically sending an HTTP POST request to your PHP script that will accept the image ID like a normal post request, using $_REQUEST or $_POST.
There are tonnes of options to configure with jQuery, you can look at the docs here. For more information on working with images in PHP and AJAX, this answer is useful.
I am currently making a webpage where I want the user to view different database results depending on which result they pick. The results will either be picked through a button, or by a query typed in by hand into a textarea.
I have the connection to the database and everything set up in an external PHP script which I am currently linking in to my site using "require".
Within this PHP script I have a "query" variable.
I would like for this variable to be dependent on whatever value is entered by the user.
I suppose this should be doable using some sort of $query = $POST['entry'] and some kind of Ajax call in a javascript? I just don't know how this whole thing should be fitted together.
If we assume that my menu and container looks something like this, where getData.php is where the $query variable is and what returns the database data.
<div id="menu">
<textarea class="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input class="menuButt" type="button" value="Submit" onclick="JavaScript:ChangeDivVal();"/>
</div>
<div id="container">
<?php
require 'getData.php';
?>
</div>
Here is a picture if that helps my explanation of what I want to do.
I'm very grateful for any help I could possibly get!
//Ambrose
There are neat and simple mechanisms to pass the input of your textarea (the query string) to php and return the database output back to javascript. From there you then can easily attach it to any dom node you wish.
I personally do stuff with jQuery since its so handy. You might wanna use the load function for your simple purpose:
$( document ).ready(function() {
$('#querySubmitButton').click(function (evt)
{
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
// load data received from php script into the dom container
$('#container').load('getData.php', { query:myQuery, anotherVar:null });
});
});
The load function simply loads everything the desired script outputs into the given domnode. You can add as many parameters as you want in the second argument and could even use a callback to perform some more js after loading.
For details see http://api.jquery.com/load/.
Oh and by the way I changed your html to this:
<div id="menu">
<textarea id="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input id="querySubmitButton" type="button" value="Submit"/>
</div>
<div id="container"></div>
In your getData.php (which I assume produces plain html) you can then use php's $_POST var to get the query.
$query = $_POST['query'];
I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.