How to write a variable value in a text file with php - php

I have a problem with a php code. It's a simple web page hosted on my computer with two buttons and a text box. When I click + or - button the number in text box increase or decrease. Everything works as is suppose to, except when I want to write the textBox.value into a text file using php code. The result is something like "value = textBox.value" when it should be something like "value = 0". Thank you.
The code is below:
<!DOCTYPE html>
<html>
<body>
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
<?php
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = ";
fwrite($myfile, $txt);
$v = textBox.value;
fwrite($myfile, $v);
fclose($myfile);
?>
</body>
</html>

Brief Explanation:
You are trying to combine two separate languages as if both were client-side "as needed" scripting languages.
Javascript is client-side, and as such, will run based on event listeners or any other defined parameters. PHP is server-side, and as such, will run when the file is parsed. This means that your PHP is already processed and out of the picture by the time the Javascript even comes into the picture.
What is happening in your script presently:
The file is parsed, PHP is identified, and runs first. Immediately upon running, the file gets written to. PHP defaults to the text-value of "textBox.value" as it is not an actual variable (which would be preceded with $ if it were). In all honesty, it should be returning an error that "textBox.value" means nothing, essentially (PHP is not strict, so it makes a lot of assumptions). It's not, however, because it's assuming you are referencing a Constant. After the PHP is processed, the DOM is processed and sent to the browser. The PHP does not even exist at this point and has been stripped away from the DOM (rightfully so - you'd NEVER want PHP to be visible to a client).
What to do:
You cannot run this PHP snippet every time you want to increment/decrement the value with the PHP being inside of the same file (at least not without a form submit, or something to "catch" the request -- my response will be based on the fact that you simply want it to write when clicking, instead of submitting a form every time). You must change your code. One thing I'd suggest is placing the PHP inside of its own file. Then, upon incrementing/decrementing the value, you use AJAX to actually hit that file (thus triggering a file write).
Example:
index.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<script>
$("#decreaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) -1);
writeToFile($("#textBox").val());
})
$("#increaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) +1);
writeToFile($("#textBox").val());
})
function writeToFile(value){
$.ajax({
url: 'write.php?v=' + value,
type: 'GET',
dataType: 'json',
success: function(ret){
alert('Success!');
},
error: function(ret){
alert('Error!');
}
});
}
</script>
</body>
</html>
write.php:
<?php
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = " . $_GET['v'];
fwrite($myfile, $txt);
fclose($myfile);
?>
Note the Changes:
I am using JQuery in my example. I apologize if you wanted strictly native Javascript.
Also please note, I changed the PHP. You had two writes, which was unnecessary and would take more time. File Input/Output is costly, and should be used minimally. In fact, in this example, I'd personally have just written to a database. However, you did not ask for a separate solution, so I simply provided an example similar to what you had written.
Random Thoughts
You can use decrement/increment instead of what you're doing as well. Like so:
<script>
decreaseNumber.onclick = function() {
textBox.value--;
alert(textBox.value);
}
increaseNumber.onclick = function() {
textBox.value++;
alert(textBox.value);
}
</script>

Here, you are getting value in javascript easily and in php if you want to get values then you have to post the form or send through parameters in URL.Here are some ways to passing data in php :
- Passing PHP variables with $_POST
- Passing PHP variables in links with $_GET
- Passing PHP variables without POST or GET | $_SESSION
- Passing PHP variables arrays from one page to another
- Passing PHP COOKIE variables
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" name="textBox" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input type="submit" name="submit" value="Write To File">
</form>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
<?php
if(isset($_POST['submit'])){
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = ";
fwrite($myfile, $txt);
$v = $_POST['textBox'];
fwrite($myfile, $v);
fclose($myfile);
}
?>
</body>
</html>

