Normally, when I'm handling forms, in the "action" parameter, I usually have to reference a full PHP script, like this:
<form method="post" action="foo.php"></form>
Is there a way to tell the form to use a function or method rather than having to mention a whole script?
Not that I know of, but I'm pretty sure you could do something like this...
action="foo.php?fromForm=yes"
Then in your php code, you could have this...
if($_GET['fromForm'] == "yes") {
//put your function here, or call it here
}
else {
//rest of code goes here
}
imagining that your form looked something like:
<form name="form1" method="post" action="">
<p>
<label></label>
<input type="text" name="textfield" id="textfield" />
</p>
<p>
<label></label>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
then you could just put at the top of the php:
if (isset($_POST['textfield'])) {
foo();
}
replacing foo(); with the name of the function you want to execute.
This simply checks if there was any form data posted to the page with name="textfield".
No. What you're specifying is not a script, it's a URL. HTML/the browser doesn't know about server-side functions or methods, only about URLs.
You can use the onsubmit attribute to call a javascript method instead:
<form method="post" onsubmit="doSomething()"></form>
You can also use this to validate your form before passing it to a script such as the following:
<form method="post" action="foo.php" onsubmit="canSubmit()"></form>
NOTE: I'm assuming you're asking if you can access a method or function in the PHP code on the server-side, not call a JavaScript function on the client-side!
The client side cannot arbitrarily invoke methods on the server side. The URL or path to the resource, is what is used to identify a resource on the server.
If you want to perform different functionality in the same script, you could use if/else blocking and use query parameters to differentiate your URLs.
HTML:
<form method="post" action="foo.php?method=saveData"></form>
PHP:
<? /* foo.php */
if($_REQUEST['method'] == "saveData") {
// do stuff
} else if($_REQUEST['method'] == "doSomethingElse") {
// do other stuff
}
?>
This is at it's core a very basic example. For more complex needs, many frameworks can perform this level of branching, out of the box, and with much more sophistication.
If your PHP script is written as follows:
<?php
switch ($_GET ['f']) {
case 'do_one':
// do something
break;
case 'do_two':
// or use a callback
do_two_callback ();
break;
default:
// ...
}
?>
... you can always do this
<form method="post" action="foo.php?f=do_one"></form>
Related
I have a php website thats more or less like this. PHP noob here.
Index.php
<?
include('conexion.php');
include('funciones.php');
?>
<head>
</head>
<body>
<?php
if (!empty($_GET["palabra"])) {
function1($conexion);
} elseif (!empty($_GET["letra"])) {
include('letra.php');
} elseif (!empty($_POST["buscar"])) {
include('search.php');
} else {
function3($conexion);
}
?>
</body>
All functions fuctions and database connections are defined in the included files.
Website uses only a single html file, so all the content is included or called by the functions. Is there a good way for the website to identify which "section" or content is the user browsing?
So, for example I want a function to run only when the user is using the search page, should I continue to use the REQUEST to identify what the user is doing? Should I insert a variable like $section and then if($section=search){dosomething()} or maybe using the URL? should I use another approach?
You want something like this?
PHP Page
<?php
switch ($_GET["page"]) {
case 'login':
# code blocks
break;
case 'student_notes':
# code blocks
break;
default:
# code blocks
break;
}
?>
HTML Page
<form id="form1" name="form1" method="post" action="?page=login">
<p>
<label for="studentCount">Kişi Sayısı</label>
<input type="text" name="studentCount" id="studentCount" />
</p>
<p>
<input type="submit" name="button" id="button" value="Send" />
</p>
</form>
<form id="form1" name="form1" method="post" action="?page=student_notes">
<p>
<label for="studentCount">Kişi Sayısı</label>
<input type="text" name="studentCount" id="studentCount" />
</p>
<p>
<input type="submit" name="button" id="button" value="Send" />
</p>
</form>
I believe you are a little bit confuse about what PHP is and what can do.
PHP will execute in the server, meanwhile HTML execute in the client. Who define how to serve and what are you using the language.
For example:
The user click on an item in a menu, each link in the menu would send a URL to the server in a way like this:
<a href="index.php?page=palabra" >PALABRA</a>
<a href="index.php?page=letra" >LETRA<a>
<a href="index.php?page=buscar" >BUSCAR</a>
All those links will open the same page: INDEX.PHP
Is up to yo to define what to do with the $_GET var sent in the URL.
So, in your index.php you can defined:
<?php
switch ($_GET["page"]) {
case 'palabra':
# code blocks - DO SOMETHING
break;
case 'letra':
# code blocks - SHOW SOMETHING
break;
case 'buscar':
# code blocks - SEARCH SOMETHING
break;
}
?>
In that way who control what to show, and when are you.
Any way, PHP have some globals that will point the name of the script or the page being serve:
Check out https://www.php.net/manual/es/reserved.variables.server.php
I will recomend you research a little bit about php and better try to use a framework like cakePHP, Laravel or Simfony for a start. There are many more.
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.
I have a form on on html outside of php...
<form method="post" action="">
<input type="text" name="user"/></br>
<input type="submit" value="submit" name="login"/>
</form>
then call submit button from php and do this
if(isset($_POST["login"]))
{
print <<<this
<form method="post" action="">
<input type="submit" name="apply"/>
</form>
this;
if(isset($_POST["apply"]))
{ print "it works";}
}
Alright, so the problem is that, "it works" won't print from the second form thats inside the php. it just takes me back to where i came from. Perhaps it's a dumb question, please help though! thanks
The problem is that by the time you're checking if(isset($_POST["apply"])) the login condition becomes invalid because everything is inside the if(isset($_POST["login"])).
Try taking the if(isset($_POST["apply"])) outside the login IF.
Your "apply" code exists only INSIDE the login test code. When you submit that second form, there will be NO login form field, because you didn't include an input/textarea of that name in the second form. So the second form submits, there's no login, and the entire inner code never gets executed. You probably want:
if(isset($_POST["login"]))
{
print <<<this
<form method="post" action="" name="apply">
<input type="hidden" name="login" value="foo" /> <!-- add this line -->
etc...
I'm not sure to understand what you wanna do with this code but you obviously missed some details :
_You did not set the "action" field in your form tag, so I don't understant how you would like the PHP file to get called ?
_Your code if(isset($_POST['login'])) has no sense, you are testing the existence of a value sent by a validation button, you'd rather whrite isset($_POST['user'])
Hoping to have helped you
Your variables are declared in 2 forms, so there will be 2 calls (completely independant) to your php.
So you could have a second submit button inside your second form:
if(isset($_POST["login"]))
{
print <<<this
<form method="post" action="">
<input type="submit" name="apply" value="Second"/>
</form>
this;
}
if(isset($_POST["apply"]))
{ print "it works";}
I have a project that requires a search form that searches two separate eBay stores depending on what the user is looking for.
I want to have one input field with two submit buttons. I'm having problems getting the form to specify which site to call from either of the buttons. I've had a good look around and tried a few things but thought someone might be able to straighten out my syntax etc.
I have the form.
<form target="_blank" action="rp.php" method="get">
<input type="text">
<button name="replacement" type="submit">Search Replacement Parts</button>
<button name="performance" type="submit">Search Performance Parts</button>
</form>
..and I have the PHP.
<?php
if( isset($_GET['replacement']) ) {
header("Location: http://www.example.com");
exit;
} else if {
( isset($_GET['performance']) ) {
header("Location: http://www.example.com");
exit;
}
?>
I think I'm on the right track, just need a bit-o-help. I don't know whether or not to use POST or GET, GET seemed to make more sense to me for this.
You can use the following code for this:
<form target="_blank" name="myform" method="POST">
<input type="text" name="search">
<button onclick="submit1('http://example1.com/')" >Search Replacement Parts</button>
<button onclick="submit1('http://example2.com/')" >Search Performance Parts</button>
</form>
<script>
function submit1(url)
{
document.myform.action=url;
document.myform.submit();
}
</script>
Your PHP is a bit off for the elseif, otherwise it should "work"
<?php
if ( isset($_GET['replacement']) ) {
header("Location: http://www.example.com");
exit;
} elseif ( isset($_GET['performance']) ) {
header("Location: http://www.example.com");
exit;
}
?>
You can use either a GET or a POST to do this, however a GET will result in the query values being visible in the querystring and are limited in size in some older browsers. POST is probably prefered, in which case you would replace $_GET with $_POST in the code above, and change method="get" to method="post" in your form.
I would use same name for both buttons, with different value for each one and then in php code just check which value is submitted.
I want to consolidate my PHP files into a common class file, but I am not sure how to call the function instead of the .php page. How can I call sendEmail() in the form section of my HTML page?
HMTL
<form action="form_class.php" id="frmAirport" method="post">
Full Name: <span style="white-space: pre;">
</span><input name="name" type="text" /><br /><br />
Email Address: <input name="email" type="text" /><br /><br />
Subject: <span style="white-space: pre;">
</span><input name="subject" type="text" /><br /><br />
<textarea id="txtComments" cols="30" rows="10">Comments</textarea><br />
<input type="submit" value="Send" />
</form>
<?php
function addPerson() {
//do stuff here
}
function sendEmail() {
//do some stuff here
}
?>
You can't call PHP functions directly. However, if the php file is formatted how you displayed here with only two functions you could pass a flag in as a POST field and have a logic block determine which function call based on that flag. It's not ideal but it would work for your purposes. However, this would force the page to refresh and you would probably have to load a different page after the function returns so you may want to simply implement this as an ajax call to avoid the page refresh.
Edit based on your comment (Using jQuery Ajax):
I am using the .ajax() jQuery function. My intentions create one php file that contains multiple functions for different html forms. – tmhenson
Well in this case, you can have your file contain the logic block to "route" the request to the right function and finally return the result.
I'll try to provide an option for what you want to do based on some simple jQuery. Say you have something like this:
Java Script:
$("#button1").click(function(e){
e.preventDefault(); // prevents submit event if button is a submit
ajax_route('ap');
});
$("#button2").click(function(e){
e.preventDefault(); // prevents submit event if button is a submit
ajax_route('se');
});
function ajax_route(action_requested){
$.post("ajax_handler.php", {action : action_requested}, function(data){
if (data.length>0){
alert("Hoorah! Completed the action requested: "+action_requested);
}
})
}
PHP (inside ajax_handler.php)
<?php
// make sure u have an action to take
if(isset($_POST['action'])
switch($_POST['action']){
case 'ap': addPerson(); break;
case 'se': sendEmail(); break;
default: break;
}
}
function addPerson() {
//do stuff here
}
function sendEmail() {
//do some stuff here
}
?>
You CAN'T. PHP runs on the server only. You can use a javascript AJAX call to invoke a php script on the server, or use a regular form submission, but directly invoking a particular PHP function from client-side html? not possible.
I am not sure if I uderstand right, but to call function/method you can use hidden input:
<!-- form -->
<input type="hidden" name="action" value="sendEmail" />
// handle file
<?php
$actionObject = new Actions();
if (method_exists($actionObject, $_POST['action'])) {
$actionObject->{$_POST['action']};
}
?>
AddPerson and sendEmail doesn't sounds they should be method of one class. Try to use classes only with method witch are related. To call method, you can define it as static, or you must make instance of class and then call method.