Trying to send two values from php to JS - javascript

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>

Related

Passing value to other page by clicking a list item

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.

PHP Escaping double Quote on echo with onclick

Please notice the addslashes($model->subject) part in the code below. If the subject contains single quote, it works fine but if it has double quote, javascript generates error and treats that the onclick method ends on the double quote character. How to solve that error?
$string.=" <a href='#' class='' data-toggle='modal' "
. "onclick=\"to_edit('" . $model->id . "','" . $model->doc_type_level_1 . "','" . $model->doc_type_level_2 . "','" . $model->doc_type_level_3 . "','" . addslashes($model->subject) . "','" . $model->date . "',"
. "'" . $model->date_release . "','" . $model->is_confidential . "'"
. ")\" "
. "data-target='#modal_doc' ><span class='fa fa-pencil'></span></a>";
You should use htmlspecialchars to convert these entities, use following code:
htmlspecialchars($model->subject, ENT_QUOTES);

Assign id within a php echoed statement

in the below php statement I want to assign ID to EmployeeName.I will use the ID tag to search an element in the echoed list by name.Where am I making the mistake ?
<?php while( $toprow4 = sqlsrv_fetch_array( $stmt4) ) {
echo "<div class='parent-div'><span class='rank'>" . $toprow4['rank'] . "</span><span class='name'>" id = ' . $toprow4['EmployeeName'] .' "</span><span class='points'>" . $toprow4['pointsRewarded'] . "</span></div>";
} ?>
Add the id to the div element as an attribute and not as textContent
echo "<div class='parent-div' id='" . $toprow4['EmployeeName'] . "'><span class='rank'>" . $toprow4['rank'] . "</span><span class='name'>" . $toprow4['EmployeeName'] . "</span><span class='points'>" . $toprow4['pointsRewarded'] . "</span></div>";
and try and make that name a valid ID by removing spaces or replace them by -.
You need to check your quotes. If you aren't already, I'd strongly recommend using an editor with code highlighting.
<?php
while ($toprow4 = sqlsrv_fetch_array( $stmt4)) {
$rank = $toprow4['rank'];
$id = $toprow4['EmployeeName'];
$points = $toprow4['pointsRewarded'];
echo "<div class='parent-div'><span class='rank'>$rank</span>";
echo "<span class='name' id='$id'></span><span class='points'>$points<span></div>";
}
?>
Seems like you have a big problem escaping your output string correctly. Perhaps you should to try write it clean by using templates and sprintf() like in this sample.
i did not test the logic of the while statement you have given
<?php
$template = '<div class="parent-div">';
$template .= '<span class="rank">%s</span>';
$template .= '<span class="name">id = %s</span>';
$template .= '<span class="points">%s</span>';
$template .= '</div>';
while($toprow = sqlsrv_fetch_array($stmt4) {
echo sprintf(
$template,
$toprow['rank'],
$toprow['EmployeeName'],
$toprow['pointsRewarded']
)
}
?>
Your code is not clean, so you failed on making correct quotes and single-quotes.

JS sequential calling of function fails

I need to exicute one JS function after another sequencually. I can exicute these functions individually and they work but when I put them in a sequence I only get the openPatient() and the openMessage() does not exicute. My JS functions
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
My function call:
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
This function call exists in this process:
<?php
// Generate a table row for each pending portal request or message.
// This logic merges requests with messages by date.
$v1 = each($result['list']);
$v2 = each($result['messages']);
while ($v1 || $v2) {
echo " <tr class='detail' bgcolor='#ddddff'>\n";
if (!$v2 || $v1 && $v1[1]['datetime'] < $v2[1]['datetime']) {
$postid = $v1[1]['postid'];
$ptname = patientNameFromLogin($v1[1]['user']);
// Get the portal request data.
if (!$postid) die(xlt('Request ID is missing!'));
$result2 = cms_portal_call(array('action' => 'getpost', 'postid' => $postid));
if ($result2['errmsg']) {
die(text($result2['errmsg']));
}
// Look up the patient in OpenEMR.
$ptid = lookup_openemr_patient($result2['post']['user']);
echo " <td>" . text($v1[1]['user']) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;' onclick=\"openPatient()\">" .text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
echo " <td>" . text($v1[1]['type' ]) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_req_cb[" .
attr($postid) . "]' value='" . attr($postid) . "' /></td>\n";
$v1 = each($result['list']);
}
else {
$messageid = $v2[1]['messageid'];
$ptname = patientNameFromLogin($v2[1]['user']);
echo " <td>" . text($v2[1]['user']) . "</td>\n";
echo " <td>" . text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openMessage(" .
"'" . addslashes($messageid) . "'" .
")\">" . text($v2[1]['datetime']) . "</td>\n";
echo " <td>" . text($v2[1]['user'] == $v2[1]['fromuser'] ?
xl('Message from patient') : xl('Message to patient')) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_msg_cb[" .
attr($messageid) . "]' value='" . attr($messageid) . "' /></td>\n";
$v2 = each($result['messages']);
}
echo " </tr>\n";
}
?>
I am thinking part of the problem may be that openPatient() opens in another window. Perhaps it is loosing focus. Any tips to fix this would be appreciated.
EDIT:
What I have tried and helps is adding return this; to openPatient():
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
This then executes the next function but the next function executes too soon. it needs to wait for openPatient() to fully load before executing openMessage(). I have tried adding setTimeout( wait, 1000 ); but then openMessage() does not execute at all.
The solution:
The call:
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient();setTimeout(function(){openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
")}, 2500);\">" . text($v1[1]['datetime']) . "</td>\n";
The functions:
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
Keys to success: return this; and the use of the anonymous function with setTimeout in the call.
Posts that helped:
What does "return this" do within a javascript function?
setTimeout delay not working

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.

Categories