i am calling a javascript for image gallery and php on a single page.
let me show you some code to make things clear:
PHP
echo "<form method = post action = 'user_submit.php'>";
// get possible answers using question ID
$query = "SELECT aid, atitle FROM answers WHERE qid = '$qid' ORDER BY aid ASC";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_object($result)) {
echo "<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>";
echo "<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th".$row->aid.".jpg' /> </a>";
echo "<input type = hidden name = aid id = rd".$row->aid." value = ".$row->aid.">".$row->atitle."</input>";
echo "</div>";
}
echo "<input type = hidden name = qid value = '".$qid."'>";
echo "<br/>";
echo "<input type = submit name = submit value = 'Vote!'>";
}
echo '</form>';
}
the above code fetches object ids and places jpeg images accordingly (thumbnails).
now when i click on these thumbnails the javascript opens an overlay to display the large version. i want to pass the value of $row->aid to javascript.
then from the javascript i want to fill out a form and pass the $row->aid and the form to user_submit.php to add it to the DB.
i am new to php. please help me out.
You can write a variable, object or array literal declaration to your javascipt file or to a <script> element in a HTML file, as kiamlaluno correctly said. but i would suggest, (1) use the var keyword and (2) consider using a separate namespace.
If you have several things to tell the JS, it's handy to put them in a PHP hash and json_encode() and then write the encoded string to your output. This takes care of the namespace and correct escaping of the data. For example:
<?php
$jsdata = array(
'this' => "It\"s gone.\nWhat?",
'that' => array(1,3,2),
'another' => 0x2f );
$jsdata = json_encode($jsdata);
?>
<html>
<head></head>
<body>
<script type="text/javascript">
var thedata = <?php echo "$jsdata;" ?>
window.console.log(thedata);
</script>
</body>
</html>
Try that and look at the javascript console to see if it works.
EDIT: Another reason I like this approach is because you can use PHP's array handling conveniences to construct an arbitrarily complex $jsdata while not worrying about escaping issues and only consuming one global JS object name.
First of all, you don't need to echo everything. Something like this is just as valid:
while ($row = mysql_fetch_object($result)) { ?>
<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>
<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th<?=$row->aid?>jpg' /> </a>
<?php ...
In this case, uses php's echo shortcut tag to echo the value of the contents. It is equivalent to <?php echo $some_variable ?> .
Second, I don't actually see any JavaScript code in your question. But to accomplish what it sounds like you want to do, you can make an HTML form with a SINGLE hidden input whose value is set by selecting one of your images, and then have that form submit to user_submit.php.
The value-setting can happen in a number of ways, which is really up to you. But suppose you wanted it to happen when the user clicked an image. Then you could set the onClick event inside the img tag, like onclick="hidden_input.value='<?=$row->aid?>'"
There are many ways to pass data to JavaScript; the easier is the following:
<script>
aid = <?php print $row->aid; ?>
// The rest of the script
</script>
I only wrote the necessary code, without even write all the attributes for the tag SCRIPT.
Related
I have a link in a php while loop
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
The pop up requires the product id to search the database but hash tag is client side. I tried to use javascript window.location.hash but the outcome was not very reliable.
Does anyone know a method preferably server side I could use to retain the active product id while I call the pop up, attain the product id, use it to query the database and output it in the pop up.
I have a session already started and tied to a different condition.
I tried to call the product id directly from the pop up but because of the loop I only get either the first or last in the array.
<?
while ($i < $num) {
$product_id=mysql_result($result,$i,"prod_id");
$title=mysql_result($result,$i,"lTitle");
//main page
echo "<b>" , $title;
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
?>
<!------pop up--------->
<script type="text/javascript">
function pop_up(){
document.getElementById('pop').style.display='block';
}
</script>
<div id="pop">
<p style='color:#6F0A0A; font-size:15px;'><? echo $product_id; ?></p>
</div>
<?
$i++;
}
?>
I'll try answering but to be honest the question is very vague and the code is a bit messy.
First off, you can simply send the product_id as a GET variable to the new popup and read it in PHP. Something like this will work:
echo "<a href = 'http://www.mydomain.com/popup.php?product_id=$product_id' onclick="window.open(this.href, 'popup_win',
'left=100,top=100,width=500,height=500,toolbar=1,resizable=0'); return false;" id = 'linker' >See more</a>";
On your popup.php file (the popup page) you will get the product_id with the PHP $_GET method:
$product_id = $_GET['product_id'];
and then do whatever MySQL query you want, now that you know $product_id.
I hope this helps, if that's not exactly what you meant please add more details so I can revise my answer.
Well, you could first load all this records first and place them into the popup content or, make an ajax request, open the popup, and when the request is done successfully place the values returned into the popup content. Better with JQuery
I'm looking to change the font color of a div using jquery where the div is populated by the output of a SQL query.
I have:
$(document).ready(function(){
$('#foo').each(function(){
if ($(this).text() == 'bar') {
$(this).css('color','orange');
}
});
});
From a SO search which works fine when the div contains text.
But as this is SQL i'm populating the div with: ".$row['result']."
And this now does not work. I'm guessing this is because the sql, although being a varchar field is a $variable and isn't 'text' as such?.
I'm sure this is something simple, but i'm struggling to phrase this in google to return anything useful.
Many thanks.
edit
The whole thing is rather long and before i've tried to add the jquery was all working fine, so i'll just post the additions.
This is within the head:
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js'></script>";
echo "<script type='text/javascript'>";
echo "$(document).ready(function(){ $('#foo').each(function(){ if ($(this).text() == 'bar') { $(this).css('color','orange');}});});";
Then i echo each row in a while loop:
$sql = "SELECT...";
$result = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<div id='foo'>".$row['result']."</div>";
}
The whole document is wrapped in PHP but its not the source of the issue as if i change the div to contain text rather than ".$row['result']." then the jquery executes on it just fine.
You are giving every div the same id ("foo"). An id has to be unique in HTML, you would be better off using a class for this. The way you have it now the .each() function would only be called on one element, possibly the first.
Change the HTML output like this:
echo "<div class='foo'>".$row['result']."</div>";
Then, adapt your selector in jQuery accordingly:
$('.foo').each(function(){
// ...
}
Do you use a $.ajax call or just emmbed the value via PHP on page load?
If you use PHP to print the value, I guess you forgott to echo the value:
".<?php echo $row['result']?>."
Not just:
".$row['result']."
So this is what I have - A javascript onclick event that will parse json from my MySQL database data and display it when someone clicks on a seat.
var jsonData = <?php echo json_encode($array); ?>;
function displayInfoForDiv(i){
document.getElementById('fname').innerHTML = jsonData[i].first_name;
document.getElementById('lname').innerHTML = jsonData[i].last_name;
}
Output
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span id="fname"><?php echo $row['first_name']; ?></span></p>
<p><span id="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
The PHP is for my search box when you try to look up a name - I'm using this
$sql = mysql_query("select * from people where first_name like '%$term%' OR last_name LIKE '%$term2%'");
So the problem I'm having is when I conduct a search for Matt, more then one result will show up. Say:
Matt
Hasselbeck
Matt
Hew
But if I use the onclick event and click on joe's seat, it will display like this:
Joe
Frill
Matt
Hew
So the problem is that the search results will remain when I trigger the onClick event but the first one will change.
My question is, is there a way when I click on a seat to clear the search results and only display the one but when I conduct a search to display the similar names.
I'm using the PHP and JS to call the same data because, the JS only has a range of floor, while the php is grabbing everything from the database.
Hopefully this is clear and thank you for any input.
You Have Two Issues going on here.
You are using the same value for the id attribute multiple times.
Your result setup is logically flawed
Solution to Issue 1
Change id attribute to class attribute
When you use document.getElementById in javascript it returns the first element with that id.
Which means that if you have multiple ids with the same value only the first element will be selected. So your function should be changed to the following
function displayInfoForDiv(i){
document.getElementsByClassName('fname')[i].innerHTML = jsonData[i].first_name;
document.getElementsByClassName('lname')[i].innerHTML = jsonData[i].last_name;
}
Solution to Issue 2
Use template for results
Wrap all results in a div tag
By wrapping results into a div tag you will be able to clear results by clearing the html for that div tag.
<div id='Results'>
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span class="fname"><?php echo $row['first_name']; ?></span></p>
<p><span class="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
</div>
<script>
function clearResults()
{
document.getElementById('Results').innerHTML='';
}
</script>
To use a template for results I would recommend underscore.js
So a template for your needs would look like the following:
<script id='result-template' type="text/x-jquery-tmpl">
<p><span class="fname">${first_name}</span></p>
<p><span class="lname">${last_name}</span></p>
</script>
And to utilize the template you would do the following:
The code below assumes you have included underscore.js
function LoadResults(jsonData)
{
_.templateSettings = {
interpolate: /\$\{(.+?)\}/g
};
var output='',
resultDiv=document.getElementById('Results');
template= _.template(
document.getElementById('result-template').innerHTML
);
clearResults();
for(x in jsonData)
{
resultDiv.innerHTML+=template(jsonData[x]);
}
}
I am trying to build a db driven web site in which the user selects from a drop down menu a
value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:
$("#button").click(function(){
var datastr = ($('#act').val());
var datastr1 = ($('#loc').val());
$.ajax({
type:'POST',
url:'activities_code.php',
data: {datastr:datastr, datastr1:datastr1},
success:function(response){
$("#msg").html(response);
} });});
In the url parameter I have the following php file (this is a part of the php file):
$query = "SELECT PK,title,Information from activities where Activities='$category'";
$result = mysqli_query($dbcon, $query) or die('no available data');
echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Here the columns of title and information are printed
echo "<tr><td>";
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
echo "<br>";
echo $x = $row['PK'];
echo "</td></tr>";
echo "<tr><td>";
echo $row['Information'];
echo "</td></tr>";
// Here I sum up the number of the results
$num_results=$num_results+1;
$t = $t+1;
}
}
As you can see, I have a while loop in which I echo each time a link with an id:
"<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
What I want to do is to use this id of each link later in my code by doing something like this:
document.getElementById("t1").value
My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what.
If you dont understand some part of the code or I didn't explain everything clear, please ask me.
Thanks
D.
This is what I get when I alert(response) in the success function.
<!DOCTYPE HTML>
<table id="container"><tr><td><a href='test.php' id="t0" target="_new" class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
<img src="m.jpg" class="textwrap" height="120px" width="120px">
<p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
<br>
<br>
<hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
<p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
<br>
<br>
<br>
<hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!
</div></table> <!-- End of PHP code-->
First, There is problem with ID of your anchor tag. here is correction
"<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Second, Give id to your table like
<table id="container">
Third, give class to your anchor tag.
"<a href='test.php' class='pickanchor' id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Now write following code into your success handle after .html() statement
NEW EDIT
$("a.pickanchor").each(function(i){
alert(this.id);
});
In line you presentd you made mistake. In wrong place you have added ".
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
It should be
echo "<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
As simplest solution you could add after the while loop
echo "<script> my_max_id_num=$t </script>"
This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.
Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:
Rewrite while loop so it returns something like:
{ "data":[
...
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
...
]}
Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.
This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.
The simplest solution would be to give your elements a class, that way you don't need to select based on the elements id, but you can access it easily:
eg.
test 0
test 1
$('#msg').on('click', '.className', function() {
console.log(this.id);
});
I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?
Lets say you wanted to get the link location it could be something like:
var value = $('#addButton').attr('href');
and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?
So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:
HTML
<div id="valueBox"></div>
jQuery
$("#valueBox").html(value);
Hi i want to get changed text value from JQuery but i can't select edit text with JQUERY because edit texts generated from php while loop that this php code query on database and get value of edit texts and in my program i have edit button for every edit texts and when the user changed value of edit text i select new value and when user click edit button send this value from get method to another php page with jquery $.ajax function and send new value to that php code with ajax.But i don't know how can i select edit text that it's value changed because i don't know id of that edit text!.And when i set one id for every edit text i only get first edit text value from $("#id").change().val();.I use below code but it doesn't work.I am beginner in java script and don't know how fix this problem!.
var testAnswer;
function setNewTestAnswer(id){
testAnswer = $("#id").val();
}
function sendToEdit(pID,phID,thDate,type){
var info = 'pId='+pID+'&phId='+phID+'&testAnswer='+testAnswer+'&thDate='+thDate+'&type='+type;
}
2nd function use testAnswer that user changed in edit text.
php code
<?php
include 'Connect.php';
if(match($_POST['pId'], "/^[\d]+$/") ){
$pId = $_POST['pId'];
$result = mysql_query("select pName, pID, phName, phID, testHistoryDate, type, testAnswer from patient join reception using(pID) join physician using(phID) join testHistory using(rID) join test using(tID) where pID = $pId",$connection);
}
else
die("Insert true value");
while($row=mysql_fetch_array($result)){
echo "<tr><td>";
echo $row["pName"].'</td>';
echo '<td>'.$row["phName"].'</td>';
echo '<td>'.$row["testHistoryDate"].'</td>';
echo '<td>'.$row["type"].'</td>';
$type = $row['type'];
$testHistoryDate = $row['testHistoryDate'];
?>
<td>
<span id='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer' value='<?php echo $row['testAnswer']; ?>' />
</span>
</td>
<td>
<input type='submit' value='Edit' name='edit' id='edit' onclick="sendToEdit('<?php echo $row['pID'] ?>','<?php echo $row['phID'] ?>', '<?php echo $row['testHistoryDate'] ?>', '<?php echo $row['type'] ?>')" />
</td>
</tr>
<?php } ?>
tl;dr
So it isn't completely clear what you are trying to do here but I can explain a couple things that might help.
in html ids should be unique. You dont have to obey this rule for your page to work but you have found one of the consequences if breaking it: jQuery will only find the first one.
it is a good idea to base html ids on some unique attribute of your data eg the table row id.
You can get more creative with your jQuery selectors for example
$('input[type="text"]') // gets all the text inputs
Use classes. When you want to be able to easily select all of a group of html elements you should give them all the same class name. one element can have multiple class names and many elements can share a class name. you can then select them by class name using jquery like this:
$('.myclassname')
I think you need to change your php to look more like this:
<span class='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer-<?php echo $row['id'] ?>' value='<?php echo $row['testAnswer']; ?>' />
</span>
Since you're creating elements inside a php loop, you must be sure that every element has a unique id (or no id at all). You can use either an incrementing index, or some unique value in your array. At first glance, seems that $row['pID'] is a good candidate:
<input id='edit_<?php $row['pID'] ?>' type='submit' value='Edit' ... />
After that you should be able to target individual elements.