passing array of string from php to html - javascript

I want to tranform a php array of string into html. My php and html code are in the same page.
I have $myvar that hold my array of string. I pass $myvar with POST and insert it to $ba.
My code needs to print on html page 3 line (in while loop).
But when I pass the $be, it writes me error message: "Notice: Undefined index: myvar" (in php code)
What do I need to repair so that my code prints to my screen all the 3 lines that I get from php?
my code:(php)
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("", $myvar);
my html code:
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p> <?php echo $ba ?> </p>

Simply echo the mysql query on a function and call it on HTML as follows:
UPDATE: 3rd column will be an image wich route are stored on database, and 4th col will be an image eich only the name was stored on database (because we know the full route) as example:
<?php
function printOnHtml(){
include ("connection.php");
$sql = "SELECT * FROM foo;"
if ($result = connection()->query($sql)){
$rs = $result->fetch_array(MYSQLI_NUM);
while ($rs[0] != ''){
echo "first column: ".$rs[0]." second column: ".$rs[1]." image with full route on database: <img src='".$rs[2]."' alt=''> <br> if only the img name is stored cuz we know the route: <img src='img_route/".$rs[3]."' alt=''>";
$rs = $result->fetch_array(MYSQLI_NUM);
}
}
}
Then on HTML
<html>
blablabla
<body>
blablabla
<?php
printOnHtml();
?>
blablabla
</body>
</html>
Note that it have to be a .php file to call the php function (for example index.php)
I paste the connection php script i use in order if you need it:
<?php
function connection(){
if($mysqli = new MySQLi("localhost","user","password","database_name")) echo "OK"; else echo "KO";
mysqli_set_charset($mysqli, "utf8");
return $mysqli;
}
?>
i did it with mysqli fetch array, but you can do the same using fetch assoc if you want.
UPDATE2: If you stubborness makes you follow using a txt to store data (wich, if increase will fail when you get a some thousands line txt), modify this on your code:
$myvar='';
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
if(isset($myvar)){
$myvar=fgets($handle);
}
$counter++;
}
}
}
and i'm supposing that you declared $dir, $file and other vars properly.
You NEVER have to use vars without declaring it (as NULL at least). You only can do this if you ensured 100% that this var will get a value at this point.

You have to convert the array to string in a correct way using implode and <br> as a separator
Then just print it using php tags (as you are using both at the same page ) you can access the variable direct and print it using <?= $ba ?> or <?php echo $ba ; ?>
Code will be :
<?php
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("<br>", $myvar);
?>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p id="deatiles"> <?= $ba ?> </p>

Related

Submit and POST "True" or "False" to a series of text questions presented one by one taken from a php array