To make php do this, you would need to submit the form. You can either do this via ajax or a normal post submit.
I've modified your code to work on a basic post submit.
Please read up on what a post method is.
I've had to make tiny changes in your HTML as well, and php.
I've commented them for ease.
You cannot combine two different languages to work together, not in this case at least. You could assign values from PHP to JAVASCRIPT variables, but not the other way around.
PHP has the ability to read values of input fields as long as they are submitted.
If you would like for PHP to write to the file every time the number is increased or decreased, you will have to do an ajax request to a php script on those particular events to get this done.(onClick)
<!DOCTYPE html>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
//You dont need to write twice, you can use both values in one single variable and write once
//added whitespce \r\n for line break
$v = $_POST['textbox'];
$txt = "value = $v";
fwrite($myfile, $txt);
fclose($myfile);
echo "written to file";
}
?>
<html>
<body>
<!--Made this a form so it can be submit to php-->
<!--Read about POST method-->
<form method="POST" action="">
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<!-- Add the name attribute so php can read the value -->
<input name ='textbox' id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input type='submit' value='Submit'/>
</form>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
</body>
</html>
LINKS THAT WILL BE USEFUL TO YOU
$_POST - http://php.net/manual/en/reserved.variables.post.php
PHP FORM HANDLING - http://www.w3schools.com/php/php_forms.asp
AJAX REQUESTS - http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

You're mixing things up and it won't work like this.
First off, enclose your input boxes inside a <form> pointing to the PHP file that will handle the increase / decrease function, and write it to the test.txt file:
<form id="handler" method="post" action="handler.php">
<!-- Your input elements here -->
</form>
Also, you'll need to add the attribute name to your textBox element, you may call it nvalue, in example.
Second, your click event listeners are invalid. The correct to set them is:
document.getElementById("decreaseNumber").addEventListener("click", function() {
document.getElementById("textBox.value").value--;
document.getElementById("handler").submit();
});
The same goes for increaseeNumber
Third, put your php in your new handler.php file. Get the increase/decrease value with $_POST['nvalue']. Write this value to the file.
Note: You may also use AJAX for this, but it's a little more advanced and you'll also probably need a JS library like jQuery.
Note 2: You can redirect back from handler.php to your form page after updating test.txt file by using php header() function.
Note 3: You can make your <input id="textBox"> to show the current value in the file test.txt by loading it above and echoing value = "<?php echo $nvalue; ?>", of course, $nvalue is gotten using fread() or similar.

Related

Submit content of div in database on button click

