How to pass form input value to php function - php

I want to write a php page in which there is a html form. I want to send all input (number for example) of my form to a php function (instead of a javascript function; I make this to hide my javascript function code).
How can I send input value to php function?
Is it possible to call the php function through onclick="function(param1, param2)"?
I know that javascript is a client-side language while php is server-side.
If it is possible, how can I write the return of the function in an input field?
I want to remain in my page.
Is it correct - action="#"?
My code is:
<form action="#" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" value="send"></input>
</form>
Help me in the implementation of the simple php function and in the passage of values from input to function!
Thanks!

Make your action empty. You don't need to set the onclick attribute, that's only javascript. When you click your submit button, it will reload your page with input from the form. So write your PHP code at the top of the form.
<?php
if( isset($_GET['submit']) )
{
//be sure to validate and clean your variables
$val1 = htmlentities($_GET['val1']);
$val2 = htmlentities($_GET['val2']);
//then you can use them in a PHP function.
$result = myFunction($val1, $val2);
}
?>
<?php if( isset($result) ) echo $result; //print the result above the form ?>
<form action="" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" name="submit" value="send"></input>
</form>

You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc

This is pretty basic, just put in the php file you want to use for processing in the element.
For example
<form action="process.php" method="post">
Then in process.php you would get the form values using $_POST['name of the variable]

No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.

You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].

you must have read about function call . here i give you example of it.
<?php
funtion pr($n)
{
echo $n;
}
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>

Related

Add Multiple row of data in databse at once

i have few field of data such as product , amount and barcode.The system just show 1 row of data insert form that contain the 3 field.when i completed insert the first row, then second row of textbox will auto generate, i can do it by microsoft access, can i do so for php ?
<?php $i=0; ?>
<form method="post" action="">
<input type="text" name="<?php echo $i; ?>" />
</form>
<?php
if(isset($_POST[$i])){
$i++;
?>
<form method="post" action="">
<input type="text" name="<?php echo $i; ?>" />
</form>
<?php }?>
it work for the first and second textbox, but how can i continue to create more textbox accordingly?
say your file name is 1.php and you will submit the form to 1a.php
1.php
<html>
<head>
<script>
a=0;
function generate()
{
if(document.getElementById(a).value!="")
{
var new_input=document.getElementById(a).cloneNode(true);
//document.getElementById(a).type="hidden";//uncomment this statement to hide the previous input box.
new_input.id=++a;
new_input.title='product_no:'+(a+1);
new_input.value="";
document.getElementById('input_section').appendChild(new_input);
}
else
{
alert("Give some value first.");
document.getElementById(a).focus();
}
}
</script>
</head>
<body>
<form method="post" action="1a.php">
<span id="input_section">
<input type="text" onFocus="this.name='prod[]'; this.id=a; this.title='product_no:'+(a+1);"/>
</span>
<input type="button" value="Insert&Generate" onClick="try{generate()} catch(e){alert(e)}">
<input type="submit" value="INSERT ALL">
</form>
</body>
</html>
1a.php
<html>
<?php
if(count($_POST)==0)
{
?>
<script>
alert('No record to insert.')
location.href="1.php";
</script>
<?php
}
$con=mysqli_connect(...);// connect to database
foreach($_POST['prod'] as $prod_info)
{
$prod_info_arr=explode(",",$prod_info);
$sql="insert into tab1(product, amount, barcode) values('".$prod_info_arr[0]."', ".$prod_info_arr[1].", '".$prod_info_arr[2]."')";
mysqli_query($sql);
}
?>
</html>
This is what you wanted. Check it.
edit: just added comment on the statement document.getElementById(a).type="hidden"; to make the filled textbox not disappear.
If you want to have dynamic input fields, so that second and third input boxes are displayed only when the first input box is filled, use an AJAX code.
This must be what you want. Since you have not mentioned clearly under what condition the second input field should be displayed, i assumed if 'try' is inserted in the first input field, second input field is shown.
<?php
echo "<script>
function showUser(str)
{
if (str=='')
{
document.getElementById('txtHint').innerHTML='';
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('txtHint').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','get.php?q='+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form method='post' action=''>
First input<input type='text' name='name' onclick='showUser(this.value)' /></br>
<div id='txtHint'></div>
</form>
</body>
</html>";
?>
And in get.php file the following code;
<?php
$q = $_GET['q'];
if($q == 'try'){
echo "Second input<input type='text' />";
}
?>
Hope this will help. And change the get.php code according to the condition you want the second input field to be shown.
This code works. After entering try in the first input field again click inside the text field. And then second input field will be shown.

AJAX XMLHttpRequest not working

I'm trying to work with ajax. I have two pages: request.html and reply.php.
request.html:
<html>
<script language="javascript">
var xht = new XMLHttpRequest();
function testAJAX()
{
xht.open("get","http://localhost:9999//a.php", true);
xht.send();
xht.onreadystatechange=function() {
if (xht.readyState==4) {
alert("Text: "+xht.responseText);
}
}
}
</script>
<form id="form1" name="form1" method="post" action="">
btn
<input name="btn" type="submit" id="btn" onClick="testAJAX();" value="Submit" />
</form>
</html>
reply.php:
<?php
echo 'hi';
?>
The problem is that I don't get a response via xht.responseText and with xht.responseXML I get null and with xht.status I get 0.
I asked the link http://localhost:9999//a.php via browser and got hi correctly.
P.S: I tried this on Chrome 29.0.1547.18 and Maxthon v4.1.1
any ideas..
You don't need to mention "http://localhost".
The main mistake is you have given the input type as Submit If it is submit the form will be submitted first the click event will not trigger. Change the input type to button.
If you want to do form submission do it in java script
The corrected code is below.
<form id="form1" name="form1" method="post" action="">
btn
<input name="btn" type="button" id="btn" onClick="testAJAX();" value="Submit" />
// change type to button
</form>
var xht = new XMLHttpRequest();
function testAJAX()
{
xht.open("get","a.php", true); /// Change to a.php
xht.send();
xht.onreadystatechange=function() {
if (xht.readyState==4) {
alert("Text: "+xht.responseText);
}
}
}
Adding to SarathPrakash's answer, I would like to point out that there is nothing wrong with specifying localhost. It will still work as long as the PHP file's address is valid.
You can also have the submit button. But you'll have to modify the form opening tag as follows:-
<form id="form1" name="form1" method="POST" action="" onsubmit="return false">
This is will stop the default behaviour of the form being submitted. Although in my opinion, it is best to avoid it altogether, and just stick with assigning the correct event handler to the onclick attribute.
Also, it is good practice to follow the correct syntax for HTML documents.
<html>
<head>
<title> Your title here </title>
<script type="text/javascript"> Your script here </script>
</head>
<body>
Your main document text here. Forms, tables etc.
</body>
</html>
For a simple tutorial, you could try this.

Send image to server Ajax

How can i send image from the client side to server?
i have a simple form like :
<form>
<input type="file" id="myfile" name="myfile" />
<input type="button" value="Submit" onclick="SendImageToServer();" />
<iframe id="uploadframe" name="uploadframe" src="upload.php" width="8" height="8" scrolling="no" frameborder="0"></iframe>
</form>
And in the method i am using is :
function sendImage(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//I want to get the response as simple <img scr="myimage"/>
}
Can anyone help me how can i do this using Ajax-php.(NO JQUERY)?
Well, for one thing you cannot send files with AJAX. But if you are submitting to an iframe, then the form needs to have enctype="multipart/form-data" defined, otherwise it does not submit files.
You should not use AJAX term as you won't be creating one. To upload the file set an action and target on form and everything else should be automatic, that is, in-page.
<form action="upload.php" target="uploadframe" enctype="multipart/form-data">
... everything else here
<input type="submit" value="Go!"/>
</form>
Hope this helps...

Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).
Here is what I reach to:
In the test.php file:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test() function ] is in the same file also:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
User (well, the browser) requests test.php from your server
On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
The browser displays the form, the user can interact with it.
The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
Use SAJAX or switch to JavaScript
Sajax is an open source tool to make
programming websites using the Ajax
framework — also known as
XMLHTTPRequest or remote scripting —
as easy as possible. Sajax makes it
easy to call PHP, Perl or Python
functions from your webpages via
JavaScript without performing a
browser refresh.
That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.
...
success: function(html) {
alert(html);
}
...
This is the better way that I use to create submit without loading in a form.
You can use some CSS to stylise the iframe the way you want.
A php result will be loaded into the iframe.
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>