new to forum, AJAX and JQuery. A little experience of PHP and JS.
I'm trying to present a long series of questions (400+) one by one in an input text field on a form with 2 submit buttons labelled "True" and "False". I need one question to be presented at a time, then record the True or False result as (1 or -1) sequentially into another text file. I cannot refresh the input field with the next question after 'Submit'. I believe that AJAX would be the answer.
This code is the first effort: (any later efforts are more complicated, but don't work any better) it opens the questions file (CPXQ.dat) into an indexed array, then places the first question into the input text field. When either of the submit buttons are pressed, the result is POSTed to data.cpx, and the next question appears, but it won't continue thereafter. I have tried various PHP loops and some javascript, but these don't work, either looping through immediately to the last question, or getting stuck in the loop. (The php includes just contain CSS and JQuery source.)
I'd also like to prevent the user from being able to go back over any of the questions, but that may be a query for another day!
Any advice much appreciated, and apologies if not clear. Happy to provide any further info.
<div class="container">
<?php include("top.php"); ?>
<div class="intro">
<p><h1>CPI TEST</h1></p>
<?php
$i = 0;
//file in to an array
$lines = file("CPXQ.dat");
?>
<?php
if(isset($_POST['submitT'])) {
//echo $_POST['submitT'];
$data="1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
if(isset($_POST['submitF'])) {
//echo $_POST['submitF'];
$data="-1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
?>
<form method = "post" action = "CPI_Test.php">
<input type="text" name="question" value="<?php echo $lines[$i];?>">
<input type="submit" name="submitT" value="True">
<input type="submit" name="submitF" value="False">
</form>
</div>
</body>
Here's the code for the preliminary page collecting user details:
<!DOCTYPE html>
<html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PPCS CPI Information</title>
<?php include("head.php"); ?>
</head>
<body>
<?php
// define variables and set to empty values
$initdataErr = $surnamedataErr = $agedataErr = $gendataErr = "";
$initdata = $surnamedata = $agedata = $gendata = $codata = "";
function test_input(&$surnamedata) {
$surnamedata = trim($surnamedata);
$surnamedata = stripslashes($surnamedata);
//$data = htmlspecialchars($data);
$surnamedata = preg_replace('/\s+/', '', $surnamedata);
return $surnamedata;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['initdata'])) {
$initdataErr = "Initials are required";
} else {
$initdata = test_input($_POST['initdata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Z- ]*$/",$initdata)) {
$initdataErr = "Please use capital letters without spaces only";
}
}
if (empty($_POST['surnamedata'])) {
$surnamedataErr = "Surname is required";
} else {
$surnamedata = test_input($_POST['surnamedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$surnamedata)) {
$surnamedataErr = "Please use letters only";
}
}
if (empty($_POST['agedata'])) {
$agedataErr = "Age is required";
} else {
$agedata = test_input($_POST['agedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$agedata)) {
$agedataErr = "Only numbers and white space allowed";
}
}
if (empty($_POST['gendata'])) {
$gendataErr = "Gender is required";
}
}
?>
<div class="container">
<?php include("top.php"); ?>
<br><h1>CPI TEST INFORMATION</h1><br>
<b>Please fill in the form below carefully</b>
<p><span class="error">* required field</span></p>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Initials: <span class="error">* <?php echo $initdataErr;?></span> <br>
<input type="text" name="initdata" value="<?php echo $initdata;?>"><br>
<br>
Surname: <span class="error">* <?php echo $surnamedataErr;?></span> <br>
<input type="text" name="surnamedata" value="<?php echo $surnamedata;?>" ><br>
<br>
Company (Optional):<br>
<input type="text" name="codata" value="<?php echo isset($_POST["codata"]) ? $_POST["codata"] : '';?>" ><br>
<br>
Age in Years: <span class="error">* <?php echo $agedataErr;?></span><br>
<input type="text" name="agedata" maxlength="2" min="0" max="99" step="1" pattern="[0-9]{2}"value="<?php echo $agedata;?>"><br>
<br>
Gender: <span class="error">* <?php echo $gendataErr;?></span><br>
<select name="gendata">
<option value="">Select...</option>
<option value="m" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'm') ? 'selected' : ''; ?>>Male</option>
<option value="f" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'f') ? 'selected' : ''; ?>>Female</option>
</select>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit'])){
// Fetching variables of the form which travels in URL
$initdata = $_POST['initdata'];
$surnamedata = $_POST['surnamedata'];
$codata = $_POST['codata'];
$agedata = $_POST['agedata'];
$gendata = $_POST['gendata'];
if($initdata !=''&&(preg_match("/^[A-Z]*$/",$initdata))
&& $surnamedata !='' && (preg_match("/^([A-Za-z \-]+(?:\'|&#0*39;)*)*[A-Za-z \-]+$/",$surnamedata)) && $agedata !='' && (preg_match("/^[0-9]*$/",$agedata)) && $gendata !='')
{
date_default_timezone_set("Europe/London");
//^['\a-zA-Z]*$/ This is the most recent
test_input($surnamedata);
$_POST['surnamedata'] = ucwords($_POST['surnamedata']);
$data = '"' . $_POST['initdata'] . ' ' . stripslashes($_POST['surnamedata']) . '","' . $_POST['agedata'] . '","'. $_POST['gendata'] .'","' . $_POST['codata'] . '","' . '","'. '","'. date("d/m/Y"). '","'. date("H:i:s"). '","';
//Create CPX filename
$fn = $_POST['initdata'] . $_POST['surnamedata'];
$fn = preg_replace('/\PL/u', '', $fn);
$fn = strtoupper($fn);
$fn = $fn . "XXXXXX";
$fn = substr($fn,0,8);
echo "$fn";
echo "$data";
//Create temp file for CPX filename
$fp = fopen($fn . '.temp', 'a') or die("Unable to open file!");
fwrite($fp, $fn);
fclose($fp);
//Create CPX file
$fp = fopen($fn . '.cpx', 'a') or die("Unable to open file!");
fwrite($fp, $data);
//Append new line
//fwrite($fp, "\ntest");
fclose($fp);
// Redirect
/header("Location:/CPI_Form_Trial/instructions.php");
}
else{
?>
<br><span class = "error"><?php echo "Please make sure that you have filled in all required fields and click 'Submit' again";?></span> <?php
}
}
?>
Using AJAX (fetch) is ideally suited to this type of problem where you do not wish to refresh the screen and want to present new data after submitting a http request. The following single page application shows how you might accomplish your stated goal but it does not take into account a couple of possible issues which are:
[a] multiple users participating in the questionnaire simultaneously
[b] a user abandoning the questionnaire and restarting, once or more than once.
The issues mentioned could be negated by using a database to store answers and assigning the users unique identifiers (ie: user id, username) which is used when sending the ajax request.
The demo that follows will write, to the answerfile, either 1 or 0 ( which is more common than -1 for false ) alongside the question line number ( which is sort of the ID )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
$file='CPXQ.dat';
$answerfile='data.cpx';
$lines=file( $file );
switch( $_POST['action'] ){
case 'start':
header('Content-Type: text/html');
exit( $lines[0] );
break;
case 'question':
$id=(int)$_POST['id'];
# increment ID value
$id++;
$question=isset( $lines[ $id ] ) ? $lines[ $id ] : false;
if( $question && $id < count( $lines ) ){
# log the current answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
# the json payload
$data=array(
'id' => $id,
'question' => $question
);
} elseif( !$question && $id==count( $lines ) ){
# log the final answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
$data=array(
'id' => 0,
'question' => 'End of questionnaire'
);
}
header('Content-Type: application/json');
exit( json_encode( $data ) );
break;
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Questions, questions, questions...</title>
</head>
<body>
<!--
a basic form: The question is rendered within the `fieldset`
element. Both buttons use datasets, the data-id refers to the
question number (line from source file) and data-value is the
boolean value indicating answer value.
-->
<form name='questions' method='post'>
<fieldset></fieldset>
<div>
<input type='button' data-value=1 data-id=0 value='True' />
<input type='button' data-value=0 data-id=0 value='False' />
</div>
</form>
<script>
const fs=document.querySelector('fieldset');
/*
When the page loads we fetch the first question ( ie: first line in source file )
and display on the page. The action parameter helps the backend determine what stage
we are at.
*/
let fd=new FormData();
fd.set('action', 'start');
// make the request an show question
fetch( location.href, { method:'post', body:fd })
.then(r=>r.text())
.then(text=>{
fs.innerHTML=text;
});
/*
The delegated event handler processes button clicks and sends the
data-id ( ie: line number ) and answer to the backend processing script.
Here this is all done on the same page for convenience - for your case
it would be CPI_Test.php
*/
const clickhandler=function(e){
if( e.target.tagName.toLowerCase()=='input' && e.target.type=='button' ){
// set a different `action` so that the backend knows what to do
fd.set('action','question');
fd.set('id',e.target.dataset.id);
fd.set('answer',e.target.dataset.value);
// send the request and display new question
fetch( location.href, { method:'post', body:fd } )
.then( r=>r.json() )
.then( json=>{
fs.innerHTML=json.question;
// update the buttons so that they have the new id assigned ready for next click
// or disable ( or remove ) when the questionnaire is over.
document.querySelectorAll('[type="button"][data-value]').forEach( bttn=>{
if( Number( json.id ) !==0 ) bttn.dataset.id=json.id;
else bttn.disabled=true;
});
})
}
};
// add a delegated event handler to process button clicks
document.forms.questions.addEventListener( 'click', clickhandler );
</script>
</body>
</html>
A sample of the answerfile:
q:1, a:1
q:2, a:0
q:3, a:1
q:4, a:1
q:5, a:0
q:6, a:0
q:7, a:1
q:8, a:0
q:9, a:1
q:10, a:0
q:11, a:1
q:12, a:1
q:13, a:1
q:14, a:1
q:15, a:0
q:16, a:1
q:17, a:0
q:18, a:1
q:19, a:1
q:20, a:0
I hope it helps you arrive at a solution but as mentioned it would be more robust / reliable with a database rather than simple text file.

Is there a way to pass value of a Button on click to another php file?

My aim is to get the lec_id which is the Button value when the button is clicked and pass it to chapters.php where I use the button value for a SQL query.
Below is part of my code for index.php
<?php
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from lectures";
$result = mysqli_query($con, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lec_id = $row['lec_id'];
$lec_name = $row['lec_name'];
$lec_number = $row['lec_number'];
$lec_views = $row['lec_views'];
echo "<button id=linkButton name={$row['lec_name']} value={$row['lec_id']} type='button' class='btn btn-outline-primary lecture' onclick='buttonClicked(this)'>
{$row['lec_name']}
</button> ";
}
} else {
echo "0 results";
}
?>
my button onclick function
function buttonClicked(btn) {
btn.click_counter = (btn.click_counter || 0) + 1;
document.getElementById("num_clicks_feedback").textContent = `btn ${btn.getAttribute('name')} has been clicked ${btn.click_counter} times`;
localStorage.setItem("lecId", btn.getAttribute('value'));
location.href = 'index.php?action=lec_hub/chapters';
}
I want to use the Button value here in chapters.php for a SQL query.
<html>
<head></head>
<body>
<?php
echo "<p id='lecId'></p>";
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from chapters where <<this is where i want to use lecId>> ";
?>
<script>
function getValue(){
var lecId = localStorage.getItem("lecId");
document.getElementById("lecId").innerHTML = lecId;
var resetValue= 0;
localStorage.setItem("lecId", resetValue)
}
getValue()
</script>
</body>
</html>
Welcome to Stack Overflow! As Barmar stated in their comment, you can pass data to a PHP file using URL parameters, or more commonly known as GET parameters. Here's how you do it.
From your file with your button in it, you can create a form like this one:
<form action="chapters.php" method="get">
<input type="text" name="data" /> <!-- This is the value that will be passed -->
<input type="submit" value="Button" /> <!-- This is your button -->
</form>
And then from your PHP file, you can get that passed data like this:
echo $_GET["data"]
$_GET is a global PHP array that contains all of the URL parameters sent to the file. you can pass multiple values as GET parameters to a file. You can read all about the $_GET variable here. I hope this helps!

Passing a PHP variable with fetched data to a JavaScript variable returns NULL or empty

I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.

Jscript/Ajax to return PHP without page reload

Complete novice but making progress. Please assist in getting form data to php and back without a page refresh. I know this should require JQuery / AJAX. I have tried multiple methods (serialize/dataform) but I am stumped. The goal is to fill in a listbox on form.php with headers acquired with PHPExcel from an Excel file PRIOR to being uploaded / tmp (no fopen etc) via lbox.php. All code below works. ** I am not looking to submit the data with the button YET, this should be called when a file has been chosen to be uploaded**
form.php
<html>
<head>
<title>Testing Page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script = "text/javascript">
window.onload = startChecking;
function startChecking()
{
var myVar = setInterval(doFunction, 1000);
}
function doFunction()
{
var nme= document.getElementById("file");
var x=document.getElementById("right");
if(nme.value.length<1){
document.getElementById("right").style.display="none";
return false;
}
document.getElementById("right").style.display="block";
//CODE NEEDED TO LOAD THE LISBOX THAT IS NOW APPEARING
clearInterval(myVar);
}
</script>
</head>
<body>
<form action="lbox.php" method="post" enctype="multipart/form-data" name="creationform" id="frmCreate">
Project Name:
<input type="text" name="YourName" value="Testing">
<br><br>
Choose your file: <br>
<input type="file" name="file" id="file">
<input type="submit" name="Create" value="Create" />
</form>
<div id = "right" style="display:none">
Below should be the data from PHP loaded into the listbox
<BR>
<!-- //This code takes our array of headers and builds them into a listbox -->
<select size="15" name="decision1" multiple>
<?php foreach($myArray as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option> -->
<?php }?>
</select>
</div>
</body>
</html>
lbox.php
<?php
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($_FILES['file']['tmp_name']);
// This code creates our concatenation of column headers
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$val2 = null;
// $highestRow = $worksheet->getHighestDataRow(); // e.g. 10
$highestRow = 1; // e.g. 10
$highestColumn = $worksheet->getHighestDataColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val2 .= $cell->getValue().',';
$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val2);
}
}
}
//The code below gets rid of the extra comma at the end
$val2 = substr($val2,0,strlen($val2)-1);
$val2 .= '';
echo '<br />';
// This code takes our concatenation and turns it into an array with the comma delimiter
$myString = $val2;
$myArray = explode(',',$myString);
print_r($myArray);
echo '<br />';
?>
Thanks, Mark.

