Dynamic ID between PHP, SQL and jQuery - php

I have a SQL database that PHP is getting the contents of. It gets the info from each row of a table and displays it on a web page. There is also an anchor and a hidden div containing more details from that row of the SQL table. When the use clicks the anchor the jQuery needs to detect it and show the hidden div. The problem I have is that each anchor and hidden div have a dynamic id of:
'ev_a_' . $row['id']
'ev_' . $row['id']
the jQuery I assume needs to look something like this:
$('#ev_a_')[].click(function(){
$('#ev_')[].show();
}
I'm not entirely sure how this works and I've never used dynamic ids before in jQuery. Any suggestions?
I should point out the PHP/SQL code is:
while($row = mysql_fetch_array($q_result)){
echo "<br/><b>" . $row['a'] . "</b><br/>" . $row['b'] . ", " . $row['c'] . "<br/>" . $row['d'] . "<br/><a class='ev_event_a'>More Details</a><br/><div class='ev_event'>" . $row['e'] . "</div>";
}

I would use a class instead for these links instead and set the ID in a data attribute. Depending on your needs you don't even need the ID as you can show the next element if it is already part of the DOM.
A simple example (ID not used...):
Toggle details
<div class="initially_hidden">
...
</div>
....
Toggle details
<div class="initially_hidden">
...
</div>
....
and the javascript:
$('.show_more').on('click', function(e) {
e.preventDefault();
$(this).next().slideToggle();
// if you need the ID, you can get it via $(this).data('id')
});

Related

Get array details PHP

I have a google map on this page, all markers were generated by submit postcodes. So I have the array below, loop info of each marker,
imploded as ("array", "array") format, I am trying to click on a infoWindow and display the according marker details on details.php.
The problem is everything is on the button onclick event, only a simple get on the second page.
This is working, but it is a very bad way. Because the limit to URL length and security reasons;
I would like to be able to get an array info from details.php page,
and the button onclick event trigger url looks like: details.php?marker=id
I don't know what is the best way to go about this, can someone pointing me to the right direction please?
index.php
$info = array();
foreach($stmt as $x)
{
$info[] =
"<h4>" . $x['name'] . "</h4><hr />".
"<h5>Address: </h5>" . $x['Address']."<br />" .
"<h5>Postcode: " . $x['postcode'] ."</h5><br />" .
"<button onclick='window.location.href= \\\"details.php?marker=". "<h4>" . $x['name'] . "</h4><hr />".
"<h5>Address: </h5>" . $x['address']."<br />" . "<h5>Postcode: " . $x['postcode'] ."</h5><br />" . "\\\" ' >
View Details</button>";
}
$i=' "'.implode('","', $info).'"';
details.php
echo $infomarker = $_GET['marker'];
You have to use $x['id'] insted of $x['name'] which is unique in your database and also use base64_encode() for encryption of your id "details.php?marker=".base64_encode($x['id'])."
In your details.php
$infomarker = base64_decode($_GET['marker']);
Try using AJAX to get the info from details.php and then load it into your InfoWindow.
I didn't realise how simple this was, all I need is use that id, write it inside a sql statement in details page then call any part of the statement out. Thanks everyone. Thanks to #Manjeet Barnala for encode tips.

How to make an inline editable content?

I have a list of products that I wish to be editable. When a user hits the edit button, then the content of only the selected product needs to be changed (for example to a textbox so the user can edit the title on the fly). But how do I prevent php to echo for example a textbox to all the products- I guess it would do that automatically?
I also guess that i should use some Jquery stuff to make the content editable :P ?
The list is being looped like this:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo $products['product_name'];
echo 'Edit me';
}
As your first commenter pointed out, PHP alone is not enough here. You'll need on-page JS code that can communicate the changes in the browser, and a PHP script that can take those changes and work them back into the database. You can either write that yourself, or use proven libraries that exist specifically for this purpose, like http://backbonejs.org/ or http://angularjs.org/
These are model/view frameworks that let you show a view of your database data on a page, while keeping them editable, updating the database records when you update the entry online. But be warned: if you've never worked with MVC frameworks, you get to look forward to probably being very confused at first. The approach is completely different from the much simpler "get data from db with PHP, generate page content, send off to client, the end" approach.
Not necessarily the most efficient, but if there aren't a huge number of products how about including a simple form for each product but just hiding it until the 'Edit' link is clicked?
The list/forms:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo "<span>" . $products['product_name'] . "</span>";
echo "<a class='editButton'>Edit</a>";
echo "<form action='products.php' method='post' style='display: none;'>
<input type='hidden' name='product' value='" . $products['prodcut_id'] . "' >
<input type='text' name='title' value='" . $products['product_name'] . "' >
<input type='submit' value='Update' >
</form>";
echo "<br/>";
}
The jQuery:
$(".editButton").click(function(){
//Hide the text entry and the edit link
$(this).prev().hide();
$(this).hide();
//Show the form
$(this).next().show();
});
If you'd rather not reload the page to submit changes you could submit them via ajax too for a more dynamic user experience.

