I try to realize the following:
I generate via php a table of two fields (about training lessons) - lessons' name and location.
This table has several rows and i implemented an like this:
<table border='0' id='testing'>
<thead>
<tr class='small_title_bold'>
<th>Formation</th><th align='center'>Niveau</th><th align='center'>Ville</th>
</tr>
</thead>
<tbody>
<?php
db_connect();
if (isset($etablissement)){
$sql_find_id_etablissement = "select id_etablissement, subdesignation, address1, address2, zip, city, town, department, phone, fax, www from etablissements where designation = '$etablissement' and id_region='$id_region'";
$result_find_id_etablissement = mysql_query($sql_find_id_etablissement, $connection) or die('error');
while ($row_find_id_etablissement = mysql_fetch_row($result_find_id_etablissement)){
$id_etablissement = $row_find_id_etablissement[0];
$subdesignation = $row_find_id_etablissement[1];
$address1 = $row_find_id_etablissement[2];
$address2 = $row_find_id_etablissement[3];
$zip = $row_find_id_etablissement[4];
$city = $row_find_id_etablissement[5];
$town = $row_find_id_etablissement[6];
$department = $row_find_id_etablissement[7];
$phone = $row_find_id_etablissement[8];
$fax = $row_find_id_etablissement[9];
$www = $row_find_id_etablissement[10];
print "<tr class='small_subtitle_bold'><td colspan='3' align='center'>".$id_etablissement."-". $subdesignation."</td></tr>";
$sql_find_master = "select id_master, designation, master_level from masters where id_etablissement = '$id_etablissement' order by designation, master_level";
$result_find_master = mysql_query($sql_find_master, $connection) or die('error');
$count=mysql_num_rows($result_find_master);
for($i = 0; $i < $count; $i++) {
$row_find_master = mysql_fetch_row($result_find_master);
$id_master = $row_find_master[0];
$designation = $row_find_master[1];
$level = $row_find_master[2];
if($i % 2) {
print "<tr class='univ' bgcolor='#A4D2FD'>";
print "<td><a class='univ' href='master-details.php?master-id=".$id_master."&etablissement-id=".$id_etablissement."' onclick='popup('master-details.php?master=".$designation."')>".$designation."</a></td><td class='small_text' align='center'>".$level."</td><td class='small_text' align='center'>".$town."</td>";
print "</tr>";
}
else {
print "<tr class='univ' bgcolor='#FFFFFF'>";
print "<td><a class='univ' href='#' onClick='javascript:swapContent(".$id_master.",".$id_etablissement.")'>".$designation."</a></td><td class='small_text' align='center'>".$level."</td><td class='small_text' align='center'>".$town."</td>";
print "</tr>";
}
}
}
}
?>
</tbody>
</table>
When a user clicks a row, i want to run a mysql query and present the results (the lesson's details) in a separated located in the same page without reloading the page.
I placed the following script in my head section:
<script language="JavaScript" type="text/javascript">
function swapContent(id_master, id_etablissement) {
var url = "master-details.php";
$.post(url, {id_master: id_master, id_etablissement: id_etablissement} ,function(data) {
var content = $( data ).find( '#content', function () {alert('Query was performed.');} );
$( "#queryResults" ).empty().append( content );
});
}
</script>
I want my jquery script to run a php file named master-details with the parameters id_master and id_etablissement and returns the results in a DIV section named queryResults.
However, when I clicked on a row in my table, nothing happened.
Any help would be greatly appreciated.
Something like this:
jQuery("tr").live("click", function(){
$.post///what you already have.
});
You just need a way to tell it to do something when you click.
...when I clicked on a row in my table, nothing happened.
Something happened, even if it was not apparent. The task is to determine exactly what happened, and why it didn't produce the expected results.
There are several steps you can take to determine what really happened:
Check for Javascript errors. You can use Firebug for Firefox or the built in Developer Tools for Chrome to view the Javascript console. If a Javascript error occurred, it will be shown there.
Determine if the PHP script was executed. You can do this by checking your webserver's logs, or by looking at the "Network" tab of the aforementioned tools.
If the PHP script is successfully executing, determine what output it produces. You can do this by running the script directly. Find the URL that your AJAX call references, and paste it into your browser's address bar. Is the output what you expect it to be?
If the PHP script executes and returns appropriate results, check your Javascript selectors. Are you sure they reference the correct div? Does that div exist?
Related
I have a little problem in my code, please review it and help me.
I want to assign value of the span tag(fetched by id in html) to a php variable and then run a sql query to fetch record of the related value in the table. Here is my code.
I tried it in different ways but it not works.
I print the sql query and its absolutely right but does not show the correct result. I copied that printed sql query and paste it into phpmyadmin query section and run it there. Then it works fine and show related records. Please help
$regg = '<span id="modal-myvalue"></span>';
$fee_detail = "SELECT * FROM `fee_enroll` WHERE registeration = '$regg' AND mode = 'ENABLE'";
//here i print the query and its output is correct but doesn't show the correct record here.
echo $fee_detail;
$result_fee = mysqli_query($con, $fee_detail);
while($row_fee = mysqli_fetch_assoc($result_fee)) {
echo $row_fee['registeration'];
}
The data which i want to fetch in span tag(in id) is sent from a button through this script:
<script type="text/javascript">
var ATTRIBUTES = ['myvalue'];
$('[data-toggle="modal"]').on('click', function(e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function(attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '');
});
});
</script>
and the button code is
<a class="btn" type=submit data-toggle="modal" data-target="#model-view" data-myvalue="<?php echo $row['registeration']; ?>">VIEW Detail</a>
When i print the query it shows:
(SELECT * FROM `fee_enroll` WHERE registeration = 'FA12-BSE-094' AND mode = 'ENABLE')
which works correctly in phpmyadmin query section. but not works here when i want to execute.
You can try DOMDocument as follows,
$regg = '<span id="modal-myvalue">FA12-BSE-094</span>';
$doc = new DOMDocument();
$doc->loadHTML($regg);
$elements = $doc->getElementsByTagName('span')->item(0);
var_dump($elements->nodeValue);
And then you can use this variable in query like below,
$fee_detail = "SELECT * FROM `fee_enroll` WHERE registeration = '$elements->nodeValue' AND mode = 'ENABLE'";
You cannot insert a variable like that. See this answer.
Complex (curly) syntax
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.
Curly braces in string in PHP
My suggestion should be to change the query string into the following:
$fee_detail = "SELECT * FROMfee_enrollWHERE registeration = '{$regg}' AND mode = 'ENABLE'";
Having an annoying small problem. Cannot find the solution that works tried just about everything i could find from searching here and google.
Purpose of this is to pass them along into a "room" that has been created previously.
Seems like it doesn't matter what i try i cannot get it to load into another page using onclick with an href. And i know its an easy fix its just something silly i cannot think of.
and sorry if i am not posting my code just right this is my first time asking a question i normally just lurk around for answers.
//..Left out <?php and my connect info but it is in my script
//--CLEANUP MY MESS
$sql = "SHOW TABLES";
$result = mysql_query($sql) or die('err11');
while ($row = mysql_fetch_row($result)) $testing[$row[0]] = true;// Gets a list of tables in the database and turns them into a handy format
if ($testing['prim']){// Checks to see if table prim exists
$sql = "SELECT * FROM prim"; // Pulling all info again after cleaning
$result = mysql_query($sql) or die('err11');
$_e = '';
while ($row = mysql_fetch_assoc($result)){// Cycle through enteries to see what rooms are up
$_e = $_e . "<a href='' onclick='join(" . $row['room'] . ");'>" . $row['teach'] ."</a><br>";
}
}else $_e = "Sorry no rooms are open";
mysql_close($con);
?>
<!DOCTYPE html>
<html>
<head>
<script>
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
//THE LINE BELOW DOES NOT SEEM TO WORK
document.location = "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er;
//THE LINE ABOVE DOES NOT WORK
}
</script>
<title>Portal</title>
</head>
<body>
Name:<input type="text" id='name' name="name"><br><?php echo $_e ?>
</body>
</html>
I tried many different small variations like window.location window.location.href etc etc.. also messed with returns and just driving me nuts
Grateful for any help and you folks have a nice day
window.open will open a new window for you. (see http://www.javascript-coder.com/window-popup/javascript-window-open.phtml )
Alternatively you could set the href and use target="_blank". That way you don't have to use javascript so it's more accessible.
On first hand I am thinking try
<a href='#' onclick=...
but I will investigate further.
My thought is to try the following and see if it works.
hello
Then at least that will tell you if javascript is working properly on your browser etc.
You could try rename it from join to something another name because join is a javascript function (operating on arrays) maybe its having a conflict?
Try the following and tell me if it works. Then try adding some PHP code to the top and see if it still works.
<script>
function test()
{
alert("testing");
document.location = "http://location_edited_out/provingground/start.php?name=abcd&room=1";
}
</script>
hi
One thing you could try is to move the script out of the "head" section and into the body.
For example:
<html>
<head><title>Portal</title>
</head><body>
<script>
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
//THE LINE BELOW DOES NOT SEEM TO WORK
document.location = "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er;
//THE LINE ABOVE DOES NOT WORK
}
</script>
Name:<input type="text" id='name' name="name"><br><?php echo $_e ?>
</body>
</html>
Also you could try putting the script at the end of the body (after the php echo command).
Also you could try splitting it into two statements maybe it doesn't like doing it on the one line:
var url = "http://webaddr.com/start.php?name=" + document.getElementById("name").value + "&room=" + er;
document.location = url;
http://www.webmasterworld.com/javascript/3285118.htm
Try window.location.href or simply, location.href
top.location
?
The following works in internet explorer, having a button instead of an "a href".
<html>
<body>
<script>
function test()
{
alert("testing");
window.location.assign("http://location_edited_out/provingground/start.php?name=abcd&room=1")
}
</script>
<input type='button' value='Load new document' onclick='test()'>
</body></html>
Not sure if this is an option?
So the code is:
while ($row = mysql_fetch_assoc($result)){// Cycle through enteries to see what rooms are up
$_e = $_e . "<input type='button' onclick='join(" . $row['room'] . ");' value='" . $row['teach'] ."'><br>";
}
...
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
window.location.assign( "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er);
}
Let me know if it works.
First of all I need to say that I'm new to jQuery.
When I select an option of a menu, a PHP file is loaded into a div with the method load of jQuery. In this PHP file I have a table and a input text. When the PHP file is loaded it catch the values of database.
The problem apears that I need to create a search method for the values of database.
I need that when the user writes in the input of php document, the table load the values that match with the value of input.
The code that loads the PHP file is the next:
$("#searchuser").click(function() {
$(".info").load("usuerlist.php",function(){
$("#search").keyup(function(){
alert($('#search').val());
});
});
});
The name search is the name of the input.
The code of PHP file is the next:
<?php
require_once "aplicacio/loaddata.php";
include_once 'classe/gestorclass.php';
$var = new loaddata();
$var1 = $var->selectAllGestor();
$var2 = $var->selectAllUser();
?>
<div class="informacio">
Usuari<input type="text" name="cerca" id="cerca">
<table class="infoTable">
<tr class="titol"><td>User Name</td></tr>
<?php
for($i = 0; $i<sizeof($var1); $i++){
if($i % 2){
$res = '1';
}else{
$res= '2';
}
echo '<tr class="linia'.$res.'"><td>'.$var1[$i]->getUsuari().'</td></tr>';
}
?>
</table>
</div>
I found the solution.
I create a file that genereates the table, and when I put info into the input I call this file with the next code:
$("#searchuser").click(function() {
$(".info").load("usuarislist.php",function(){
$("#cerca").keyup(function(){
var valor = $('#cerca').val();
$("#tableUser").load("aplicacio/tableGenerator.php?origen=tableUser&valor="+valor);
I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
$(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.
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.