how to use $editFormAction in javascript? - php

I have created a form that has a subit button which will submit the for to a database, and a email button which will run a .cgi script to process the mail. Im having trouble getting the submit button to work.
here is the form buttons
<FORM name="drop_list" method="POST" >
<input name="emailForm" type="button" id="emailForm" onClick="sendFormEmail()" value="Email">
<input name="add_patient" type="button" id="add_patient" onClick="addPatient()" value="Add Patient">
</FORM>
And here is my javascript
function sendFormEmail() //email form
{
alert ("Email, this is disabled atm");
document.drop_list.action = "html_form_send.php"
document.drop_list.submit(); // Submit the page
return true;
}
function addPatient() //Post form to data base
{
alert ("Post to database");
document.drop_list.action = <?php echo $editFormAction; ?>;
document.drop_list.submit(); // Submit the page
return true;
}
The sendFormEmail() works fine, but when I try to use addPatient(). The form will not submit and something in the document.drop_list.action = ; line completely breaks the java script.
Thanks in advance for your help.
-Gregg

You haven't shown the value of $editFormAction, but I'll bet it doesn't have quotes around it. So you need to write:
document.drop_list.action = "<?php echo $editFormAction; ?>";
If you checked in the Javascript console, you should have seen an error message about an undefined variable or undefined not having a php method. And then if you looked at the JS source, you would have noticed that the script name doesn't have quotes around it, like it does in sendFormEmail.

Related

Why am I getting this PHP error?

