PHP Working with Buttons and Functions - php

I'm having difficulties on the executing a php function with a button
I've been browsing through the net (and ofcourse here at stackoverflow) for a solution to this problem. However, still no luck.
This problem might have been asked many times in this site, but none of them seems to work to me (or am i just that poorly literate with programming).
What i am trying to achieve is to set a session variable once the button is clicked, and print it in the second page as it redirect.
here's what my first php page looks like:
<?php
session_start();
if(isset($_POST['submit']))
{
$_SESSION['testing']= "hello world";
}
?>
<form method="post" action="update.php">
<input type="submit" id="submit" name="sumbit" value="Submit" >
</form>
and here's the update.php:
<?php
session_start();
echo $_SESSION['testing'];
?>
It may look theres nothing wrong with it, but the script does not execute anything inside the "if(isset(..." statement.
I am using WAMP as a server and my PHP version is 5.3.13
PS: I am aware that PHP is a server-side programming, and what i'm trying to do is something similar to client-side scripting.
The problem is, i do not know how to work with javascripting and what they call it "Ajax" scripting.
Is there any way this could be fix? Is it possible to do this with PHP alone without using javascript or ajax?

Hi simply empty action like <form method="post" action=""> on form tag and redirect after session setting.like header("location:update.php");.Hope solve your problem.Your first page code will be
<?php
session_start();
if(!empty($_POST))
{
$_SESSION['testing']= "hello world";
header("location:update.php");
}
?>
<form method="post" action="">
<input type="submit" id="submit" name="sumbit" value="Submit">
</form>
While on update page
<?php
session_start();
echo $_SESSION['testing'];
?>

$.ajax({
type: "get",
url: "update.php",
success: function(){
alert("success");
// do something
}
});
Above is the example of jquery ajax.

Try this one:
First Page:
<form method="post" action="update.php">
<input type="submit" id="submit" name="sumbit" value="Submit" >
</form>
Update.php:
<?php
session_start();
$_SESSION['testing'] = 'Hello World';
echo $_SESSION['testing'];
?>
Since you want to print the session in the second page, you should put a value of session in update.php not in your first page..

Related

I'm not understanding something at PHP handling

i'm new to programming so sorry if this question doesn't makes much sense.I learned PHP handling and i succeed at it. But i am not able to do something.
First take a look at the code...
<body>
<form action="get.php" method="get">
Username: <input type="text" name="name"><br>
<input type="submit"value="Connect" class="btn">
</form>
<>
</body>
</html>
And the get.php file:
<html>
<body>
Connected to: <?php echo $_GET["name"];?><br>
</body>
</html>
The output (connected to $name) will be on a blank page, without the other html and css elements. Is there a way to print the output right below the connect button ?
It's not the best approach in modern web programming, but since you're a beginner: you can combine the PHP connection logic with the HTML into the same file.
<!DOCTYPE html>
<html>
<body>
<form method="get">
Username: <input type="text" name="name" />
<input type="submit" value="Connect" class="btn" />
</form>
<?php
if (isset($_GET["name"])) {
echo "Connected to: " . $_GET["name"];
}
?>
</body>
</html>
Note that I omitted the action="...", in order to target to the current page.
By the way, a good approach will be to separate the business logic from the visual components (I recommend you to read about the MVC design pattern).
In addition, if you want to obviate refreshing the whole page, you can use JavaScript and AJAX (I recommend you to read about jQuery), but it's a bit more advanced.
The web is "stateless" and what it sounds like you want to do is to submit the form without refreshing the page. This can be done client side in JavaScript. The following for instance uses jQuery to make the JS you have to write smaller, but can (arguably should) done in straight JS.
<html>
<body>
<form action="get.php" method="get" id="the-form">
<label for="name">Username: <input type="text" id="name" name="name">
<br>
<input type="submit"value="Connect" class="btn">
</form>
<div id="response">
<?php
if(isset($_GET['name']))
{
include('get.php');
}
?>
</div>
</body>
</html>
<script src="path/to/jquery.min.js"></script>
<script>
$(#the-form).submit(function(event)
{
event.preventDefault();
$.ajax({
url: 'get.php',
type: 'get',
data: $("#the-form").serialize(),
success: function(data)
{
$('#response').append(data);
}
});
});
</script>
If you're not worried about the page refresh, then Reflection's answer is what you are looking for. That said, you could do both using the JS/ajax free version as a fall back and the AJAX version as a progressive enhancement.

Cannot echo the values from a simple php form

