Use data retrieved from MySQL in JavaScript? - php

I am selecting some data from my database and I can echo it with PHP in my document. How can I straight pass it to JavaScript, or it its not duable, how do people deal with these things?
Here is how I get and echo:
$q=mysql_real_escape_string($_GET['q']);
$query="SELECT * FROM contacts WHERE id = '".$q."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo "Name: " . $row['first'] . " <br />";
echo "Surname: " . $row['last'] . " <br />";
}
mysql_close();

This is a quick and simple way to get this setup.
echo("<script>");
echo("var myJSvar = " . json_encode($row) . ";");
echo("</script>");
Then in any JS from there you can use myJSvar;
alert(myJSvar['first'] + " " + myJSvar['last']);

<div id="name">
<?php echo $name; ?>
</div>
<script type="text/javascript">
//jquery example
$(document).ready(function(){
alert($('#name').text());
});
</script>

$x is a string (or anything else really, just make sure the types are compatible before passing them)
$x = phpvar
echo "<script type='text/javascript'>
function Javascript_function(){
var passed = ".$x."}</script>";
That should do it. Don't forget the script <> tags, SO wouldn't let me insert them probably to prevent me just throwing javascript on every page.

Related

Passing a value through URL

Here is what i want to achieve ; sending ID's through URL's and printing it.
index.html
ID 1
ID 2
receive.php
<?php
$id_q = $_GET['id'];
print "The parameters passed through URL are $id_q";
?>
This above code works perfectly, I'm not able to do this with a list of ID's printed with a php command.
The below code is used to print all the PID's in the DB.How do i make every PID printed clickable ?
When I add html tags inside PHP code it throws up an error.
print.php
$result = mysqli_query($con,"SELECT * FROM List");
while($row = mysqli_fetch_array($result))
{
echo $row['PID'];
}
edit-query.php
$pid_q=$_GET[pid];
echo $pid_q;
while($row = mysqli_fetch_array($result))
{
echo "<a href='receive.php?id=".$row['PID']."'>".$row['PID']."</a>";
}
If you want to add your own text to a variable or echo, quote it and separate the variable with a "."
echo ''.$row['PID'].'';
you should do that like this
How about...
echo '' . $row['PID'] . '';
I believe this is what you mean?
while($row = mysqli_fetch_array($result))
{
echo 'Print ID: ' . $row['PID'] . '';
}
while($row = mysqli_fetch_array($result))
{
echo "<p id=".$row['PID']." class='clickable'>" . $row['PID'] . "</p>";
}
$(document).ready(function(){
$("#clickable").click(function(){
$(this)...something...
});
});
This is a little something you can do using JQuery if you wanted each PID to do something other than refer to another location. It will listen on any with the clickable class.

How to loop the $row = mysql_fetch_array($rs);

I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php

Having trouble getting id from while loop to query

I have a bunch of items I list on a page and each of these items have an id associated with them on there link.
For instance, when you hover over the items you get a url of items.php?id=5.
I have my while loop which produces all of the items on this page including the links, how do I carryover that ID into my other code?
Here is my code that brings up all the items.
while ($results = mysqli_fetch_assoc($query)) {
echo
"<li>
<img style='width: 200px; height: 200px' src='images/inventory/" . $results['Image'] . "'/>" .
"<div class='infoContainer'>" .
"<a class='productLink' href='selectItems.php?status=active&id=" . $results['ID'] . "'>" . $results['ProductName'] . "</a>" .
"<br />" .
"<i>Currently Available </i>" .
"<i class='quantity'>" . $results['Quantity'] . "</i>" .
"</div>" .
"</li>";
}
Now I simply want to put each items attributes into a dialog box. How do I carryover an id from above to get the right data back?
<div id="dialog" title="A title">
<?php
$sql = "SELECT * FROM `my_table` WHERE `id` = ";
$query = mysqli_query($sql) or die(mysqli_error());
var_dump($sql);
$results = mysqli_fetch_assoc($query);
var_dump($results);
?>
</div>
You should call a javascript function and send id in it..
donot forget to include the jquery files..
this method loads the data using AJAX..
<script>
function getData(idtosend){
$.post('getdata.php', id: idtosend, function (response){
$("#dialog").html(response);
});
}
</script>
Here is the code of getdata.php file:
<?php
//Connect mysql here
$id = mysql_real_escape_string($_POST['id']);
$sql = "SELECT * FROM `my_table` WHERE `id` = $id";
$query = mysqli_query($sql) or die(mysqli_error());
var_dump($sql);
$results = mysqli_fetch_assoc($query);
var_dump($results);
?>
in PHP you cat use ob_start() - this is output buffer for echo operations.
after save result in variable or array and put it into needful block on page

