PHP: How to get CURRENT innerHTML? - javascript

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

Related

How to pass data from a JS function to PHP

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
?>

Change paragraph text from another html site

I'm making a simple html site with some text and a php-login area. When logged in successfully (which already works) I come to a site where I want the possibility to change paragraph text on the landing page.
I tried this code, but I lets me only change paragraph text on the same site, not on the landing page. Is this possible?
<script type="text/javascript">
function change() {
document.getElementById("name2").innerHTML = "New text inside the text element!";
}
Button to trigger the event
<input id="button1" type="button" value="1" onclick="change()">
well, document refers to the site, not the landing page, right?
besides, if you want to make a change permanent, you should retrieve the text from somewhere you save it in, and not only change what is currently displayed
You could definitely pass a cookie to the Global session variable and you can use an if statement to check on the new page if the session is available and then you can render a new markup.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
if you set these variable then you can have access to them on each page and can use it to manipulate your data

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Ckeditor content retrieval using PHP

I've been trying to integrate ckeditor in my php website, and I've encountered the following issue.
Essentially, the content in ckeditor wouldn't appear in the $_POST variable after submitting the form.
I looked the issue up and apparently one has to update the form field with a small piece of code.
So I wrote the corresponding script and linked it to the submit button in order to get the result I want, but $_POST still shows up as empty.
I'm inexperienced with Javascript so the error probably lies there. Any ideas?
cktest.php:
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="http://localhost/ECLIPSEPHP/ckeditor/ckeditor.js"></script>
</head>
<body>
<form action = <?php echo $_SERVER['PHP_SELF']
?>>
<textarea name="test" id="test" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<input type = "submit" name = 'submitButton' id = 'submitButton' value = 'Submit'>
<script>
// Replace the <textarea id="test"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'test' );
</script>
<script type = "text/javascript" src = "http://localhost/ECLIPSEPHP/js/update.js"></script>
</form>
</body>
</html>
<?php
var_dump($_POST);
//echo $_POST['test'];
?>
The javascript supposed to handle the onclick event :
function updateAllMessageForms()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
}
var submitButton = document.getElementById('submitButton');
submitButton.onclick = updateAllMessageForms;
There are quite a lot of problems with that code. The first thing to check is to add a method to that form tag: method="post".
See what <form action = <?php echo $_SERVER['PHP_SELF'] ?>> renders. It looks like it could be a wrong. I'm guessing it should be more like <form action="<?php echo $_SERVER['PHP_SELF'] ?>">.
Don't use ' for HTML attribute delimiters, use " instead: 'submitButton' --> "submitButton".
If you edit the updateElement a little: CKEDITOR.instances[instance].updateElement(); alert(1); - do you see the alert? If not, that code is not being called and you need to edit it so that it is.
Don't add spaces between your attribute name, the equals symbol and the value. That looks very strange and could be interpreted wrong or it could send Internet Explorer into quirks mode. Try to change this style: type = "submit" to type="submit" and keep up with that style.
Remember that it's often a good idea to look at the Rendered source in the browser to see what the browser actually gets. Happy coding!

Calling javascript function from ajax page

I have a form where I upload a file through an ajax call containing an API call.
If the API is successful I want to update a table containing the list of files.
I was thinking of calling a javascript function inside the ajax page, but what I get back is that the function in undefined, I fixed that by putting clarifications.js before the javascript function.
Here is the form (at the top of the page I included the js file containing the javascript function):
<div class='input_table_title'>Upload file:</div>
<div style='float:left;'>
<form name='upload_my_files' action='ajax/clarifications/handle_upload.php' method='post' enctype='multipart/form-data' target='upload_target'>
<input type='file' name='file_upload' />
<input type='hidden' name='notification_id' value='<?php echo $value->NotifiNumber; ?>' />
<input type='submit' value='Upload'>
</form>
<iframe id='upload_target' name='upload_target' src='' style='width:0;height:0;border:0px solid #fff;'></iframe>
</div>
in handle_upload.php I make the API call and at the end of the page I close the php, put the clarification.js and calling the function.
<script src="(position)/clarifications.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
createTable("<?php echo $outcome ?>", "<?php echo $uploaded_filename ?>");
</script>
in the clarifications.js file I declare the function (as I said earlier I included the js file in the form page):
function createTable (result, filename) {
if (result == 'success'){
var success = document.getElementById('clarification_success');
success.style.display = "block";
success.innnerHTML = "File "+filename+" successfully uploaded.";
// Update the list of uploads
var list = document.getElementById('table_clarification');
var myElement = document.createElement("td");
myElement.innerHTML = filename;
list.appendChild(myElement);
}
return true;
}
clarification_success is a div where I want to display a success message.
table_clarification is the id of the table where I want to add the row with filename uploaded
The upload is successful but the function createTable is not defined. Edit: Solved
The other problem that I'm having is that the function can't find the id "clarification_success", I think because is looking for it in the instead of the normal page. Am I correct? If yes how can I solve it?
Note: I'm afraid I can't use jQuery, only Javascript please.
if i understood right - the iframe content should be the separate page. this page is dynamicaly constructed on server and returned to client as a post answer.
this page should probably contain <script src="(path)/clarifications.js"></script> in the header

Categories

Resources