Replace a php variable with textbox input - javascript

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>

Related

How do I save form data to a text file?

I know this question has been asked before, but I'm trying to diagnose why this isn't working. I want to write form data into a .txt file using a post request. I don't know much PHP at all, as this is a quick program I'm patching together. Here's the code:
Javascript:
function submitdata() {
document.querySelector("#val").innerHTML = input.value + ": " + input1.value;
document.querySelector("#submitform").submit(); }
HTML:
<form style="display: none;" method="POST" name="myform" id="submitform">
<input id="val" name="val">
</form>
PHP:
<?php
if(isset($_POST['val']))
{
$data=$_POST['val'];
$fp = fopen('data.txt', 'a+');
fwrite($fp, $data);
fclose($fp);
}
?>
How does your browser know where to send the form data?
You need to specify the php file name in form action attribute.
Edit- added relevant point from comment below.
I have pointed out the obvious error based on what you have provided, but it might not be the only one. Other error is you are using innerHTML on an input element. So this may not set the value for #val (some browsers may set the value, some may not).

How to allow a user to resubmit a form without a warning

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");
?>

javascript submit() command not sending my post data

From this earlier thread I thought I learned that form data could be sent by POST method using javascript submit() command. But I can't get it to work. This demo doesn't make obvious sense with respect to purpose but bear with me. I just wanted to test this specific command which doesn't seem to work for me. Can you please help me? Clicking the regular submit button sends the post data ok but activating the javascript via the link does not.
<html><body>
<?php
$self = $_SERVER['PHP_SELF'];
$posttext = file_get_contents('php://input');
echo "Received input: ".chr(34).$posttext.chr(34)."<br><br>";
echo "<form id='test' action='{$self}' method='post'>";
?>
Please fill in the fields with any text:<br><br>
foo: <input type="text" name="foofield"><br><br>
bar: <input type="text" name="barfield"><br><br>
<input type="submit" value="Submit button works"><br><br>
Submitting by JS not working – why?
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
$(document).ready(function(){
$("a#submitlink").click(function(){
alert("Yes, the link has been clicked. It is not that.");
$("form#test").submit();
});
});
});
</script>
</body></html>
You need to: event.preventDefault(); the default behaviour from the <a>. The problem is if you don't do that, the page reloads cause that is what the <a> tag does. So even you submit the data you also refresh the page where the submitted data gets lost.
$("a#submitlink").click(function(event){
event.preventDefault();
$("form#test").submit();
});
The other solution is to add # in the href of the <a> tag like:
Submitting by JS not working – why?
this will also prevent the <a> tag from doing a refresh.

console.log in php backend

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();

Form submitting when clicked

I am having an issue with this login system, when ever I click the log in button, or the sign up button it re-directs me to a white page with writing on it, That being said it is interfering with my log in action.
Here is the code that I think is causing the issue,
<form method="POST" action="" accept-charset="UTF-8">
on line 16 of the HTML code, I tried to take that code out and it stopped the re-directing but the text boxes went out of place, and the white background/background-box was not there either,
Link, HERE
You want to use preventDefault() if this is a purely Javascript: you should be able to pass the button press event into the listener when you create it:
$('.login').on('click', function(e) {
e.preventDefault();
// Will be executed on press
}
<form method="POST" class="login" accept-charset="UTF-8">
If there's no JS involved in this scenario, then you want to get rid of the action parameter entirely – leaving it as the empty string will still cause it to redirect in some cases.
As Jonathan Lonowski explained above, when the log in / sign up button is clicked, the form will post the data to the page mentioned in the action= attribute. Since this attribute is empty in your form tags, it will re-load the same page, posting the data to itself.
The data will arrive in key=value variable pairs. The variable value will be the contents of the field, the variable name will be the value of the name="" attribute on the element.
For e.g., for this field:
<input id="fname" name="first" value="Bobby" />
The data will be received like this:
$fn = $_POST['first']; //value is Bobby, or whatever user enters
On your page containing the form, add a section at the top like this:
<?php
if (isset($_POST['fname']) == true){
$fn = $_POST['fname'];
echo "Received First Name: " . $fn;
die();
}else{
?>
//Your current page, in its entirety, goes here
<?php
} //close the PHP if statement
?>
That is how you deal with a normal HTML <form> construct.
However, if you wish to use AJAX to communicate with a PHP file without changing the page, then:
(1) There is no need to use a <form> construct, just use a DIV with an input button: <input type="button" id="sub_btn" value="Submit" />
(2) Trap the button press using standard js/jQuery:
$('sub_btn').click(function(){
var fn = $('#first').val();
//etc.
$.ajax(function(){
type: 'post',
url: 'my_php_processing_file.php',
data: 'fname=' +fn+ '&lname=' etc
});
});
In your PHP processor file, the data will be received thus:
<?php
$fn = $_POST['fname'];
$ln = $_POST['lname'];
//Do your MySQL lookup here...
echo 'Received ' .$fn. ' ' .$ln;
(3) IF you do use the form construct, you can still do everything as above, but you will need to suppress the default form action of navigating to the page specified in the action= attribute (an attribute setting of action="" will post data to and reload the same page you are on).
To suppress navigating to the page specified in action= (involves page refresh, even if just action=""), use event.preventDefault(), as follows:
$('#buttonID').click(function(event){
event.preventDefault();
//remainder of button click code goes here
});

Categories