So here's my full code
<!DOCTYPE html>
<html>
<body>
<h1>Encrypt</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter word to encrypt<input type="text" name="in">
<input type="submit">
<hr>
</form>
<h1>Decrypt</h1>
<form>
Enter word to decrypt<input type="text" name="out">
<input type="submit">
<hr>
</form>
</body>
</html>
<?php
$encrypt = $_POST['in'];
?>
And here's the error I get
Notice: Undefined index: in in /Users/idrisk/Colourity/si/index.php on line 20
Line 20 is $encrypt = $_POST['in']; and I don't see what I'm doing wrong with it. Any ideas?
As a general practice for forms in php, always check if the submit button has been clicked.
First name your submit button:
<input type="submit" name="submit">
then further in your php:
if (isset($_POST['submit'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
EDIT #1: Added to that, you seem to have 2 forms and 2 submit buttons. I suggest you keep only one form, and one submit button (remove the 2nd form element and submit button).
If you really need 2 forms, name your submit buttons differently and then you can call them separately.
<input type="submit" name="submit-in">
<!-- ... -->
<input type="submit" name="submit-out">
<?php // ...
if (isset($_POST['submit-in'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
if (isset($_POST['submit-out'])) {
// do your stuff, eg...
$dencrypt = $_POST['out'];
}
EDIT #2: If you want to echo stuff posted in your form, make sure you do the form submission checking and variable setting before the form and then echo the variable after the form (or wherever you want).
you need to first check if the form has been sent, if it hasn't then $_POST['in'] does not yet exist thus throwing the error
May be nothing but you called a php script after closing the form /form, the body /body and then then the HTML /html
replace this code $encrypt = $_POST['in']; by this $encrypt = #$_POST['in'];
this is an error on client server when you upload this file on remote server you will not saw this. use # sign on the client server when you saw this error in future.

submit button that will submit the form and send a email?

I have a form that has 2 buttons on it. 1 will send a email using a .php script,and another will submit the form to a .php database. Both of these work great by themselves, but I would like to combine them into 1 button. here is a example of my code:
<FORM name="drop_list" action="<?php echo $editFormAction; ?>"" method="POST" >
<input name="emailForm" type="button" id="emailForm" onClick="sendFormEmail()" value="Email">
<input name="add_patient" type="submit" id="add_patient" onclick=document.drop_list.action='<?php echo $editFormAction; ?>' value="Add Patient">
Here is the java script that is run for the email button:
function sendFormEmail() //email form
{
document.drop_list.action = "html_form_send.php";
document.drop_list.target = "_blank";
document.drop_list.submit(); // Submit the page
return true;
}
I am still very new to php script and javascript, so any help is appreciated.
Just use mail(to,subject,message,headers,parameters) in the send email function.
The function arguments have to be the strings where you store the text of the form fields, so you can fill the mail() function with the email and other data inserted in the user interface.
check this to get to know how to actually call a function declared in the same file Calling a particular PHP function on form submit

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>

how to call a php function on button click

These are two files
Calling.php
<html>
<body>
<form action="Called.php" method="get">
<input type="button" name="B1" value="B1">
<input type="button" name="B2" value="B2">
<input type="Submit" name="Submit1"/>
<!-- Google
yahoo
-->
</form>
</body>
</html>
And Called.php
<?php
if(isset($_GET("Submit1")))
{
echo("<script>location.href = 'http://stackoverflow.com';</script>");
}
if(isset($_GET["B1"]))
{
echo("<script>location.href = 'http://google.com/';</script>");
exit();
}
if(isset($_GET["B2"]))
- List item
{
echo "<meta http-equiv='refresh' content='0;url=http://www.yahoo.com'>";
exit();
}
?>
When i click the buttons "B1" and "B2", page will blink but now where redirect and third one "Submit" button will redirect to new page and there i am getting the out put as "Called.php".
Please spend few seconds for this php beginner.
You can't directly because the button click is a client side activity and PHP is server side. If you make all the inputs submit then the one the user clicked will be submitted as part of the $_GET array but that only works if the user clicks one of them and doesn't submit the form by, say, hitting Enter in a text input.
You could attach AJAX events to the button and have them trigger off a PHP script to run the function you want to run, but that has its own set of issues.
EDIT: I should note that your method of redirecting is rather inelegant to say the least. You can just use header() to do the redirection, it would be much cleaner than all this messing around with echoing out javascript.
You need to use Ajax to do this. If you are using jQuery ajax the code will look something like this
$(function(){
$('input[type="button"]').click(function(){
var name = $(this).attr('value');
$.ajax({
type :'GET',
url : 'Calling.php',
data :{name:name}
success : function(data) {
//do smthng
}
})
})
})
//Code is not tested. Need to verify.

Javascript Validation

I was just trying to submit a simple form to the same page but when it is submitted it will call PHP function on the same page. However I was trying to do some JavaScript validation before submission. So I want to know what the difference between using onSubmit call js function in the form tag and onClick call js function with button.... This is what I am currently trying to do.
<?php
function tobecalled()
{
echo "This was run";
}
?>
<html>
<head><title>Testing</title>
<script type="text/javascript">
function testResults (form)
{
var TestVar = form.inputboxname.value;
if(TestVar == '')
return false;
else
return true;
}
</script>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST" onSubmit="return testResults(this);">
<input type="text" name="inputboxname" />
<input type="submit" value="Save" name="submit" />
<?php
if(isset($_POST['submit']))
tobecalled();
?>
</form>
</body
</html>
It works..
But if I make (Submit Via JS)
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
...
<input type="submit" value="Save" name="submit" onClick="return testResults(this);"/>
...
Its still calls the PHP function tobecalled()--Why? I am expecting it not call. How do it work?
The reason that it is allowing it to go through is because you are passing this in the onclick event. In this instance this is referring to the submit button not the form as required by the function.
Thus form.inputboxname.value returns undefined which is not '' (empty string) and therefore the testResults function returns true. So the submit is then activated.
The difference is this. this points to a different object in onClick than in onSubmit. Your function expects a form to be passed, but when you use onClick, you give it the submit button. That's why the second method doesn't work as expected.
Because regardless of whether you add your javascript to the onsubmit of the form or the onclick of the submit button the form will still be submitted by the submit button. That means that a request is being sent back to the server and $_POST['submit'] will be set. Since that variable is set you find your function being called.

Categories