How do i pass a mysql query result as a variable to be used in another query search?

Ok so basically I've got a product database. members search the database by clicking on categories of their choice.
These categories are spans which all trigger a javascript (ajax) function which calls a php query to find all of the subcategories of the span just clicked.
Those subcategories are outputted in a while loop which creates more spans which also trigger the same js function which will link back to the query.
The code below shows the output of the categories displayed based on the output of the database query.
"<div id=\"div1\">";
while($row = mysql_fetch_array($result))
{
$spans++;
echo " <span id=\"$spans\"
onclick='serverconnect(\"http://localhost/dreamweaver/Website/webdev/Code structure.php\",
\"nya\")'> $row[1] </span>";
echo "<br />";
}
"</div>";
So let's say the output of this is:
HEALTH
FITNESS
EDUCATION
LEISURE
How could i pass the span names as values for the next query so that whatever span is clicked on gets its appropriate value passed to the database search?
Would i have to somehow assign the contents of each span to a variable and then pass the variable to the javascript function which would then pass it to the query?
Im out of ideas as to how to do that, or if i should do it another way.
Thanks!
Try replacing:
echo " <span id=\"$spans\"
onclick='serverconnect(\"http://localhost/dreamweaver/Website/webdev/Code structure.php
\", \"nya\")'> $row[1] </span>";
With:
echo " <span id=\"$spans\"
onclick='serverconnect(\"http://localhost/dreamweaver/Website/webdev/Code
structure.php?value=" . urlencode($row[1]) . "\", \"nya\")'> $row[1] </span>";
You may then retrieve the value in $_GET['value'] after clicking the SPAN.
Note: I added some line breaks in the text for ease of reading, don't forget to remove them.

Using PHP function to create a dynamic dropdown menu using arrays: dropdown doesn't populate

I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.

Variable for unique ids in JavaScript function

I have an onclick event called in a PHP foreach loop for several items whose author name I need to click. Only one name was getting generated, so I know that I must have a unique id for each HTML element. I already have a variable $objkey for a counter used in the loop so I appended it to the id.
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo 'Click name to add <span><button id="closest' . $objkey . '" onClick="setAuthor()">' . $closest . '</button></span><br />';
?>
I have done a print_r('$objkey); and the appropriate value for the counter is getting passed along.
I want the value of this button element $closest to be passed to an input field. I have appended the variable to both the input's id and name elements (not sure if that helps) (UPDATE: There is an input field for each of the authors that needs to get the value):
<?php
echo '<input id="author_name' . $objkey . '" type="text" name="author_name' . $objkey . '" value="' . $author . '" />';
?>
Where I'm stuck is with my function:
<script type="text/javascript">function setAuthor() {
var author = document.getElementById("closest").innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author; }</script>
How do I create a variable in the function for the unique ids so that each looped item generates distinct names?
One way to do it is to pass this to the the setAuthor function:
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo "Click name to add <button id='closest_{$objkey}' onClick='setAuthor(this)'>{$closest}</button><br/>";
?>
With this approach, you can access the element within setAuthor:
<script type="text/javascript">
function setAuthor(el) {
var author = el.innerHTML,
id = el.id.replace(/^closest_/, '');
if (console) {
console.log(author);
}
document.forms["myform"].elements["author_name_" + id].value = author;
}
</script>
However, you shouldn't set onclick inline and for each element. You should use an event registration function.

Categories