I did also creating a different class. but still not working...
but if I place the '<script>console.log("message here");</script>' will work..
//index.html
assuming that this is a complete code.
<form action="post.php" method="post">
<input type="text" name="name" id="name"/>
<input type="submit" value="submit"/>
</form>
//post.php
<?PHP
if(isset($_POST['name'])){
echo "<script>console.log('".$_POST['name']."');</script>";
}
?>
my problem is , i cant use console.log in submitting a form. but if I did this in redirection It will work..
The Function under my class is ...
public function console($data) {
if(is_array($data) || is_object($data)) {
echo("<script>console.log('".json_encode($data)."');</script>");
} else {
echo("<script>console.log('".$data."');</script>");
}
}
It does not work within PHP because of the missing " around the String argument of console.log.
The output would've been
<script>console.log(name);</script>
instead of
<script>console.log("name");</script>
Solution
echo '<script>console.log("'.$_POST['name'].'");</script>';
If you are trying to debug or see the value that was posted from the front end to back end then you can simply use the chrome inspector.
Right click anywhere in browser and click inspect element.
click on network tab.
submit your form with desired values.
on the left click on the post.php.
Click on the headers on the right and scroll down to find Form Data.
You will have all your post variables listed there with respective values.
You seem to be trying to debug the $_POST variable, If thats the case, then Please note, that console.log() is a frontend debugging tool used in javascript, and has nothing to do with php.
Few good way of checking the content of variables in php.
1. print_r
This will output the content of a variable that can be an array, object or string in a nice human readable format.
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
2. var_dump
This will output the content of the variable with extra respective details like datatypes and length.
var_dump($_POST);
die();
Related
I am trying to make a form on my website where users can submit their name and their score will get saved to a list of highscores. (its a quiz game.)
I tried learning to use forms using w3schools. I used this example: https://www.w3schools.com/php/php_forms.asp
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
with welcome.php looking like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
I literally copy and pasted this example and tried running it and i get this error message:
WelcomeWarning: Undefined array key "name" in [filelocation] on line 4
Your email address is:Warning: Undefined array key "email" in [filelocation] on line 5
However when I replaced all the "post" with "get" it worked. Why? What do I need to do to get it to work with post?
EDIT: Also I left the "post" in the html but i replaced the POST in the welcome.php with REQUEST. It now works, however I think its somehow using GET instead of POSTs because i can see the input in the URL. I definitely need to avoid this.
Maybe this helps
Thank you!
you might running directly welcome.php page.
Replace your welcome.php with
<html>
<body>
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { ?>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
<?php }
else{ ?>
<script> location.replace("yourHtmlFileName.html") </script>
<?php } ?>
</body>
</html>
The W3Schools page you linked has two examples using both POST and GET on the same page.
Considering you said you didn't edit the code, i think it's very likely you copied the HTML code of the second example that uses GET whiile using the PHP code from the first example that uses POST. The code block is right below is.
Frankly, this kind of thing happens to everyone sometimes, make sure you're properly hydrated and carry on!
Another issue which I faced for similar problem was that I have named my html file as "index.html" and also php file as "index.php" because of which php was working on php files first In my case changing the name of file worked out for me
try this php code in your index page:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
echo $name .'Welcome '. $lastname .'your email adress is: '. $email;
?>
As you said, if you literally copied and pasted a example from w3schools and got those errors, check if you're using an VSCode with live server plugin. I just stop using the live server plugin (Five server) and my problem with PHP was gone. For some reason, that plugin was the origin of ERROR: Undefined array key.
I believe it will be a poor question, because most people wants to prevent a form from beeing resubmited but I'll need the exact opposit of it.
That means a user should be allowed to reload a page and the form values have to be posted each time (Session Variables are not possible in this cenario)
Normally the user gets the annoying warning message of the browser.
Is it possible to turn this warning off or simply resubmit the form (eg. with jQuery)
Thanks a lot for your help!
You could overwrite alert and empty the function with alert = function(){}. Check this example:
alert("test");
alert = function(){};
alert("test2");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You cannot turn off this alert (in a good way), but you can redirect to the same form, with all fields auto-compiled, so if you re-do a submit, it won't ask you a confirm.
You can redirect with a _GET parameter, and if your code detect this, it will check for all values to insert in the form.
Something like this:
form.php
<?php
if(!empty($_GET['param'])) {
/* Pseudo code */
$data = query_and_fetch("select 'value_1' as field_1 from yourtable WHERE wfield='".escape($_GET['param'])."' ;");
}
?>
<form method='post' action='process.php'>
<input name='field_1' value='<?=isset($data['field_1']) ? $data['field_1'] : ''?>/>
<input type='submit' value='submit'/>
</form>
process.php
<?php
header("location: form.php?param=123");
?>
This IS a duplicate from Calling a php function by onclick event, but I have a question on it. The answer I had a question on is by timpanix, and basically it won't work.
He said to execute some PHP code in a On Click event do this:
onclick="document.write('<?php //call a PHP function here ?>');"
and call the PHP function. Yet whenever I try it:
<button id="profileinformationbutton" input type="submit" value="Login" onclick="document.write('<?php profileupdated() ?>');"> Update Profile </button>
it prints out ');" > Update Profile, yet I have no clue why. It is inside of a form, and the PHP function looks like this:
<?php
function profileupdated() {
?>
<div id="profileupdated"> Profile Updated </div>
<?php
}
?>
Why would the code be displaying this? Please help! :) Thank You.
EDIT
The code does not seem to be writing Profile Updated to the page, any idea why?
function profileupdated() {
echo "<div id='profileupdated'> Profile Updated </div>";
}
Also if you only want to print this value to your tag why you're using function? Assign it to a variable.
like
$myVar = '<div id="profileupdated"> Profile Updated </div>';
Then use this variable where you want?
you should echo or return your function body. Carefull! I changed quotes!
Your PHP function is writing to the page already, rendering the document.write (javascript) useless. Try this:
<?php
function profileupdated() {
return "<div id='profileupdated'>Profile updated</div>";
}
?>
I do want to note though that you might want to consider a cleaner way of doing this: If you just want to display a fixed text ("Profile updated"), stick to pure client-side Javascript.
Otherwise (if there's logic to be done server-side), you might want to decouple server and client and use an AJAX call and JSON to transfer your data.
PHP is a server side programming language, you are executing the JavaScript on the client side.
If you want to call a PHP script from your JavaScript you need Ajax, f.e. jQuery.
Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>
I have a HTML form and PHP code. In my form, I have a textbox and a textarea. Within both, I have included the "disabled" option. I want both textboxes to remain disabled until the user decides to click the "Edit" button, in which case both textboxes should be enabled so changes can be made and the output once again saved. According to the research I have done, the only way to do this is to use javascript, so I have included the following code within my PHP;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "var oldnotes = document.getElementById('oldnotes');";
echo "oldnotes.disabled = false;";
echo "var record = document.getElementById('record');";
echo "record.disabled = false;";
echo "</script>";
}
I have also tried;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "$('#oldnotes').removeAttr('disabled')";
echo "$('#record').removeAttr('disabled')";
echo "</script>";
}
But no luck :(
I am not receiving any errors, the textboxes just remain disabled after I click the Edit button. Could anyone help me with this? Thanks in advance.
This is a better approach for these kind of problems :
if (isset($_POST['edit'])){
?>
<script type="text/javascript">
var oldnotes = document.getElementById('oldnotes');
oldnotes.disabled = '';
var record = document.getElementById('record');
record.disabled = '';
</script>
<?php
}
<?
<script language='javascript'>
(javascript code here)
</script>
?>
Try use onclick on your Button
<input type="button" name="edit" id="edit" onclick="document.getElementById('oldnotes').disabled=false; document.getElementById('record').disabled=false; return false;">
I hope it helps.
The second approach seems correct, but you're missing ; there. Also, you haven't put any newline characters.
Here's what I suggest:
<?php
if (isset($_POST['edit'])) {
?>
<script type="text/javascript">
alert("Check entry"); // Use this for checking if your script is reaching here or not
$('#oldnotes, #record').removeAttr('disabled');
</script>
<?php
}
?>
You don't need to echo the whole thing. You can simply put it out of the PHP and keep it inside a if block.
Also, I've kept the alert to check if your code structure is proper. If you're getting the alert on clicking the edit button, means you're on the right path. You just need to workout on the JS.
If not, something wrong with your edit button and the form POST
Use single quotes for script type
echo "<script type='text/javascript'>\n";
//javascript goes here
echo "</script>";
use this jquery code:
<script>
$('#oldnotes,#record').attr('disabled','')
</script>
If you want to use JS with PHP you can read here:
how to write javascript code inside php
However: it seems you want the JS to be called on it own accord upon evaluation in the php logic as per the implementation provided.
Technically speaking your JS simply states it should re-enable the controls. Rather add the JS functionality to the OnClick of the submitting control and it should work fine. This is a quicker way of testing the functionality as well.
<a href="javascript:void(0);" onclick="document.getElementById('oldnotes').disabled=false;" >
Once it is clicked it will hide the appropriate control instead of trying to write new JS on the fly that is not executed. This is tried and tested and should work fine for you.
Hope it helps!
you can always make a cookie
use document.cookie()
set the onclick=“” to changing the cookie
and make a script that runs and gets the cookie when you open the site (use window.onload = function(){/*code goes here*/})