I have a WYSIWYG tool where I can create a content. At the bottom, I have a form where I can submit a value (from an input text) to a database. That works fine. Now, I am trying to submit the content that has been created in the WYSIWYG in the database.
I am thinking of using a value in the input as shown below:
<input name="videoLink" type="text" value="John" required/>
and use javascript to make the value dynamic. But there must be an easier way. To make the form submit the content of a div instead of having to type anything in the input box.
My code is shown below:
angular.module("textAngularTest", ['textAngular']);
function wysiwygeditor($scope) {
$scope.orightml = '<h2>Put Your Text Here</h2>';
$scope.htmlcontent = $scope.orightml;
$scope.disabled = false;
};
.ta-editor {
min-height: 80px;
height: auto;
overflow: auto;
font-family: inherit;
font-size: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/textAngular/1.1.2/textAngular.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.min.css" rel="stylesheet" />
<div ng-app="textAngularTest" ng-controller="wysiwygeditor" class="container app">
<h3>WYSIWYG Editor</h3>
<div text-angular="text-angular" name="htmlcontent" ng-model="htmlcontent" ta-disabled='disabled'></div>
<!--<h3>Raw HTML in a text area</h3>
<textarea ng-model="htmlcontent" style="width: 100%"></textarea>-->
<h3>Preview</h3>
<div ng-bind-html="htmlcontent"></div>
<!--<h3>Bound with ta-bind, our internal html-binding directive</h3>
<div ta-bind="text" ng-model="htmlcontent" ta-readonly='disabled'></div>-->
<button type="button" ng-click="htmlcontent = orightml">Reset</button>
<form action="Insert.php" method='POST' enctype='multipart/form-data'>
<label><input name="videoLink" type="text" required/></label>
<input id="button" type="submit" name="log">
</form>
</div>
Use placeholder instead of value.
Set value =" " but the placeholder="Put text here" ... otherwise you could get a lot of Johns.. I presume that's what you want to avoid? I don't think you can avoid php/ passing values to php from html [using javascript] to enter values into a database.
Your form isn't that big. You don't need that amount of js unless your site is using angular/is included in all pages of the CMS. So if the question is really how to pass variables to php with minimal javascript, then comment.
You should still use placeholder instead of value. Otherwise if people don't change the text / maybe just press enter/submit.. your required error message won't fire. That's a lot of Johns in the db! :)
Hope this helps

AJAX request callback using jQuery

I am new to the use of jQuery for handling AJAX, and have written a basic script to get the basics down. Currently I am POSTing an AJAX request to the same file, and I wish to do some additional processing based on the results of that AJAX call.
Here is my code:
**/*convertNum.php*/**
$num = $_POST['json'];
if (isset($num))
echo $num['number'] * 2;
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style type="text/css">
td {border:none;}
</style>
</head>
<body>
<table width="800" border="1">
<tr>
<td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
<td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
</tr>
<tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
</table>
<script>
$(document).ready(function () {
$('#getNum').click(function () {
var $numSent = $('#numSend').val();
var json = {"number":$numSent};
$.post("convertNum.php", {"json": json}).done(function (data)
{
alert(data);
}
);
});
});
</script>
</body>
</html>
Here is the response I get if I submit the number '2':
4
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style type="text/css">
td {border:none;}
</style>
</head>
<body>
<table width="800" border="1">
<tr>
<td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
<td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
</tr>
<tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
</table>
<script>
$(document).ready(function () {
$('#getNum').click(function () {
var $numSent = $('#numSend').val();
var json = {"number":$numSent};
$.post("convertNum.php", {"json": json}).done(function (data)
{
alert(data);
}
);
});
});
</script>
</body>
</html>
Obviously I'm only interested in receiving and using the number '4', hence my question: What is the best way to specify exactly what data I want returned?
Some thoughts I've had:
wrapping all my HTML inside a if statement (i.e., if $num isset, do NOT output html; else output HTML) but then I'm echoing HTML, and I'd rather not do that.
Setting up a separate PHP script to receive my AJAX call: That was what I did originally, and it works just fine. However, I am interested in keeping everything inside one file, and wanted to explore possible ways of doing so.
I'm sure there is an elegant way to do this. Thanks for any suggestions!
The elegant way would be to have a separate(!) PHP file that will only output the number times 2 part of your current PHP. Then you generate an AJAX request from your current PHP to the new separate PHP.
I believe this post answers one aspect of what you are seeing - the echoing of the entire page in your alert box.
Next, here are some good posts for getting the basics of AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
You could add die(); after you echo the number if you really want to keep it on the same page. This will terminate the execution of the script. Don't forget to add brackets around the if statement:
if (isset($num)) {
echo $num['number'] * 2;
die();
}
It is, however, not the most elegant solution.
NOTE *The better approach is to keep things like this in a separate file, makes it easier to read and easier to understand, especially if you use a good naming conversion.
It is a bad procedural approach but here I go :) :
<?php
$num = $_POST['json'];
if (isset($num))
echo ($num['number'] * 2);
die();
?>
or better yet:
<?php
$num = $_POST['json'];
if (isset($num))
die($num['number'] * 2); //In case of error you could put them in brackets
?>
PS
As alternative to die(); you could use exit();, they both do pretty much the same: terminating further execution
I don't know how efficient this is but you can do something like:
<?php
/*convertNum.php*/
$num = isset($_POST['json']) ? $_POST['json'] : NULL; //you have errors in this line
if (!is_null($num)){
echo $num['number'] * 2;
exit(); //exit from script
}
?>

Saving info on a server, and getting it back