Transferring DB data between PHP and Javascript 2D array

I am attempting to get all the data from a MySQL db with PHP, initialise a 2D java array and populate it with the PHP data.
I am having trouble embedding JS in the PHP. I have marked up what is working and what isn't.
As you will see, some of the embedded java works but not all.
Any thoughts?
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
string [][] hhgdata = new string[numrows][4]; // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter + "<br/><br/>"); //THIS WORKS
hhgtitle = <?php echo $hhgtitle; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write(hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?
$counter++; // THIS WORKS
}
?>
</body>
You are mixing up Java and JavaScript. For example this is Java syntax, you can't write this within a script tag which should only contain JavaScript:
string [][] hhgdata = new string[numrows][4];
The JavaScript arrays are dynamic, this should be enough:
var hhgdata = [];
When you want to add another array into it, as you seem to be doing later in your code, just do this:
hhgdata[counter] = [];
And then assign to the inner array:
hhgdata[counter][1] = hhgtitle;
You are also creating multiple assigning an unquoted string literal to variable with this (assuming $hhgtitle contains a string):
hhgtitle = <?php echo $hhgtitle; ?>;
It should be something like this:
hhgtitle = <?php echo '"' . $hhgtitle .'"'; ?>;
Finally, while it's not incorrect, your PHP while loop is creating multiple script elements in your HTML.
EDIT
I have made the changes described above as well as in comments, copy-paste exactly and see how it goes:
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
var hhgdata = new Array(numrows); // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?php
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
var counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter); //THIS WORKS
hhgtitle = <?php echo '"' . $hhgtitle . '"'; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter] = [];
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write("<br />hhgdata[counter][1]: " + hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?php
$counter++; // THIS WORKS
}
?>
</body>
Why not just take the PHP array of data and json_encode it? Then you can work with it in Javascript, see below:
var json = <?php echo json_encode($foo); ?>;
You can learn more about how to do this here: http://www.openjs.com/scripts/data/json_encode.php

How do I put id number from select tag to a php link?

Currently, this is what I have so far, but it's not working:
<form>
<select name="patientID" id="patientSelect">
<?php
$qPatient = mysql_query("SELECT idpatients, firstName, mi, lastName, suffix FROM patients ORDER BY lastName ASC");
while($rowPatient = mysql_fetch_array( $qPatient )) {
if(isset($rowPatient['suffix']) && !empty($rowPatient['suffix'])){$suffix = " " . $rowPatient['suffix'];}else{$suffix = NULL;}
if(isset($rowPatient['mi']) && !empty($rowPatient['mi'])){$mi = " " . $rowPatient['mi'] . ".";}else{$mi = NULL;}
echo "<option value=" . $rowPatient['idpatients'] . $rowPatient . ">" . $rowPatient['lastName'] . $suffix . ", " . $rowPatient['firstName'] . $mi . "</option>";
}
?>
</select>
<a id="updatelink" href="">....</a>
<a id="deletelink" href="">....</a>
<script type="text/javascript">
$(document).ready(function(){
$("#patientSelect").change(function(){
$("#updatelink").attr('href',"update.php?id="+$("#patientSelect").val());
$("#deletelink").attr('href',"delete.php?id="+$("#patientSelect").val());
});
});
</script>
</form>
You code works. See it here: http://jsfiddle.net/Paulpro/Euyzp/
Changing the dropdown's value changes the href of the links. Are you wanting to change the links text as well?
Also just a side note, you shouldn't be wrapping that code in a $(document).ready(), because you want that script to execute as soon as the <select> is added to the DOM.
You see, it's working: http://jsfiddle.net/Deele/A35B8/

Categories