Following on from a previous question, (previous question here), the problem I'm having seems to involve trying to pass/post a value through a form when the form action is '#'. I've tried session data but it always returns the last item from the database. Everthing else returns nothing.
Any help/ideas/advice greatly received, S. (Code below)
This is the code that displays the list of items, each containing an 'email' link/button to one instance of a popup window/form that is located at the bottom of the page.
<?php
$query = mysql_query("select * from istable where categoryID = '1'");
while ($result = mysql_fetch_array($query)) {
echo '<h4>'.$result['title'].'</h4>
<p>'.substr($result['descrip'],0,408).'... <strong>Read more</strong></p>
<form action="#" method="post" rel="#sheet" class="see">
<input type="hidden" name="propTitle" value="'.$propResult['title'].'">
<input type="submit" name="submit" value="Email">
</form>
';
}
?>
This is the code for the popup window/form at the bottom of the same page that is called through jquery.
<div id="sheet" class="rounded">
<!--{{{ pane1 -->
<div class="pane" id="pane1">
<h4>Email Details to a Friend</h4>
<p>You have selected to forward the details of <?php echo $_POST['propTitle']; ?> to a friend.</p>
<p>Please fill out the following form</p>
<form class="rounded" id="email-form" method="post" action="<?php echo $pageLink; ?>">
<!-- form goes in here -->
</form>
</div>
<!--}}}-->
</div>
<script type="text/javascript">
$(".see").overlay({mask: '#999', fixed: false}).bind("onBeforeClose", function(e) {
$(".error").hide();
});
</script>
Why are you using PHP for this? If the popup is called through the same page, use JavaScript to get the DOM element value and if you need to process data use AJAX.
Related
I want to make a website that has a text box and if an user enters "hello" and clicks submit I want to show example.com/test.php?link=hello
How can I do that? The php is already written I just need to make something with html or php to be able to show example.com/test.php?link=whatUserEnters
Thanks!
The form should have the method "get" defined. Then on the test.php page you just
<form method="get" action="test.php">
...
<input type="text" name="link"/>
</form>
and on the test.php
<? echo $_GET['link']; ?>
or
<?= $_GET['link']?>
Edit with the POST solution:
<form method="post" action="test.php">
...
<input type="text" name="link"/>
</form>
and on the test.php
<? echo $_POST['link']; ?>
<!DOCTYPE html>
<html>
<body>
<!--just create a text box, give an id to it.-->
<input type="text" id="text_to_display" />
<input type="button" value="Submit" onClick="concat();" />
<!--Create a label or div assign a separate id to it too.-->
<p id="concatenated_text"></p>
<script>
//Create a function in javascript.
function concat() {
//Get the value in function using that id.
var text = document.getElementById("text_to_display").value;
//Concatenate the value with the string and put it in div using id.
var final_text = "example.com/test.php?link="+text;
// you can use location.href to use it for link purpose
location.href = final_text;
}
</script>
</body>
</html>
I am having trouble understanding handling variables that are passed through pages when a form submit button is clicked. Basically i have a text area where a user writes an sql query. Then clicks submit. Then on the same page (x.php) , i have to display the results in a table. I figured, when the user clicks the button, i call a function that connects to the database, then runs the query, and outputs the result in a table. The code i have below is a mock, and isnt quite working.But above is essentially what i am trying to do.
In my code, I call the page, and check to see if the proper submit button has been clicked, is that how i am suppose to do it?
Also, I am trying to post the metadata in the code below, but how does the table replace what is already on the page?
<html>
<head>
<title>CNT 4714 - Project Five Database Client</title>
</head>
<body style="background-color:white">
<center>
<h1 style="color:red">CNT 4714 - Project Five Database Client</h1>
<hr>
<div style="float:left; text-align:left;padding-right:80px; padding-left:80px; ">
<font color="yellow">
<?php
?>
Welcome Back!<br>
<?php echo $_POST["user"];?>
</font>
</div>
<font color="yellow">
<div style="float:left; text-align:left">
<center>
<h2 style="color:green">Enter Query</h2><br><br>
Please enter a valid SQL Query or update statement. You may also just press<br>
"Submit Query" to run a defualt query against the database!
<form action="" id="sql" method="post">
<br>
<textarea rows="10" cols="50" name="query" form="sql">Enter text here...</textarea><br><br>
<input type="submit" name="submit" color="red">
<input type="submit" name="" color="red" value="Submit Update">
</form>
<?php
if(isset($_POST['submit'])){
echo "hello";
query(); //here goes the function call
}
function query()
{
echo "hello";
$conn = mysqli_connect("localhost:3306", "root", "*******", "project4");
$query = $_POST["query"];
$result = mysqli_query($conn, $query);
$metadata = mysqli_fetch_fields($result);
print("<tr>");
for($i=0; $i<count($metadata);$i++){
print("<tr");
printf("%s",$metadata[$i]->name);
print("</tr>");
}
}
?>
</center>
</div>
</font>
</center>
</body>
</html>
You are trying to get the values of the global variable $_POST while you are posing it to $_GET. The way to fix this is assigning the method into your form element.
Example:
<form id="sql" action="" method="POST">
There are many ways for checking or the form is submitted, one of this ways (the one I am always using) is checking or the $_SERVER['REQUEST_METHOD'] is equal to "POST". This way you can tell the different between a GET, POST, or PUT request.
Example:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['sql']))
{
....
}
}
If you're using $_POST, your form request method should be POST.
<form action="" id="sql" method="post">
Otherwise, it will submit it with a GET request by default.
In that case, you will have to access the variable using $_GET instead.
So I'm new to PHP and I'm having trouble getting some of my forms to function. I think it may be the way my site is set up that's causing me problems.
I have index.php which is set up as such:
<div class="pageContent">
<div id="main" style="width:1000px; margin:0 auto;">
<!-- Create the tabs -->
<div id="tabs" >
<ul>
<li>Overview</li>
<li>Ranked</li>
<li>Arena</li>
<li>Decks</li>
<li>New Game</li>
<li>Admin</li>
</ul>
<div id="tabs-0"></div>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
<div id="tabs-3"></div>
<div id="tabs-4"></div>
<div id="tabs-5"></div>
</div>
<!-- Load the pages into tabs -->
<script>
$("#tabs").tabs();
$("#tabs-0").load("tab0.php");
$("#tabs-1").load("tab1.php");
$("#tabs-2").load("tab2.php");
$("#tabs-3").load("tab3.php");
$("#tabs-4").load("newGame.php");
$("#tabs-5").load("admin.php");
</script>
</div><!-- / main -->
</div><!-- / pageContent -->
This gives me a nice static page and 6 tabs of .php files to do cool stuff on.
There are a couple of forms, log in and such, in index.php which all function fine. But when I create a form on a page in a tab, it will not.
Here's an example from admin.php (#tabs-5)
<?php
if(isset($_POST['delLog'])){
unlink('log.txt');
echo 'Success';
}
if(isset($_POST['delLog'])){
unlink('error_log');
echo 'Success';
}
?>
<html>
<head>
</head>
<body>
<table width="100%" border="1">
<tr>
<td width="40%" valign="top">
</td>
<td width="30%" valign="top">
<h1>error_log</h1>
<form action="" method="post">
<input type="submit" name="delErr" id="delErr" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('error_log'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
<td width="3'0%" valign="top">
<h1>log.txt</h1>
<form action="" method="post">
<input type="submit" name="delLog" id="delLog" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('log.txt'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
</tr>
</table>
</body>
</html>
This is another, better example. A stripped down test I did yesterday for this question
Problems with $_POST
<?php
define('INCLUDE_CHECK',true);
include 'php/functions.php';
error_reporting(E_ALL);
ini_set('display_errors',1);
logThis('ready!');
if (isset($_POST['submit'])) {
logThis('success');
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Neither of these examples work. When the submit button is pressed the site refreshes but no PHP actions are taking place. There is no error message in error_log. I don't think it's getting the call at all.
Neither of the forms return an output, one adds to the database. The other deletes log files.
Hope I've provided enough details.
What ever you are trying to do is not possible at all. You can not load PHP code to frontend, it can only be processed by the server.
The statement $("#tabs-5").load("admin.php"); is fetching only the html code (processed by the server) not the PHP script
<form action="" method="post"> will post to the current page (ie. whatever is in your address bar).
When you load the pages into index.php using ajax, that means the forms will post to index.php... I'm guessing you are expecting to fetch the form submissions in each individual php-file
So to fix it either you have to also post using ajax (and refresh the tabs with the response), or you need to change the action attribute on the forms to each individual php-file... in which case you lose your tabbed layout when a form is submitted. You can work around that as follows:
In each of the php-files you do something like this (using newGame.php as example):
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
// ...and then redirect back to index.php
header("Location: index.php");
die();
} else {
//Print your form
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
}
Note that there should be no <html>, <head>, <body> or other html in the "sub-pages" at all - just the bare content you want inside the tabs...
Now for the ajax-submit method you should also remove all "wrapping html", you should still set a target="[...]" on each form, and you should still do form handling inside each individual file. But you should not do a redirect after form handling, but just output the form again:
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
//Maybe print a little message to let the user know something happened
echo 'Form completed at ' . date('H:i:s');
}
//...then print your form no matter what
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
Then add this script to index.php - it will post all forms inside the tabs using ajax instead of refreshing the page:
<script>
my_cool_ajax_post = function(form_elm, tab_elm) {
//Actual ajax post
$.post(form_elm.target, $(form_elm).serialize(), function(data){
//Results are in, replace tab content
tab_elm.html(data);
});
};
$(document).on("submit", "#tabs form", function(){
//Store the form element
var form_elm = this;
//Find the parent tab element
var tab_elm = $(this).closest('#tabs > div');
//Really simple "loader"
tab_elm.html('<p>loading...</p>');
//Submit by ajax
my_cool_ajax_post(form_elm, tab_elm);
return false;
});
</script>
Disclaimer: Completely untested, so let me know...
I have two php pages. In first php page I have two divisions, where in one division I have hyperlinked text which on click showing result in other division of same page, with the help of ajax. The code for same is below:
<body>
<div id="container">
<div id="content"> Sidebar <p> </p>
<div class="form">
<pre>
<a href=sample_disease_form.php><b>Disease</b></a><p>
<a href=sample_drug_form.php><b>Drug</b></a><p>
</pre>
</form>
</div>
</div>
<div id="sidebar">
</div>
</body>
Ajax code for this is:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('a').each(function(){
$(this).on("click",function(e) {
console.log(e);
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
});
});
});
</script>
Now, I have other PHP file, one which is opening after clicking hyperlink on same page but in other division, contains form. After being clicked submit button of this form I want the result gets displayed in same division but it will come from different PHP file. How can I achieve this?
The second file's code is below:
<pre><h2> Drug </h2></pre>
<pre><p><span class="error"> * required field </span></p></pre>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<pre> Name: <input type="text" name="drug" value="<?php echo $drug;?>"><span class="error">* <?php echo $nameErr;?></span>
<input type="checkbox" name="drug[]" value="disease">Disease</br>
<input type="checkbox" name="drug[]" value="target">chemical
<input type="submit" name="submit" value="Submit"></pre>
</form>
Since I am very new to these kinds of programming stuff, expecting help.
you need to submit the page through ajax and load the result in the same div
I have a little problem. I want to reload my page after submitting a form.
<form method="post" action="">
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input type="submit" value=" Update " id="update_button" class="update_button"/>
</form>
only use
echo "<meta http-equiv='refresh' content='0'>";
right after insert query before }
example
if(isset($_POST['submit']))
{
SQL QUERY----
echo "<meta http-equiv='refresh' content='0'>";
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
on your full page, you could have this
<?php
// check if the form was submitted
if ($_POST['submit_button']) {
// this means the submit button was clicked, and the form has refreshed the page
// to access the content in text area, you would do this
$a = $_POST['update'];
// now $a contains the data from the textarea, so you can do whatever with it
// this will echo the data on the page
echo $a;
}
else {
// form not submitted, so show the form
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
<?php
} // end "else" loop
?>
If you want the form to be submitted on the same page then remove the action from the form attributes.
<form method="POST" name="myform">
<!-- Your HTML code Here -->
</form>
However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header
function page_redirect($location)
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
exit;
}
// I want the page to go to google.
// page_redirect("http://www.google.com")
LOL, I'm just wondering why no one had idea about the PHP header function:
header("Refresh: 0"); // here 0 is in seconds
I use this, so user is not prompt to resubmit data if he refresh the page.
See Refresh a page using PHP for more details
You can maybe use :
<form method="post" action=" " onSubmit="window.location.reload()">
<form method="post" action="">
<table>
<tr><td><input name="Submit" type="submit" value="refresh"></td></tr>
</table>
</form>
<?php
if(isset($_POST['Submit']))
{
header("Location: http://yourpagehere.com");
}
?>
action attribute in <form method="post" action="action="""> should be just action=""
You want a form that self submits? Then you just leave the "action" parameter blank.
like:
<form method="post" action="" />
If you want to process the form with this page, then make sure that you have some mechanism in the form or session data to test whether it was properly submitted and to ensure you're not trying to process the empty form.
You might want another mechanism to decide if the form was filled out and submitted but is invalid. I usually use a hidden input field that matches a session variable to decide whether the user has clicked submit or just loaded the page for the first time. By giving a unique value each time and setting the session data to the same value, you can also avoid duplicate submissions if the user clicks submit twice.
//insert this php code, at the end after your closing html tag.
<?php
//setting connection to database
$con = mysqli_connect("localhost","your-username","your-
passowrd","your-dbname");
if(isset($_POST['submit_button'])){
$txt_area = $_POST['update'];
$Our_query= "INSERT INTO your-table-name (field1name, field2name)
VALUES ('abc','def')"; // values should match data
// type to field names
$insert_query = mysqli_query($con, $Our_query);
if($insert_query){
echo "<script>window.open('form.php','_self') </script>";
// supposing form.php is where you have created this form
}
} //if statement close
?>
Hope this helps.