I have a basic HTML form with one input text field, along with a submit button. Now, I want to use JavaScript to display the content entered by the user in the text field after form submission.
Here's the code of my form:
<form method = "POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" onclick = "postResul()" />
</form>
On clicking the submit button, the postResul() function is called:
<script>
function postResul()
{
var htmlString="<?php echo $_POST['tweet1']; ?>";
alert(htmlString);
}
</script>
Now, both these code snippets are stored inside a PHP file. However, on submitting the form, the data entered in the input form field doesn't get displayed. I'm displaying the $_POST['tweet1'] variable in order to display the entry submitted by the user.
What seems to be wrong here? Am I using the $_POST variable in PHP the wrong way?
If you want to display the input's value BEFORE sending it to your server:
document.querySelector("form").addEventListener("submit", function()
{
var value = this.querySelector("input[name='tweet1']").value;
alert(value);
return false; //disable sending the data to the server
}, false);
<form id="myForm" method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
If you want to display the input's value AFTER sending it to your server:
<form method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
<?php echo htmlspecialchars($_POST["tweet1"]); ?>
These are different things. You can use $_POST only after you've sent some datas to the server. When you open yoursite.com/index.php in your browser, you make a HTTP GET request. In this case, $_POST will be an empty array, since it's a GET request, no data is sent to the server. When you submit the form, you make a HTTP POST request. Your PHP can access only that data you sent to the server. With Javascript, you work on the visitor's computer, not on the server. The only one way to send the data to the server without refresing the page, if you use AJAX, and make a new HTTP POST request, that'll run in the "background". But you do not need this if you just want to display the input's value, and you don't want to save it on your server. That can be done with Javascript, and without PHP.
The code you posted above would work like this:
You make a HTTP GET request to yoursite.com/index.php.
No data is sent to the server, $_POST will be empty.
var htmlString="<?php echo $_POST['tweet1']; ?>"; In this line, you try to echo an non-existing member of $_POST, you might see an error if display_errors is not disabled.
You click on the submit button.
It has an onclick attribute, postResul (a Javascript function) is called. If you open the page's shource, you'll see this:
function postResul()
{
var htmlString="";
alert(htmlString);
}
After an empty popup is shown, and you press OK, the browser send the data to your server, and you'll able to acess the input's value via $_POST.
If you press the submit button again, you'll see submited value (and not the input's actual value), because if you open the source code, you'll see this:
function postResul()
{
var htmlString="entered data";
alert(htmlString);
}
But that isn't want you want, so see the examples above depending on what you want (save the data, or just display it in the browser).
This should work:
function postResul()
{
var htmlString=document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
But you should really read more on how client-side and server-side languages work.
You cannot use $_POST['tweet1'] to get the value when you are invoking a Javascript function. Basically client side and server side are totally different.
You can obtain the result using Javascript as:
function postResul()
{
var htmlString= document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
In HTML:
<form method = "POST">
<input type = "text" name = "tweet1"/>
<br>
<input type = "submit" onclick = "postResul()" />
</form>
Note: The above function runs in client side and not in server side.
$_POST can be used to get values of the submitted form in a php page.
Cheers.
You have to make another file. Change your code to:
<form method="POST" action="another.php" >
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
In file another.php you can show the variable then:
<?php echo htmlspecialchars($_POST['tweet1'], ENT_QUOTES, 'UTF-8'); ?>
You should use the form in a different way
<form method="POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
test.php file
<?php
return json_encode([1, 2, 3]);
js
$('form').on('submit', function() {
$.post('test.php', {}).done(function(response) {
alert(response);
})
})
Something like this.
Hope it's useful.
if you are using jquery library you can do this
<form method="POST">
<input type = "text" name = "tweet1" class="tweet" />
<br>
<input type = "submit" class="submit" />
</form>
$('.submit').click(function(e){
alert($('.tweet').val());
e.preventDefault();
});
jsfiddel working example http://jsfiddle.net/mdamia/j3w4af2w/2/
Related
I have a text box in a webpage and i want when the user type something in it, display it with no refresh.
My php file that get data from user and display it:
<?php
$text = $_GET['text'];
echo $text;
?>
and the html file:
<form method="Get">
<input type="text" name="text">
</form>
How can make it type $text when the user type in input.
What is the point use PHP and AJAX in this case? If you don't store any data from user type in database, I can not see the shuffle.
You can use simple JavaScript function to read a value of input and set it as innerHTML of any element.
Look on this JavaScript:
document.querySelector('input[name="text"]').addEventListener('keyup', function(e){
const input = e.target;
document.querySelector('#result').innerHTML = input.value;
})
and this HTML structure:
<form method="Get">
<input type="text" name="text">
</form>
<div id="result"></div>
In you types in input, it's automatically supplements [id="result"] with value.
This is working demo: https://jsbin.com/hadevocoqo/edit?html,js,output
Greetings, plum!
Kindly use javascript(AJAX) for this process.
All you need to do is keep the php file in a separate file and use AJAX to connect it.
<form method="Get">
<input type="text" name="text" onKeyUp="makeAjaxCall()" id="input">
</form>
<script>
function makeAjaxCall() {
let input = document.getElementById('input').value;
if(input){
// make the ajax function call here
// Ajax response is injected into the document using innerHTML.
connectViaAJAX();
} else {
// no input is provided.
}
}
function connectViaAJAX() {
// write ajax here
}
</script>
There are other javascript libraries out there that you can check out
Angular: http://angular.io/
VueJs: https://vuejs.org/
ReactJs: https://reactjs.org/
and many more.
You can visit : https://w3schools.com for more programming tutorials
I'm trying to submit an image file using javascript onChange, the thing is I don't know the value of the submitted POST form, and how can I set a custom POST value. Here is a simple example:
HTML:
<form id="form" action="upload.php" method="post">
<input type="file" id="file" name="image">
</form>
Javascript:
document.getElementById("file").onchange = function() {
document.getElementById("form").submit();
}
So after I submit the form I can only get the value $_POST['image']. Usually when receiving POST I check for the value of the submit button which I create uniquely for each form such as, updateform, updateclient. Now I want to do the same by creating custom messages, one page will send 'uploadclientimage' the other will say 'uploadshopimage' and so on. This way the upload.php file can process the status to decide what to do next.
In upload.php I want to do like this:
if(isset($_POST['uploadclientimage']))
{//Save in client uploads folder and update client info}
else if(isset($_POST['uploadshopimage']))
{//Save in shops uploads folder and update shop info}
else header("Location: login.php");
using submit button does that easily <input type="submit" name="uploadclientimage">
How can I do something like that with onChange form submit???
Just add a hidden field in the form. For example:
<input type="hidden" name="uploadclientimage" value="">
My question maybe looks awkward. But I strongly need the answer. Assume a form submit like:
<input name="button2" type="submit" class="test" id="button2" value="submit"
onclick="checkSubmitStatus();"/>
When the checkSubmitStatus function is called, the form is not submitted yet, so the form data is not arrived in database in server side yet. How can I make them execute in vice-versa? I mean firstly, the form submits and its data is inserted to the server database and then call that javascript function.
I think you want to give to user some feedback about if data was inserted successfully or not, right?
if so, I recomend you to follow different way. Eg.:
Your markup:
<form id="frm-post" method="post">
<input name="foo" value="bar" type="text" />
<button type="button" id="btn-submit">Submit</button>
Your Code:
$("#btn-submit").click(function(){
var objData = {
type : 'post' ,
url : 'your url' ,
data : $('#frm-post').serialize(),
dataType : 'text' ,
success : function ( dataReceived ) {
alert(dataReceived)
}
}
$.ajax(objData);
});
Considering the page you'll call will return just the message you want to show to the user.
I've not tested the code, but I think it will put you in the right way.
I have a PHP page with two Buttons named as Save and Submit.One for Saving form Data and other for submiting the final data.
<button id="save" name="save" onclick="saveForm();">Save</button>
<button id="submit" name="submit" onclick="validate();">Submit</button>
here are the two JavaScript functions:
function saveForm() {
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
function validate() {
// some validation code here
// after validation the rest will work
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
In 'SubmissionCheck.php' page I have defined two separate actions for save and submit button, but I am facing the same process of submit button when I click the save button. How do I solve this? Any one help please. Thank you in advance.
<button id="save" value="save" name="method" onclick="saveForm();">Save</button>
<button id="submit" value="submit" name="method" onclick="validate();">Submit</button>
PHP
if(isset($_POST["method"])){
if($_POST["method"] == "save"){
echo "Saving File";
}elseif($_POST["method"] == "submit"){
echo "Submitting File";
}
}
When you are doing what you are trying to do I tend to keep my name's the same. So that I can test against them. I generally use names such as action, method, mode,and data which I can then test the values. Another good practice I do, is just var_dump then entire $_POST
example
var_dump($_POST);
var_dump($_GET);
var_dump($_REQUEST);
By performing these test conditions you can have more control over your code without getting overwhelmed by names. Another thing I like to do is use these for page actions, these action,mode,method help me generate the exact page the user is looking for.
example
<input type="text" value="" name="method" placeholder="Insert a method">
<input type="text" value="" name="action" placeholder="Insert a action">
<input type="text" value="" name="mode" placeholder="Insert a mode">
Then when submitted I can use these like so
$path = "";
if(isset($_POST["method"])){
path.="method=".$_POST["method"];
if(isset($_POST["action"])){
path.="&action=".$_POST["action"];
if(isset($_POST["mode"])){
path.="&mode=".$_POST["mode"];
}
}
header("Location: /path/".$path);
}
This will output three ways... if only method, if method and action, and if method,action,and mode. So generally speaking, testing against universal names sometimes is better. Hope this little walk down PHP $_POST usage helps you a little bit.
note I never sanitized any of the $_POST values, but if you are using them as a path you really should, or if you are access mySQL database use mysqli_real_escape_string and other sanitation methods.
Also is your forms default action being prevented, because since you have no values, $_POST will be empty every time. Unless it's prevented then submitted correctly.
<form onsubmit="return false">
//buttons
</form>
you can differentiate in actions like this
function saveForm() {
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
function validate() {
--some validation code here---
--after validation the rest will work--
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php?validate";
document.submission.submit();
}
then in SubmissionCheck.php file check
if(isset($_GET['validate']))
{
// perform actions for validation
}
check isset:
if (isset($_POST["save"]))
{
echo "save action";
}
if (isset($_POST["submit"]))
{
echo "submit action";
}
I have following form structure
<form action="{Basket-Addproduct}" method="post" id="items-form">
<button class="button-text button-gray-custom" type="submit" value="Submit" name="{dynamically generated name}"><span>Submit</span></button>
</form>
here "dynamically generated name" is the key field which tells which element or product to submit..
I want it to convert it into link,
I have tried following
Add This
Its getting submitted but not able to add the product...
Its expecting the name parameter also to be passed so it knows which product to add...
Stuck....:(
Any solution appreciated...
you should have <input type="submit".
There is no need to do JavaScript.
Just remove JS and then have as many <input type="submit" buttons as you want.
The GET/POST should have the key/value you look for.
E.g.
<input type="submit" name="item1" value="submit" />
when you click it, the recipient receives (sorry PHP used here):
$_GET['item1'] = submit
and other submits do not have value.
You can use jQuery to do this clean and easy.
So, here's your link:
<a id="form-submit-btn" href="#" name="{dynamically generated name}">Add This</a>
And your form:
<form action="{Basket-Addproduct}" method="post" id="items-form">
<!-- form contents -->
</form>
Now write a JavaScript which submits your form data on a button click:
$('#form-submit-btn').click(function(e) {
e.preventDefault();
var $form = $('#items-form');
$.post($form.attr('action'), $form.serialize(), function(data){
// do something with the data
});
});
Your code should work, I have created an example for you to test, here it is: http://jsfiddle.net/afzaal_ahmad_zeeshan/yFWzE/
<form id="form">
<input type="text" name="something" id="something" />
</form>
Submit
By using this you will submit the form using the id of it. And other user told you to use jQuery, which I am afraid you don't want to. In jQuery you use .preventDefault but if you want to stick to the simple JS then you will be using href="#" which will automatically prevent any anchor tag execution.
And the result of the request can be checked, which sadly is an error. But it makes sure that the request has been sent to the server.
Then you can test the methods and other type of executions by having some if else blocks as
if(condition == true) {
// if post
} else {
// if get
}
The parameter might be mis handled on the server side, because when the form is submitted you need to take out the data from the QueryString (the request is GET). So, you need to check that, or if that's not the issue then make sure you're pointing the element well. Otherwise if there is no such element, nothing will be sent.
I am not sure, which language you're using but here is the code for ASP.NET
var value = Request.QueryString["something"];
PHP version is already present above. That all depends on the parameters you send with the request. You are more likely to convert the code to a function. Such as
Submit
And the function
function submit() {
// create variable
var value = document.getElementById("something").value;\
// now submit the form and all that other bla bla, which
// you want to be process,
}
If you find this one tricky, using jQuery as
var values = $('form').serialize();
will be easy. This will create a string of the form and will send it with the request.