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!
Related
i am trying to add the output of the following code (on page load)
<?php the_field('object_id'); ?>
to an field of an form with the id="sf_objekt". The field has an optional set value "ID". The output of the code should replace the "ID".
I tried using "append", but with no luck.
Any ideas? Ty!
If I have correctly undestood your question, the following snippet should do the trick:
document.querySelector('#sf_objekt').value = "<?php the_field('object_id'); ?>"
<input id="sf_objekt" type="text" />
Clearly the <?php> tag will be replaced with the output of the PHP function the_field() only if the page is ran through a PHP server.
This code will auto fill in a form with the result of the php script.
<html>
<body>
<form>
<input type="text" id="sf_objekt">
</form>
<script>
document.getElementById("sf_objekt").defaultValue= "<?php echo the_field('object_id'); ?>";
</script>
</body>
</html>
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 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.
Let me Clear what title means:
In my code for a validation purpose of one field dependent on field "t1" I need to auto submit my form once (Just Once). But my below code is submitting it infinite times and I know the reason why its happening.
I guess Reason is everytime the form submits again JS in header runs. Please help me avoid this. Following is my code:
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("CheckForm");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("t1");
temp1.value = "Task";
}
document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm" id="CheckForm" method="Post">
<input type="text" id="t1" name="t1"/>
</form>
</body>
</html>
I tried stopping it using variable like flag and static variables like arguments.callee.count = ++arguments.callee.count || 1 and placing my CheckForm.submit() line in if clause. But nothing worked. Any advice or help is appreciable.
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("t1");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("CheckForm.t1");
temp1.value = "Task";
}
if(window.location.search=="")document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm">
<input type="text" id="t1"/>
</form>
</body>
</html>
Surely your form is more complex than:
<form name="CheckForm">
<input type="text" id="t1">
</form>
That will not submit anything to the server since there are no successful controls (the only control doesn't have a name).
Since the form is just submitting to the same page, you can submit a hidden value like:
<form name="CheckForm">
<input type="text" id="t1">
<input type="hidden" name="hasBeenSubmitted" value="yes">
</form>
Now when the form submits the URL of the new page will include ...?hasBeenSubmitted=yes so you can look for that value in the URL, e.g.
if (/hasBeenSubmitted=yes/.test(window.location.search)) {
// this page loaded because the form was submitted
}
If it exists, don't submit the form again.
So since you are using a post method the easiest way's to handle this is to ubmitted to a new url , however you seem set on keeping the form submitted to the same url in which case is you are using php (or really any other language) you can check if the http request has a post attribute with a value t1
<?php
if(isset($_POST['t1']){
$your_text=$_POST['t1'];
/*do some string checking to make safe and the throw into your database or mdo whatever you please with data
if you wanted to include the ip address of the user you can get a basic and most likely client ip address like so
$ip_address= $_SERVER['REMOTE_ADDR'];
if you are handing a mulitpage form look into php session or similar tech ... cookies is kind of over kill for this scenario
then include a succes page as the form has been submitted
or you could end php with this tag ?> and then have your html and start again with <?
*/
include 'form_submitted.php';
}else{
//this would be the html page that you included in your question and can be handle in same ways as form submitted
include 'my_form.php'
}
?>
Ip address may not be best included as it would stop 2 user from filling out the form if they are in the same LAN for eg. 2 people in same office or same house (if your page is acttual on the worldwide web).
I would take a look at #RobG answer as it he is basically suggesting the same type of thing with a get instead of post
ANyways hope this helps
I need to redirect one page to another page using the form value.
I have this code, which i think is fine for first page and what should i put in the other page where i want to show the data ??
<meta http-equiv='refresh' content='0;url=http://site.com/page.php'>
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php echo $url; ?>">
<script language="JavaScript">document.myform.submit();</script>
</form>
Regards
You can't mix a meta-refresh redirect with a form submission per se.
Also, meta-refreshes are terrible anyway. Since you are already in control of the receiving page, and it's using PHP, use that to accomplish the redirect. Try this:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="submit" value="Go!" />
</form>
Then, in page.php:
<?php
// Act on the input, store it in the database or whatever. Then do the redirect using an HTTP 302.
header('Location: http://example.com');
?>
If you need the form to pass the destination along to page.php, you'll want to sanitize it to prevent a LOT of security problems. Here's a rough outline.
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="destination" value="http://example.com" />
<input type="submit" value="Go!" />
</form>
Then, in page.php (copied re-encoding from answer https://stackoverflow.com/a/5085981/198299):
<?php
$destination = $_POST['destination'];
$url_parsed = parse_url($destination);
$qry_parsed = array();
parse_str($url_parsed['query'], $qry_parsed);
// Check that $destination isn't completely open - read https://www.owasp.org/index.php/Open_redirect
$query = parse_url($destination);
$destination = "{$url_parsed['scheme']}{$url_parsed['host']}{$url_parsed['path']}?" . http_build_query($query);
header('Location: ' . $destination);
?>
I haven't double-checked that code (just wrote it here in the browser), but it should suffice as a rough sketch.
in site.com/page.php
<script>window.location.href = 'newPage.php';</script>
You will have to write this outside the php tags though.
To redirect a page in PHP, use:
<?php
header('Location: url/file.php');
?>
To refresh to a different page in HTML, use:
<meta http-equiv='refresh' content='0;url=http://url/file.php'>
In the content attribute, 0 is the amount of seconds to wait.
To refresh to a different page in JavaScript, use:
window.location.href = 'url/file.php';
When none of these work, follow an anchor link, using HTML:
Click here to go now!
To answer your question, it can be done several ways:
1) Very bad, requires two files, super redundant
HTML file:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Submit the form
document.forms['myform'].submit();
</script>
Page.php:
<?php
// Catch url's value, and send a header to redirect
header('Location: '.$_POST['url']);
?>
2) Slightly better, still not recommended
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Set form's action to that of the input's value
document.forms['myform'].action = document.forms['myform'].elements['url'].value;
// Submit the form
document.forms['myform'].submit();
</script>
3) Still very redundant, but we're getting better
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Simply refresh the page to that of input's value using JS
window.location.href = document.forms['myform'].elements['url'].value;
</script>
4) Much better, save yourself a lot of trouble and just use JS in the first place
<?php
// Start with a PHP refresh
$url = 'url/file.php'; // Variable for our URL
header('Location: '.$url); // Must be done before ANY echo or content output
?>
<!-- fallback to JS refresh -->
<script type="text/javascript">
// Directly tell JS what url to refresh to, instead of going through the trouble to get it from an input
window.location.href = "<?php=$url?>";
</script>
<!-- meta refresh fallback, incase of no JS -->
<meta http-equiv="refresh" content="0;url=<?php=$url?>">
<!-- fallback if both fail (very rare), just have the user click an anchor link -->
<div>You will be redirected in a moment, or you may redirect right away.</div>
Save that with a .php extension, and you should be good to go.