how to pass POST variable by links to own pages? - php

Hi i wannna get variable $_POST by link to self pages. Example :
<?PHP
$var = 'PIG';
echo "<a href='test.php?var=$var'>link</a>";
if (isset($_POST['var']))
{
echo $_POST['var']);
}
?>
it links to own pages. (test.php)
It not works, who can help me please. Thanks

A link cannot POST data, only GET.
In contrast to the GET request method where only a URL and headers are
sent to the server, POST requests also include a message body. This
allows for arbitrary length data of any type to be sent to the server.
Basically, a POST requires two requests, 1) the server receives the "normal" request, with an extra header value indicating that more data needs to be sent. At that point, the server sends an acknowledge and 2) the client sends the POST body. This behavior cannot be achieved only with a link.
However, there are solutions to this and I have seen some technique, among others, outputting a form with an autosubmit, something like
<form name="frm" method="post" action="http://your.domain.com/path/to/page.php?param1=1&param2=2">
<input type="hidden" name="foo" value="bar" />
</form>
<script type="text/javascript">
document.forms["frm"].submit();
</script>
which would result into calling page.php with these arguments
$_GET = array('param1' => '1', 'param2' => '2');
$_POST = array('foo' => 'bar');
Note that this is a simple "redirect" method, but you can create <a> elements to actually trigger some hidden form like that instead of using the standard link. (untested code)
A simple link
<script type="text/javascript">
function dopost(url, params) {
var pe = '';
for (var param : params) {
pe += '<input type="hidden" name="'+param+'" value="'+params[param]+'" />';
}
var frmName = "frm" + new Date().getTime();
var form = '<form name="'+frmName+'" method="post" action="'+url'">'+pe+'</form>';
var wrapper = document.createElement("div");
wrapper.innerHTML = form;
document.body.appendChild(wrapper);
document.forms[frmName].submit();
}
</script>
This is probably what you need, actually.

Items in the query string are available via $_GET, not $_POST, since they are not actually POSTed. If you want to POST then you must either use a form with a method of post, or you must perform a XHR as POST.