On my website i take user input from a form, and add it to a query plugin to output on the screen. Its nice to get the users input, but as soon as i refresh the page, all the input is lost and reset. How can i save the user input so that even when the page is refreshed, the data will stay there for good? can u use my code to show me?
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="textualizer.min.js"></script>
</head>
<style type="text/css">
#txtlzr{color:#585856; font-size:50px; width:1200px; height:100px;
margin-left:10%;
margin-top:80px;
font-family:"futura";
position: fixed;
}
</style>
<body>
<div id="txtlzr"></div>
<form action="#" method="post"/>
<fieldset>
<label for="kwote">Comment:</label>
<input class="kwote" type="text" maxlength="40" id="kwote"
placeholder="Enter a something here."/>
<lable for="name">Name:</label>
<input class="name" type="text" maxlength="17" id="name"
placeholder="Enter your name."/>
<input class="post" type="button" value="Add comment"
onclick="add_comment();" />
</fieldset>
</form>
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Thanks for the help: nick');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
</body>
</html>
</html>
Thanks to chris btw for helping me with the input.
There is a lot to it other than just the code on the page. You have to have a server-side language and write access into a database server, before you can do anything else.
You might take a look at the Flask tutorial or the Django tutorial if you've not picked out a language and platform. Both require that you set up a server, but use SQLite, a file-based database system, so you don't need to deal with figuring out database servers yet.

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>

PHP/JavaScript How to combine 2 page in one

I need a reference on how to make 2 pages become one.
Originally i have 2 php pages. View.php and comment.php
The view.php will have a link to call comment.php. When click the 'comment' link, it will open comment.php like pop up. After fill in the comment, and click send, it will closed and return the view.php.
The problem is, Instead of popup i want it hide until i click it. I dont know what is the exact term to call this process. I know it got something to do with javascript, using id, onclick function and similar to frame function. Because i dont know what it call, it hard for me to research. So anyone please tell me what it called or gimme any references or example solution on how to do it.
thank you very much
UPDATED:
dear all..
found this code in internet. Like RageZ said..it uses css and javascript to show and hide img. how to use for others?
do i need to convert my comment.php into a function and put in view.php n use the id for that function. is it possible?
<html>
<head>
<script>
function changeme(id, action) {
if (action=="hide") {
document.getElementById(id).style.display = "none";
} else {
document.getElementById(id).style.display = "block";
}
}
</script>
</head>
<body>
<img id="myIMG" style="display: none;" src="question.php.html"width="100" height="100" />
<span onclick="changeme('myIMG', 'show');" style="color: blue; text-decoration: underline; cursor: pointer;">Show the image</span>
<span onclick="changeme('myIMG', 'hide');" style="color: blue; text-decoration: underline; cursor: pointer;">Hide the image</span>
</body>
</html>
I think what your looking for is something like Greybox?
It opens a new pag ontop of the page, instead of opening a popup, you best check out the examples, they will be way more clear than anything I can say here.
You can do the described process for example with the following:
view.php
<script language="JavaScript">
function openComment(id) // Open comment.php in a new window and send the id of the thing you want to comment
{
window.open('comment.php?id='+id, '_blank');
}
</script>
Comment
comment.php
<?php
if ( isset($_POST['msg']) && intval($_POST['id']) > 0 ) // If a comment is sent and the id is a number > 0
{
/* Write your message to db */
?>
<!-- Reload the underlying window and close the popup -->
<script language="JavaScript">
window.parent.reload();
window.close();
</script>
<?php
}
else // Show the Form to post a comment
{
?>
<form name="comment" action="comment.php" method="POST">
<input type="hidden" name="id" value="<?php echo $_GET['id'] ?>" />
<input type="text" name="msg" value="Input your comment here" />
<input type="submit" value="Submit" />
</form>
<?php } ?>
you can use Ajax/DHTML to make the popup and post the data to the server in the same page.
I think you would need a framework to do that quick there is a lot of javascript framework around:
jquery
dojo
ExtJS
prototype
All I have forgotten

Categories