I am currently reading through a piece of code provided by my faculty and I am having troubles understanding how it works.
Specifically how the anchor is linked to the php without method="post" or method="get".
Kindly appreciate if anyone could explain or link me to relevant materials to do further readings. Much thanks.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Cart for bought items indexes is created in session if it's not there yet.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
When link with buy query parameter is opened, buy value is added to session cart. After that page is redirected to location without buy parameter.
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
List of items to buy is printed on page (i quess code in question is not full).
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Links open pages with GET method.
Link query parameters can be accessed by special $_GET variable
Related
I'm trying to learn php with html and I decided to create a project.
Right now, I'm stuck at this point where I want to display data on a textarea.
I created a database named 'company' with the table 'login' and the columns 'id','password' and 'username'.
When I select an option in the select option menu, the data from the column 'id','password' and 'username' is displayed in a table. What I want to achieve is when I click on a row, that the data from the column "problem" is displayed on the textarea which describes the situation with explanation.
I don't know how to write this but the syntax should be something like: Select 'problem' from login WHERE id='selected row id' I created on my php a select case witch works fine. The only problem that I have is I don't know how to select the id when I click on a specific row to display the data on the textarea.
Here's my code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Formulaire</title>
<link rel="stylesheet" type="text/css" href="formulaire.css"/>
<!--<script type="text/javascript" src="select1.js"></script>-->
<!--<script src="http://code.jquery.com/jquery-latest.js"></script>-->
<style>
table tr:not(:first-child){
cursor: pointer;transition: all .25s ease-in-out;
}
table tr:not(:first-child):hover{background-color: #ddd;}
</style>
</head>
<body>
<div id="form">
<form action="#" method="post">
<label>Veuillez choisir une option :</label>
<select id="choix" name="choixtest">
<option value="tous">tous</option>
<option value="id">id</option>
<option value="username">username</option>
<option value="password">password</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
<table id="table">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "company");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM login";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>username</th>";
echo "<th>password</th>";
echo "</tr>";
if(isset($_POST['submit'])){
$selected_val = $_POST['choixtest']; // Storing Selected Value In Variable
while($row = mysqli_fetch_array($result)){
switch($_POST['choixtest']){
case 'tous':
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
break;
case 'id':
echo "<tr>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'username':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'password':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "</tr>";
break;
default:
// Something went wrong or form has been tampered.
}
}
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</table>
<textarea id="erreur" rows="20" cols="100"></textarea>
</form>
</div>
</body>
</html>
For a table with <table id="myTable">to get the first column value into a textbox which is defined as
<input type="text" placeholder="Customer Name" id="cus_name">
You can add the following js code.
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
document.getElementById("cus_name").value = this.cells[0].innerHTML;
};
}
</script>
Here the cus_name is the id of the text field while in the this.cells[0], the value 0 represents the first column. You can change it accordingly and also can add more columns with the code document.getElementById("cus_name").value = this.cells[0].innerHTML; by only changing the cell value and the textbox id.
Every row in your html table must correspond to an id in the login table.
you have to place somewhere in the row the id corresponding to that row. You can achieve this in many ways.
one way to do it is using a data-something attribute to put the id, for instance
<tr data-id="<?php echo $current_row['id']; ?>">
<td>column1</td>
<td>column2</td>
<td>etcetera</td>
</tr>
Once you have the data-id atttribute set you can access it via Javascript everytime a user clicks on the row. For this you need to capture the click event on the row. I'll show you an example using jQuery:
$('.myTable tr').click(function(){
let id = $('this').data('id');
console.log('id of selected row: ' + id);
});
Now the 'id' variable contains the id of the row the user selected (check console output to make sure the id is the one you expect). The next step would be to use that id to make a request to the server, via Ajax or via regular http request. If this works successfully i suggest you to research, or make another post to find out how to reload the page with the content with the data you want. Since the more specific a question is the higher is the chance that it will be answered
I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});
I have many links which are dynamically created with PHP and now I want to add an onclick event.
while($row = mysqli_fetch_array($xyz)) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . "</a></td>";
echo "</tr>";}
but I want like this:
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . onclick="test()"</a></td>";
echo "</tr>";}
is this possible?
I am not sure if I understood what exactly you are asking but I try to answer you the same:
You can't record a normal JS variable in a page session and then to access to it after the loading of a page.
For this case you can use cookies (that are accessible via server-side too):
// put this code into methods that users suggested you.
document.cookie = "value_selected=something"
and once page is loaded:
var cookies = document.cookie.split(';');
var value_selected = JSON.parse(JSON.stringify(cookies[YOUR_COOKIE].split("=")[0]))
or server side:
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" data-something=htmlentities($_COOKIE['value_selected']) target=\_blank>" . $row['z'] . "</a></td>"; //(example)
Or more simply, pass the value selected through query
?value_selected=something //elaborate the new link in the method users suggested you
and
in server-side, use $['GET'] to obtain all values in query string.
IMHO I think the first choice is simpler than second.
I hope I helped you
Try Like this
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a class='myclick' href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . **onclick="test()"**</a></td>";
echo "</tr>";}
i have added a class to link as myclick
and in jquery
$(document).on('click','.myclick',function(e){
e.preventDefault();
alert('clicked');
});
You can try like this..just a simple way.
<script type="text/javascript">
function test(){
alert('test');
}
</script>
<?php
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href='your link' onclick='test()'></a></td>";
echo "</tr>";
}
?>
I am new to jQuery and JSON. I have the following PHP code (getData.php) performs query from the database:
<?php
header('Content-Type: application/json');
....
// some code here
....
$my_arr=array();
// fectching data into array
while($info = mysqli_fetch_array($result))
{
// convert to integer value if there is a bug after passing json_encode
$rev=intval($info['bIRevNum']);
$name=$info['bIName'];
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
$my_arr[]=array('br'=>$name,'rev'=>$rev);
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
}
// json encode
echo json_encode($my_arr);
?>
After use echo 'json_encode' here I can see the JSON object under this format
[{"br":"itemsb1","rev":37},{"br":"itemb2","rev":45}] on my page.
Now I want to access the integer of rev element of the object (37 and 45) for future usage by jQuery in a different PHP file, lets call it index.php and with the below script
<html>
.....
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value){
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
});
</script>
...
// test here
<!---jquery--->
<div id="div1"><h2>CHANGE >>>> ....!!!!</h2></div>
<button>Calling from different PHP file</button>
</html>
If it is correct, when I click on the button "Calling from different PHP file" it should appears the value of JSON object as 37, 45.
I have tried many ways, but it does not display anything on my page.
Please help me with this!
It appears your problem is that you are echo'ing the html as well as the JSON. try removing the 'echo' from these lines
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
DO NOT delete this line:
$my_arr[]=array('br'=>$name,'rev'=>$rev);
Also make sure your javascript is syntax correct
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value) {
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
Ensure that the only content coming back from getData.php is JSON-formatted; otherwise, it won't be parsed correctly. If you visit getData.php in your browser directly, you should only see JSON content, and nothing else (including errors, warnings, etc.). Your jQuery looks good; so the issue would have to be whatever content is coming back from the PHP script. I just whipped up a trivial test case using this PHP:
<?php
header('Content-type: application/json');
$my_arr[]=array('br'=>'something','rev'=>'2.0.5');
echo json_encode($my_arr);
?>
Using the exact HTML you provided, that works just as expected.
I'm working on a offine web application. But on a certain point it need to receive data from a sql database. This is done with an iframe. However the PHP files print all the data available. Every row of data has a workID, and i want them to be clickable. When you click on the work ID i need to save the work ID as variable so i can use the work ID through my whole application.
For example: I choose 1 work ID. Onclick the work ID is written in my header on every page.
I don't know if this can be done with cookies or just a javascript function on the main page.
See the following code:
<?php
$result=mysql_query("SELECT workid,problem,request FROM workreport ORDER BY workid;");
$i=0;
while( $row=mysql_fetch_array($result) )
{
if($i>0)
{
echo "<tr valign=bottom>";
echo "</tr>";
}
echo "<tr valign=center>";
echo "<td class=tabval></td>";
echo "<td class=tabval><b>".htmlspecialchars($row['workid'])."</b></button></td>";
echo "<td class=tabval>".htmlspecialchars($row['problem'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['request'])." </td>";
$i++;
}?>
PHP is loaded in an iframe. So i prefer to create the function to save the work id on my main page.
<iframe src="http://localhost/receive.php" width="400" height="300" style="border:none;"> </iframe>
Hope you can help me! thanks in advance.
You can do it like this, using javascript and PHP:
PHP:
while( $row=mysql_fetch_array($result) )
{
if($i>0)
{
echo "<tr valign=bottom>";
echo "</tr>";
}
echo "<tr valign=center>";
echo "<td class=tabval></td>";
echo "<td class=tabval><button id=\"saveid\"><b>".htmlspecialchars($row['workid'])."</b></button></td>";
echo "<td class=tabval>".htmlspecialchars($row['problem'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['request'])." </td>";
$i++;
}
Javascript
window.onload = function () {
document.getElementById('saveid').onclick = function () {
var id = this.innerHTML;
document.cookie = "saveid=" + id + ", expires=Monday, 04-Apr-2020 05:00:00 GMT";
alert('Cookie saved!');
}
}
Okay, the cookie is now saved. You can access it in PHP using $_COOKIE['saveid'].