Passing value to other page by clicking a list item - javascript

I am new at web programming and JavaScript.
I have a model page that show all the details of a request let 's say. And Before that page, what the user sees is a list with all the requests he have made. The this is, I want somehow to passe the ID of that clicked request, save it somewhere and pass to the other page and in there, by ID e shows all the details of that previously clicked request.
Here is my code:
<div class="list-group">
<?php
$id_utilizador = $_SESSION["id_utilizador"];
if(isset($_POST["por_aprovar"])){
$url = "http://localhost/myslim_aluguer_viaturas/api/requisicoes/fase1/" . $id_utilizador;
$json = file_get_contents($url);
$obj = json_decode($json);
if($obj->status == true){
$array = $obj->data;
foreach($array as $requisicao){
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
}
} else {
echo "Não existem resultados a apresentar.";
}
?>
I don 't know what to do. thank you for your time!!!

What you are looking for is a url query string aka get parameters. In your code change this:
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
To this:
echo "<a href='requisicao.php?theid=" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
And on requisicao.php you will obtain the value using php's super global variable $_GET[] which will be something like this:
if(isset($_GET['theid']) && $_GET['theid'] != ''){
$the_id = $_GET['theid'];
// do stuff with $the_id;
}
You can pass multiple values by adding additional parameters:
requisicao.php?theid=22&anothervar=something&var3=33
Also keep in mind the security implications when passing variables via query string parameters as users will be able to easily manipulate these variables, and they will be saved in access logs. Your application should have the logic to sanitize and insure that the values passed are valid.

Related

Trying to send two values from php to JS

Im retrieving a value from my db, displays on screen as a 0.
echo "<article>" . $gr_display['status'] . "</article>";
Then when im clicking on this DIV i want to send both status and id to my JS function, edit. The ID of this object is 79
echo "<div onclick='edit( " . $gr_display['status'] . "." . $gr_display['id'] . " )' </div>";
Then the start of my script
function edit(status, id) {
console.log(status, id ); some code later }
But im ending up with the result that id and status is combined into one sett of value, leaving the other one "undefined"
From console log: 0.79 undefined
Please make a clarity between PHP and JavaScript. You need to use the right separator and separate.
echo "<div onclick='edit( " . $gr_display['status'] . ", " . $gr_display['id'] . " )'> </div>";
//-----------------------------------------------------^
Replace . with ,. Also please use > for the opening <div>. You forgot to close your opening div.
you have at typo change the . into, between the 2 variables
echo "<div onclick='edit( " . $gr_display['status'] . "," . $gr_display['id'] . " )'> </div>";
//---------------------------------------------------------^
or better use data-attributes
echo "<div class='edit-element' data-status='" . $gr_display['status'] . "' data-id='" . $gr_display['id'] . "'></div>";
$('.edit-element').click(function(){
console.log($(this).attr('data-status'),$(this).attr('data-id'));
});
replace div with this:-
echo "<div onclick='edit( " . $gr_display['status'] . "," . $gr_display['id'] . " )' </div>";
The problem is causes by this line:
echo "<div onclick='edit( " . $gr_display['status'] . "." . $gr_display['id'] . " )' </div>";
Notice that between the two arguments you put a '.' instead of a ',' (a comma). That way, the second argument in your JS function does not have a value
Your code has two issues
You haven't close opening div tag
Use , to separate two parameters
echo "<div onclick='edit( " . $gr_display['status'] . ", " . $gr_display['id'] . ")'>ddd </div>";
<script type="text/javascript">
function edit(status, id) {
alert(status);
alert(id);
}
</script>

Javascript: function doScan(code) links to php file for searching to mysql

I'm a newbie on php, javascript and ajax. I got this tutorial about How to Create a Search Feature with PHP and MySQL and it was a success after creating it.
Link: http://www.webreference.com/programming/php/search/index.html
Now I'm changing the index.html file and linked only to search_display.php file for just a simple price checker program. I was confuse on how to link the "code" result under Javascript function doScan(code) to search_display.php.
<script>
function doScan(code) //displays the value target after scanning.
{
divStatus.innerHTML = 'Scanned Code:<br> ' + code;
setTimeout("startScanner()", 1250);
}
</script>
I wanted to link "code" to search_display.php and this is the code:
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
//if(preg_match("/^[a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect("localhost", "root", "bbp0m") or die ('I cannot connect to the database because: ' . mysql_error());
//var_dump($db);
//-select the database to use
$mydb=mysql_select_db("price_checker");
//var_dump($mydb);
//-query the database table
$sql="SELECT * FROM stock_master WHERE gtin LIKE '%" . #$name . "%'";
//var_dump($sql);
//-run the query against the mysql query function
$result=mysql_query($sql);
//var_dump($result);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$itemcode=$row['itemcode'];
$desc1=$row['desc1'];
$desc2=$row['desc2'];
$uom=$row['uom'];
$gtin=$row['gtin'];
$retailprice=$row['retailprice'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$itemcode . " " . $desc1 . " " . $desc2 . " " . $uom . " " . $gtin . " " . $retailprice . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
//}
?>
Any ideas how to link it and if possible I would like to put everything into index.html?
Bert

How to pass a MySQL data from PHP to Javascript through a function

I'm making a program that shows several descriptions taken from a database (MySQL):
echo "<input type=\"submit\" id=\"Boton" . $i . "\" value=\"Mostrar Descripcion\""
. " onclick=cambiarBoton(" . $i . ", \"" . $row["descripcion"] . "\") />";
echo "<div class=\"entrada-descripcion\" id=\"Descripcion" . $i . "\"> </div>";
where $row["descripcion"] is the access to the description and $i is an identifier because i'm using loops. That code generates a button that i must press to show the description. The javascript function "cambiarBoton" is the one that do that changes:
function cambiarBoton(i, d){
if (document.getElementById("Boton"+i).value == "Mostrar Descripcion"){
document.getElementById("Boton"+i).value = "Ocultar Descripcion";
document.getElementById("Descripcion"+i).innerHTML = d;
}else if(document.getElementById("Boton"+i).value == "Ocultar Descripcion"){
document.getElementById("Boton"+i).value = "Mostrar Descripcion";
document.getElementById("Descripcion"+i).innerHTML = "";
}
}
Ok, but there is a problem in the program and this is that i can't pass the description to the function in javascript and this doesn't works. How can i do this?
(I must do this without using AJAX)
I answer to the question I think you're asking is:
<?php echo "<script>var data = ".$row["description"].";</script>"; ?>
The problem was in the call of the function "cambiarBoton" in the code PHP,
it should have been this:
echo "<input type=\"submit\" id=\"Boton" . $i . "\" value=\"Mostrar Descripcion\""
. " onclick=\"cambiarBoton(" . $i . ", '" . $row["descripcion"] . "')\" />";
And then it works.

JavaScript/PHP/MySQL not inserting into database

On my website, I have a JavaScript function that saves data into a MySQL database. It works by sending the data to a PHP file, which processes it, and then inserts it into the database.
I was fiddling around with it, and it no longer inserts new information into the database. It still works fine when updating existing information in the database, but when I try to add new information in, nothing happens, The information is not there, and no error is displayed.
Here is my PHP code: (Obviously, I have already connected and selected the database)
$query = mysql_query( "insert into parts values( 0, " . mysql_escape_string( $objectID ) . ", " . $objectStackID . ", " . $objectCardID . ", '" .
mysql_escape_string( $objectProperties['name'] ) . "', '" .
mysql_escape_string( $objectProperties['partorder'] ) . "', '" .
mysql_escape_string( $objectProperties['top'] ) . "', '" .
mysql_escape_string( $objectProperties['left'] ) . "', '" .
mysql_escape_string( $objectProperties['width'] ) . "', '" .
mysql_escape_string( $objectProperties['height'] ) . "', '" .
mysql_escape_string( $objectProperties['stype'] ) . "', '" .
mysql_escape_string( $objectProperties['value'] ) . "', '" .
mysql_escape_string( $objectProperties['script'] ) . "', '" .
mysql_escape_string( $objectProperties['visible'] ) . "', '" .
mysql_escape_string( $objectProperties['disabled'] ) . "', '" .
mysql_escape_string( $objectProperties['style'] ) . "', '" .
mysql_escape_string( $objectProperties['family'] ) . "' )" );
if( ! $query )
{
logThis('Could not enter data: ' . mysql_error());
}
else
{
logThis("inputted sucessfully - here come the objectprops");
logThis("Button properties:");
logThis("Name: " . $objectProperties['name']);
logThis("Part order: " . $objectProperties['partorder']);
logThis("Top: " . $objectProperties['top']);
logThis("left: " . $objectProperties['left']);
logThis("width: " . $objectProperties['width']);
logThis("height: " . $objectProperties['height']);
logThis("stype: " . $objectProperties['stype']);
logThis("value: " . $objectProperties['value']);
logThis("script: " . $objectProperties['script']);
logThis("visible: " . $objectProperties['visible']);
logThis("disabled: " . $objectProperties['disabled']);
logThis("style: " . $objectProperties['style']);
logThis("family: " . $objectProperties['family']);
}
The logThis function writes the contents to a txt file, which is useful for debuging. In the txt file, I receive the message "inputted successfully - here come the objectprops" followed by the values (that should have been) inserted into the database. However, when I look at the database, nothing has been added.
This code did work fine at one point, however, I have been editing it on and off for about 6 months now, only testing to see if it will update information, not create now info (really stupid!), so I have no idea when it was last working, and what I changed to make it stop.
I think that my JavaScript is OK, as PHP receives the correct values (as can be seen from the log), but just does not actually insert them into the database.
Can anyone see what I have done wrong? Nay help at all would be greatly appreciated. I have been staring at this code for a long time now!
Thanks in advance.
EDIT - here is the javascript code, basically it cycls through an array, getting properties of buttons and then sends them to the save php file. Seems to work OK, but there might be a hidden error causing the issue

Change src of element loaded with AJAX

I'm trying to alter the src of imgs loaded via. AJAX, wherein the <select> and <option> elements used to control the function are also loaded by AJAX.
I'm trying to do this in order to change the size of Flickr images on the page.
I've tried loading the element, and calling an existing function to update it, but of course the <select> option doesn't exist on document.ready() and thus returns null when I try to get it.
I've also tried loading a new <script type='text/javascript'></script> in the PHP file I'm using for my XML response, but although this shows on the page it obviously isn't picked up as a source.
How can I tell the Document to 're-ready' itself, or acknowledge new sources?
Here's my code as it stands:
Making the request
function makeRequest (url, userID, searchString, selectedLicense) {
event.preventDefault();
var formData = new FormData();
formData.append("userID", userID);
formData.append("searchString", searchString);
formData.append("selectedLicense", selectedLicense);
var xmlRequest = new XMLHttpRequest();
xmlRequest.open("POST", url, true);
xmlRequest.send(formData);
xmlRequest.onreadystatechange=function()
{
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
document.getElementById("results").innerHTML=xmlRequest.responseText;
} else {
document.getElementById("results").innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
}
}
The PHP
//more code before
$resultString = $resultString . "<script type='text/javascript'>"
. "function sizeChanged(i, select) {
var sel = getSelectedOptionValue(select);
var imgURL = document.getElementById(i.toString());
alert(imgURL);
}"
. "</script>";
//main loop
foreach ($XML->photos->photo as $photo):
$resultString = $resultString . '<div class="photoBox"' . photoBox($photoCounter) . "> <p>" . $photoCounter . ". " . $photo['title'] . "" . "</p>"
. " <p>" . "<img id='" . $photoCounter . "' src=\"http://farm" . $photo['farm'] . $imgURL . "/" . $photo['server'] . "/" . $photo['id'] . "_" . $photo['secret'] . "_" . $size . "\" alt=\"" . $photo['title'] . "\">" . "</p>"
. "<select form='addInformationForm' id='selectSize" . $photoCounter . "' onChange='return sizeChanged(" . $photoCounter . ", selectSize" . $photoCounter . ");'>"
. "<option value='n'>Small (320)</option>"
. "<option value='z' selected='selected'>Medium (640)</option>"
. "<option value='h'>Large (1600)</option>"
. "</select>"
. "</div>";
$photoCounter++;
endforeach;
//more code here
echo $resultString;
The HTML Output (Example)
<div class="photoBox" style="background-color:#FFFFFF">
<p>1. Killip's Adirondack Travelog, page 20</p>
<p><img id="1" src="http://farm9.staticflickr.com//8184/8427833074_2f7e22e7ce_z.jpg" alt="Killip's Adirondack Travelog, page 20"></p>
<select form="addInformationForm" id="selectSize1" onChange="return sizeChanged(1, selectSize1);">
<option value="n">Small (320)</option>
<option value="z" selected="selected">Medium (640)</option>
<option value="h">Large (1600)</option></select>
</div>
Any advice much appreciated!
NOTE: This code is for an internal tool, not a client-facing website.
The <select> doesn't exists at onload, but it does when you create it:
var res = document.getElementById("results");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
res.innerHTML = xmlRequest.responseText;
var select = res.getElementsByTagName('select')[0];
/* Use select here */
} else {
res.innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
};
Note that the <img> element should be available too, but you won't know its dimensions because it won't be downloaded. If you want to wait until it's loaded, you can add a load event listener.

Categories