Unfortunately, you really can't do that. If you need to use an anchor to submit a value, then you will need to access the variables through $_GET or $_REQUEST.
If it has to be a $_POST (if you are set in that design decision, because $_GET actually makes a lot more sense there), you can use a form and the style the submit button to make it look very much like a link. Put this code in a text editor and check it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
.button {border:none;background-color:#FFFFFF}
.button:hover{ color:blue; }
</style>
</head>
<body>
<form action="test.php">
<input type="hidden" name="var" value="<?php echo $val; ?>" />
This kinda looks like a link:
<input type="submit" value="link" class="button" />
</form>
</body>
</html>

If you have multiple links and you don't want to rewrite all of them, just add one fake form like this:
<form id="fakeForm" method="post">
<input type="hidden" name="post_key" value="post_value" />
</form>
and set up proper jquery:
$('a').click(function(event){
event.preventDefault();
$('#fakeForm').attr('action',$(this).attr('href')).submit();
});
In this case, when you click on any link, the landing page receives the post_value variable.
Note that if the link is clicked with other than left click (or js is disabled), the link works properly, but the value isn't passed!

This code below demonstrates T30's idea works.
My rationale for passing via $_POST is to prevent certain variables from being exposed in the url which is accomplished here. However, they would still be exposed via "view source".
<?php
/*
This demonstrates how to set $_POST from a link in .php without ajax based on the idea from http://stackoverflow.com/a/27621672/1827488. The rationale for doing so is to prevent certain variables ('userid') from being exposed in the url via $_GET. However, there does not seem to be a way to avoid those variables being exposed by 'view source'.
*/
echo "<!DOCTYPE html><html lang='en'><head><title>Test Data Link</title></head><body>";
// only one hidden form
echo "<form class='hiddenForm' method='post'>
<input class='hiddenFormUserid' type='hidden' name='userid'/>
</form>";
// as many links as you need
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=101>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=101>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=102>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=102>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=103>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=103>Followers</a></p>";
echo "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>";
echo "<script type='text/javascript'>
console.log('jq');
$('.hiddenFormLink').click(function(e){
console.log('data-userid=' + $(this).attr('data-userid') + ', value=' + $('.hiddenFormUserid').val());
e.preventDefault();
$('.hiddenFormUserid')
.val($(this).attr('data-userid'));
$('.hiddenForm')
.attr('action',$(this).attr('href'))
.submit();
});
</script>";
if (isset($_GET["following"]) || isset($_GET["followers"])) {
if (isset($_GET["following"])) {
echo "followed by ";
} else {
echo "followers of ";
}
if (isset($_POST["userid"])) {
echo $_POST["userid"]."<br>";
} else {
echo "no post<br>";
}
} else {
echo "no get<br>";
}
echo "</body></html>";
$_POST["userid"] = "";
?>

Related

Return the url to its original state after refresh

I wrote this form using html and PHP on my webpage. This form receives a number as input. and adds the desired number to 2. And prints the output.
For example, if we put the number 5 at the input and press the submit button , The page refreshes to this URL : mysite.com/page1/?sen=5&sub=Submit
And the number 7 is printed on the output.
So far so good. But when we refresh the page in this case , The submitted information will not be deleted and the url will remain "mysite.com/page1/?sen=5&sub=Submit" .And the output is not cleared and still remains 7.
In this case, I want the page to return to its original state, (mysite.com/page1) . And the output is cleared.
what's the solution?
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php if ( isset($_GET['sub'])){
//$sen1=0;
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
else {
echo $sen1 + 2; }
}
?>
This can easily be achieved with Javascript. Here's a very basic example.
You could make this a function. Then call it once to invoke it on a page refresh, and if you want to invoke it on button actions, you can use an html onclick attribute, or an event listener.
<script>
function clearFormAndParams() {
// Target each form input and set the value to "".
document.querySelector("input[name='sen']").value = "";
// Split the url by the "?" and then set the value to the first half.
window.location = window.location.href.split("?")[0];
}
clearFormAndParams(); // runs on refresh
var submitButton = document.querySelector("input[name='sub']");
submitButton.addEventListener("click", function() {
clearFormAndParams();
});
</script>
You could achieve your goal by modifying your code to store the results of calculation in a cookie / session variable and redirecting to the same page without the extra parameters like so:
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php
if ( isset($_GET['sub'])){
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
setcookie("result", $sen1 + 2);
header("Location: " . $_SERVER['PHP_SELF']);
}
echo $_COOKIE['result'];
?>

How to create confirm yes/no in php?

I want to create a confirm yes/no box in php
my code like this:
<?php
if(isset($_REQUEST['id']))
{
?>
<script>
var cf=confirm("do you want to delete Y/N");
if(cf)
{ i want to call code edit of php
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name="frm" method="post" action="edit.php">
Edit <br>
Edit <br>
Edit <br>
</form>
</body>
</html>
I Want to when press Yes i call code edit in PHP
But it do not work.
Can you help me ?
Thanks you
Just use inline onclick event.
This is a simple techique, you can use it in your PHP page.
Edit
In your code, you have mentioned PHP but, have used JavaScript.
If you want to do a confirm with PHP,
Create an intermediate page for confirmation.
Post form data there.
On confirmation page, add two submit buttons:
Yes: If pressed this, redirect/post to edit page.
No: If pressed this, redirect back to form
So, your confirmation page should be:
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['confirm'])) {
if ($_POST['confirm'] == 'Yes') {
header("Location:edit.php?id=1");
}
else if ($_POST['confirm'] == 'No') {
header("goBack.php");
}
}
?>
<form method="post">
<?php
if(isset($_REQUEST['id']))
{
?>
<input type="submit" name="confirm" value="Yes"><br/>
<input type="submit" name="confirm" value="No"><br/>
<?php
}
?>
</form>
Put an id on your form:
Create an event listener for the form's onsubmit event
<script>
function onFormSubmission(e){
return confirm("do you want to delete Y/N");
}
var frm = document.getElementById('frm');
frm.addEventListener("submit", onFormSubmission);
</script>
When the user submits a form they will be prompted with your message. If they click Yes the function will return true and the form will be submitted. Otherwise the function will return false and the form submission will be cancelled
I think this is what you want to do:
<?php
//YOU MUST BE SURE THAT YOUR URL CONTAINS THE $_REQUEST['id'] PARAMETER, OTHERWISE IT WON'T WORK FROM YOUR CODE... IF YOU WANT IT TO WORK REGARDLESS OF THAT, JUST COMMENT OUT THE IF(ISSET(... BLOCK...
$editURL = "edit.php"; //EDIT URL HERE
if(isset($_REQUEST['id'])) {
//ASSIGN THE ID TO A VARIABLE FOR BUILDING THE URL LATER IN JS...
//THE DEFAULT ID IS 1 BUT YOU CAN DECIDE WITH YOUR OWN LOGIC
$defaultID = ($dID = intval(trim($_REQUEST['id']))) ? $dID : 1;
?>
<script>
function confirmEdit(evt){
evt.preventDefault();
var cf=confirm("do you want to delete Y/N");
var id=<?php echo defaultID; ?>;
if(cf){
//i want to call code edit of php
//HERE'S THE CODE YOU MAY NEED TO RUN;
if(id){
//RETURN TRUE SO THAT THE SCRIPT WITH LINK TO THE APPROPRIATE URL
return true;
// OR REDIRECT WITH JAVASCRIPT TO EDIT PAGE WITH APPROPRIATE ID
//window.location = "" + <?php echo $editURL; ?> + "?id=" + id; //YOU ALREADY HAVE THE EDIT URL... JUST APPEND THE QUERY-STRING WITH ID TO USE IN THE EDIT PAGE
// You might also just (without redirecting) return true here so to that the page continues like you just clicked on the link itself...
}
}
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<!-- THE FORM TAG IS NOT NECESSARY IN THIS CASE SINCE YOUR ANCHOR TAGS HAVE THE EXACT URL YOU WANT ASSOCIATED WITH THEM... AND YOU DON'T EVEN NEED JAVASCRIPT IN THIS CASE... BECAUSE THE HREF OF THE LINKS ARE HARD-CODED... -->
<!-- <form name="frm" method="post" action="edit.php"> -->
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-1' href="edit.php?id=1">Edit Page 1 </a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-2' href="edit.php?id=2">Edit Page 2</a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-3' href="edit.php?id=3">Edit Page 3</a> <br>
<!-- </form> -->
</body>
</html>
So, now clicking on any of the Links will Ask me to confirm if I want to delete the Resource or not. If I choose yes, then the appropriate page is loaded for the Process...
not sure if the other answers really answered your question, this was my problem too, then I experimented and here's what I came up with:
.
confirmation in php :
$Confirmation = "<script> window.confirm('Your confirmation message here');
</script>";
echo $Confirmation;
if ($Confirmation == true) {
your code goes here
}
that's all, other people might look for this, you're welcome :)
I was looking to simply have a confirmation box in php before triggering POST isset without going through javascript:
echo "<input id='send_btn' type='submit' value='previous'
name='previous' OnClick=\"return confirm('Are you sure you want to go
to previous');\" >";
This appeared for me to be the easiest solution.

Add items to array without refreshing the page?

http://alpha.ripfy.com/
As seen in the following demo, I have a YouTube video that I want to be able to play while adding items to the array in PHP. Sadly, this isn't possible from what I've tried because the page refreshes every time I add an item to the array.
Would there be any way of achieving this without the page refreshing (forcing the video to restart?)
Code:
<?php
if (isset($_POST['playlist'])) {
$playlist = $_POST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_POST['name1'])) {
$playlist[] = $_POST['name1'];
}
?>
<form method="post">
<?php
foreach($playlist as $song) {
?>
<input type="hidden" name="playlist[]" value="<?php echo $song?>">
<?php
}
?>
<input type="text" name="name1"/>
<input type="submit" name="submit1"/>
</form>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
Thanks for helping me out!
if you need that these information be storaged in database or anything on server sider don't use the convencional form post, use AJAX with JQuery.
First create a div(container)to render the list content where you need the information apears:
<div id="list_musics"></div>
Then create a page(i.e. page.ajax.php) that will treat your request. If you need you can put the information in a database or anything you want by this page. This page must return the content you want to render.
HTML:
<input type="button" id="ajaxcaller">
JQUERY:
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
$.post(page.ajax.php,text,function(data){
//Render your content in the container created on HTML
$("#list_musics").html(data);
});
});
If you just need to show what you wrote on text input instead of storage or treat the information, you may just use JQUERY to render the information in the container you created.
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
// PUT THE TEXT RIGHT AFTER THE CONTENT THAT ALREADY EXISTS IN THE CONTAINER
$("#list_musics").append(text);
});
Take a look here to see the sencond option:
https://jsfiddle.net/wqLf65ox/
Here's my answer. That fully works. In this script, the server checks the presence of a name1 request (post or get). If exists, it returns the string posted (only) and if doesn't, it returns what already was there. And the post() method posts (gets) the data and appends to the container using innerHTML+= data + "<br>";
evaluate the code, it should be self explanatory.
<?php
if (isset($_REQUEST['playlist'])) {
$playlist = $_REQUEST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_REQUEST['name1'])) {
// if exists, return plain text responce. NOT HTML
$playlist[] = $_REQUEST['name1'];
echo $_REQUEST['name1'];
}
else{
?>
<html>
<head>
<title>Demo</title>
<script src="jquery.js"></script>
</head>
<body>
<script>
text= ""
function onUpdate(){
text = document.getElementById("name1").value;
}
function handler(data){
document.getElementById('container').innerHTML += data+"<br>";
}
function post(){
onUpdate();
$.get("index.php", name1="+text, handler);
}
</script>
<input type="text" name="name1" id="name1"/>
<input type="submit" name="submit1" onclick="post()"/>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<br>
<div id="container">
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
</div>
</body>
<?php };?>
Although, it works as intended, i don't see the point of using it. just plain js should work
You have to send your form using Ajax, eg. via jQuery.post() method.
After that you have to reload your container with list or add new item there with JavaScript.
Try using the $.post and $.get JQuery methods. One method might be to $.post back to a .php page that renders a container of html, then use $.get to retrieve just that html container and insert into the DOM.

PHP Page load/refresh to exact position

What I'm trying to do is to pass a user to a php script via a href link, then have them passed back to exactly the same position that they were at before they clicked the link, like the page hasn't been refreshed. Does anyone know if or how this could be possible possible? Thank you.
Using HTML you can have the following
<p id='open_here'><a href='script.php'> Send to script </a> </p>
And then you can link back to that exact position with
Send Back to page
So essentially, instead of using a regular link as in the previuos code snippet, you could redirect back to the page using
//php redirect
<?php header('Location: mypage.html#open_here'); ?>
//Javascript redirect
<script type='text/javascript'>
window.location = "mypage.html#open_here";
</script>
If you don't mind adding some Javascript to make it work, here is a solution that will make it possible to redirect back to the exact same scrollbar position as when the user clicked the link.
index.php (the file where the link is)
<script>
window.addEventListener('load', function() {
// Do we have a #scroll in the URL hash?
if(window.location.hash && /#scroll/.test(window.location.hash)) {
// Scroll to the #scroll value
window.scrollTo(0, window.location.hash.replace('#scroll=', ''));
}
// Get all <a> elements with data-remember-position attribute
var links = document.querySelectorAll('a[data-remember-position]');
if(links.length) {
// Loop through the found links
for(var i = 0; i < links.length; i++) {
// Listen for clicks
links[i].addEventListener('click', function(e) {
// Prevent normal redirection
e.preventDefault();
// Redirect manually but put the current scroll value at the end
window.location = this.href + '?scroll=' + window.scrollY;
});
}
}
});
</script>
page.php (the PHP script that redirects back)
<?php
// Get the provided scroll position if it exists, otherwise put 0
$scrollPos = (array_key_exists('scroll', $_GET)) ? $_GET['scroll'] : 0;
// Redirect back to index.php and provide the scroll position as a hash value
header('Location: index.php#scroll='.$scrollPos);
Hope it helps! :)
I am just spilling ideas here, but I would use javascript to intercept user's click on the href, and .preventDefault first. Then figure out where the user is on the page. Maybe by splitting the page into sections, indentified by IDs. Your html markup would be something like
<div id="section-1"></div>
<div id="section-2"></div>
<div id="section-3"></div>
so when javascript prevents the link from executing, it would figure out in which section the user currently is. Let's say we know each section's height. Then we need to find out the scrollbar position. I haven't done that, but have a look here
http://api.jquery.com/scrollTop/
Once we know the height of each section and once we can detect where the scroll bar is, we can determine in which section the user is residing. Then, we fetch the url of the href link and add a query string to it like, http://something.com/script.php?section=2 and redirect user to it with whatever data you want . Then once the script has done it's job append the query string to the redirect-uri and redirect the user back with something like http://something.com#section-2 and the user will immediatly pop to section-2
I know this isn't a very specific answer, but hopefully I've given you some leads and ideas how to accomplish this. Let me know how it works!
I'd had to remember the scroll position for a <select>. Example below. Three
submit buttons to illustrate why there's three getElementById. To see
it work you must move the scroll bar first
<?php
$scrollusObscura=$_GET["imgbtn"];
$header = <<<EOD
<!DOCTYPE html>
<html>
<head>
<title>snk_db</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<head>
<script>
function gety(){
var y=document.getElementById('myUlID').scrollTop;
document.getElementById('imgbtn1').value=y;
document.getElementById('imgbtn2').value=y;
document.getElementById('imgbtn3').value=y;
}
function itemRelevatur(scrollum){
document.getElementById('myUlID').scrollTo(0, scrollum);
}
</script>
</head>
<body onload="itemRelevatur({$scrollusObscura})" >
EOD;
$html= <<<EOD
<div >
<select size="6" id="myUlID" name="myUlName" onscroll="myTimer = setInterval(gety, 300)">
<option>'1'</option>
<option>'2'</option>
<option>'3'</option>
<option>'4'</option>
<option>'5'</option>
<option>'6'</option>
<option>'7'</option>
<option>'8'</option>
<option>'9'</option>
<option>'10'</option>
<option>'11'</option>
<option>'12'</option>
<option>'13'</option>
<option>'14'</option>
<option>'15'</option>
<option>'16'</option>
<option>'17'</option>
<option>'18'</option>
<option>'19'</option>
</select>
</div>
EOD;
$html1= <<<EOD
<div><form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn1' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html2= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn2' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html3= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn3' value=''></input>
<input type='submit' value='Submit' ></input>
</form></div>
EOD;
echo $header;
echo $html;
echo $html1;
echo $html2;
echo $html3."</body></html>";
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>

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