Validating input text in php when moving pages

I do know how to validate a basic input(text) when submitting a form. However, I am lost as to how I am going to validate an input(text) when leaving a web page. Even with JS I couldn't get it to stay on the same page due to the "form action" attribute.
HTML Code for the input and submit
<form name="form1" action="second.php" **onsubmit="return error()"** method="post">
<input style="" name="hall" type="text"><br>
<input name="Move" style="height: 23px" type="submit" value="Move">
</form>
PHP CODE for validating
<?php
if (isset($_POST['Move'])) {
if(($_POST['hall']) != "Hallway")
{
echo "Not among available rooms";
}
?>
Also this is the JS code
<script type="text/javascript">
function error()
{
var x=document.forms["form1"]["hall"].value
if (x==null || x=="" || x!="next")
{
alert("Wrong entry. Try again!!!");
return false;
}
}
</script>
The following code is working on my server, provided the second.php page exists. (BTW I added a ; after value, but it seems to work without it).
Did you put the js script after the form? Maybe it could impact.
<html>
<script type="text/javascript">
function error()
{
var x=document.forms["form1"]["hall"].value;
if (x==null || x=="" || x!="next")
{
alert("Wrong entry. Try again!!!");
return false;
}
}
</script>
<body>
<form name="form1" action="second.php" onsubmit="return error()" method="post">
<input style="" name="hall" type="text"><br>
<input name="Move" style="height: 23px" type="submit" value="Move">
</form>
</body>
</html>
Other things I can think of:
-Do you have any JS errors on the page that would prevent this script from running? It worked on my server, as well.
-Do you have another HTML element with an identical name?
-I am assuming that the **'s were for emphasizing that area in your code. If not, of course, they would need to be removed.
The only thing that could prevent your "return false" from working is if you have some kind of JavaScript error that kills the script from running.
If you have additional code on your page, please post it and we'll take a look!

Categories