how to store results in more than one variable from a PHP that access a database

I'm new to this and I have trouble understanding how all things works.
I have a php/html page and a login form in it. The login submit button executes a php file (let's say check_user.php) in which theoretically it checks the user and password i put in the form in a database. If it finds them I want the php file (check_user.php) to return to the main page the name of the user and his "class" (like supervisor, operator etc) in order to use them for further active change of main page content (like hide/show menus, enable/disbale elements etc). The problem is that the php returns with echo a text as I understand....How can I process this text to be stored in variables (one or more then one) to be usable in the main page? I understand how to pass variables to a php file, but i don't understand how to process the result of the php, except changing the content of an element in the mane page.
Maybe I need a callback function, I need to use JSON....
PS: I want to do this without $_SESSION
my code is here:
main page:
<div id="show2">
<?php
$userErr = $passErr = "";
$user = $pass = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"])) {
$userErr = "User name is required";
}
else {
$user = test_input($_POST["user"]);
if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
$userErr = "Only letters and white space allowed";
}
}
if (empty($_POST["pass"])) {
$passErr = "Password is required";
}
else {
$pass = test_input($_POST["pass"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>LOGIN INFORMATION:</h2>
<form method="post" action="check_user.php">
User: <input type="text" name="user" value="<?php echo $user;?>">
<span class="error">* <?php echo $userErr;?></span>
<br><br>
Password: <input type="password" name="pass" value="<?php echo $pass;?>">
<span class="error">* <?php echo $passErr;?></span>
<br><br>
<input type="submit" name="submit" value="Login">
</form>
</div>
check_user.php:
<?php
if ($_POST["user"] == "xxx" And $_POST["pass"] == "yyyy") {
$name = "John Legend"; /*here I assign value from database*/
$class = "Supervisor"; /*here I assign value from database*/
echo .... ; /*here I don't know what to echo. I want to echo $name and $class and use them as variables (not as text) in the main page*/
}
else {
echo "error";
}
?>
the implementation for database is not done, but the example still apply to any value I assign to the variables I want the php to echo

Categories