First time i try to create a simple form using the POST method.Problem is when i click the button nothing gets echoed.
here is my insert.php file :
<?php
if(isset($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
?>
<form action="insert.php" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
EDIT: I tried the GET method and it works...Any ideas why that happened? Server configurations?
NEW EDIT: So it turns out i switched method to GET and it worked.Then i switched back to POST (like the code i posted on top) and it works...I have no clue why this happened.Any suggests?
The code you have posted is perfectly valid and should work.
I'm going to guess that you do not have PHP enabled, or it is not working.
<?php ... ?> looks to the browser like a long, malformed HTML tag, and therefore ignores it, making the effect invisible.
Try right-clicking the page and selecting View Source. If you see your PHP there, then the server is indeed not processing it.
The most likely reason for this is probably the same problem I had with my very first bit of PHP code: you're trying to "run" it directly in your browser. This won't work. You need to upload it to a server (or install a server on your computer and call it from there)
Use !empty($_POST['newitem'] instead:
if(!empty($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
empty()
Try the following:
if($_POST) {
if(!empty($_POST['newitem'])) {
$itemnew = $_POSΤ['newitem'];
echo $itemnew;
// or leave it as is: echo $itemnew = $_POSΤ['newitem'];
}
}
?>
<form action="insert.php" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
The if($_POST) will make sure the code is only executed on a post. The empty() function will also check if it isset() but also checks if it is empty or not.
Try this :
<?php
if(isset($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
$_SERVER['PHP_SELF']; is pre-defined variable in php.It allows the user to stay on same page after submitting the form.

Creating a iframe search page for my site

It is very difficult for me to put in words my query. But I will try.
I have a site xyz.com which has search facility for listed products. The search page url is generated like this :www.wyz.com/search/search_term
I want to create a iframe page in a third party site with a search facility which can directly communicated with my site xyz.com.
I have tried to create a search box with a submit button. I want to append the search query in as a variable to my form action url string.
So the search string should look like this :www.wyz.com/search/my_string_variable
The code I have written is:
<?php
$url='http://www.xyz.com/search/';
?>
<?php
if (isset($_POST['submit']))
{
$r1=$_POST['num1'];
}
?>
<?php
$result=$url.$r1
?>
<html><body>
<form action="<?php echo $result; ?>" method="post">
Num1:<input name="num1"><br>
<input type="submit" name="submit">
</form>
</body></html>
==================================================================
But output what I get, is only "http://www.xyz.com/search/". It removes my variable from the url. I am not able to find what is the reason? I have also tried to print result via to check the actual output and it shows that it has added the value at the end of url. But when I want to achieve the same thing via form action it does not work. please help?
<?php
$url='http://www.xyz.com/search/';
?>
<?php
if (isset($_POST['submit']))
{
$r1=$_POST['num1'];
$result=$url.$r1;
header("location:$result");
}
?>
<html><body>
<form action="" method="post">
Num1:<input name="num1"><br>
<input type="submit" name="submit">
</form>
</body></html>
Please try the above code. I have made some modifications. The main reason your code is not working is whenever you press the submit button it is going to the the url "http://www.xyz.com/search/" directly .The if condition is never executed. In the above mentioned code it will work properly
action="" - you are submitting to the wrong url. Here is alternate version -
<?php $url='http://www.xyz.com/search/';
if (isset($_POST['submit'])) {
$r1=$_POST['num1']; header("Location: ".$r1); // 302 redirection
}
?>
<html><body> <form target="_SELF" method="post"> Num1:<input name="num1" type="text" /><br /> <input type="submit" name="submit" /> </form> </body></html>

Calling a particular PHP function on form submit

I was trying to call a particular php function in submit of a form both the form and php scripts are in same page. My code is below.(it is not working and so I need help)
<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>
</body>
</html>
In the following line
<form method="post" action="display()">
the action should be the name of your script and you should call the function, Something like this
<form method="post" action="yourFileName.php">
<input type="text" name="studentname">
<input type="submit" value="click" name="submit"> <!-- assign a name for the button -->
</form>
<?php
function display()
{
echo "hello ".$_POST["studentname"];
}
if(isset($_POST['submit']))
{
display();
}
?>
you don't need this code
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>
Instead, you can check whether the form is submitted by checking the post variables using isset.
here goes the code
if(isset($_POST)){
echo "hello ".$_POST['studentname'];
}
click here for the php manual for isset
Assuming that your script is named x.php, try this
<?php
function display($s) {
echo $s;
}
?>
<html>
<body>
<form method="post" action="x.php">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
display();
}
?>
</body>
</html>
PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.
To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy
If you want to call a function on clicking of submit button then you have
to use ajax or jquery,if you want to call your php function after submission of form
you can do that as :
<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
if($_SERVER['REQUEST_METHOD']=='POST')
{
display();
}
?>
</body>
</html>
Write this code
<?php
if(isset($_POST['submit'])){
echo 'Hello World';
}
?>
<html>
<body>
<form method="post">
<input type="text" name="studentname">
<input type="submit" name="submit" value="click">
</form>
</body>
</html>
An alternative, and perhaps a not so good procedural coding one, is to send the "function name" to a script that then executes the function. For instance, with a login form, there is typically the login, forgotusername, forgotpassword, signin activities that are presented on the form as buttons or anchors. All of these can be directed to/as, say,
weblogin.php?function=login
weblogin.php?function=forgotusername
weblogin.php?function=forgotpassword
weblogin.php?function=signin
And then a switch statement on the receiving page does any prep work and then dispatches or runs the (next) specified function.

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>

Categories