load same data with jquery tooltip - javascript

is that posible to load same data with jquery tooltip?
for example i have a data like this.
<div class="content"><span id="user_801130021">text1</span></div>
<div class="content"><span id="user_801130021">text2</span></div>
<div class="content"><span id="user_1301193710">text3</span></div>
the tooltip only showing for text1 and text3 but not showing data for text2, i think that because same id there.
here my js code
$(document).ready(function(){
// initialize tooltip
$( " span" ).tooltip({
track:true,
open: function( event, ui ) {
ui.tooltip.css("max-width", "100%");
var id = this.id;
var split_id = id.split('_');
var userid = split_id[1];
$.ajax({
url:'fetch_details.php',
type:'post',
data:{userid:userid},
success: function(response){
// Setting content option
$("#"+id).tooltip('option','content',response);
}
});
}
});
$(" span").mouseout(function(){
// re-initializing tooltip
$(this).tooltip();
$('.ui-tooltip').hide();
});
});
my fetch_details.php
<?php
$userid = $_POST['userid'];
$query = $db->prepare ("SELECT * FROM master_post WHERE id_master_post =".$userid);
$query->execute();
$html = '<div>';
while ($value = $query->fetch()) {
$information = html_entity_decode ($value['information']);
$dom = new DOMDocument();
#$dom->loadHTML($information);
$image = $dom->getElementsByTagName('img')->item(0)->getAttribute('src');
$html .= "<img src='".$image."' height='300px' width='250px'>";
}
$html .= '</div>';
echo $html;
?>

If they are not going to be unique as in your code, you can do different things.
Class
You can use class instead of id.
Use <span class="user_801130021"> instead of <span id="user_801130021">
You can access them by using basic jQuery selectors : $('.user_801130021')
HTML5 Data Attributes
Another option is using them as HTML5 data attributes which is so much better in my opinion. Their format is data-*.
<span data-user="user_801130021">
You can get data-user value by $('span').data('user') and change it by $('span').data('user', value)
For example, if you changed id to data-user, you must change var id = this.id; to var id = this.data('user');. Then everything will be work as it must.

i found the trick.
use looping number to create unique id.
here my code.
$np = 0;
while ($value = $query->fetch()) {
<div class="content"><span id="user<?php echo np++ ?>_801130021">text1</span></div>
}

Related

Populate DIV with an PHP arrayelement based on a click on a link

What I want:
A list of links show events - a click on such a link shall show further details in a special DIV on the same page.
Idea:
I read from the database all events:
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
This gives me all available events in the DB that are not yet processed.
I assgin all found events identified by their UUID into a PHP array for further processing
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i",
$eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
Having that 2-dimensional array "eventInfo" I build the list
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
Last but not least I create a DIV to store the desired eventBody-Information:
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
To populate now the DIV when a link is clicked I tried this:
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
I wanted to pass the php-Array with JSON to make it available inside the function.
With the click-effect I wanted to load from this php-array the related array-element ['eventBody'] with the UUID given by the link-click.
Somehow I am stuck. I am able to pass the UUDI key to the javascript area and can write it into the DIV but I cannot identify a php-element by the given UUID and put the content into the DIV.
Any hint is appreciated, thank you.
As requested here is the code in total:
<?php
// Including jQuery
echo '<script src="http://code.jquery.com/jquery-1.11.3.min.js">/script>';
// Querying the Neo4J DB
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
// Parsing result and build the 2-dimensional array $eventInfo
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i", $eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
// Displaying list of events with UUID as forwarded parameter (-> JS)
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
// Creating a DIV Container to hold $eventInfo[eventUUID][eventBody]
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
// JavaScript Part
echo <<<EOT
<script type="text/javascript">
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
</script>
EOT;
?>
2nd EDIT:
I have stripped down everything to this functioncode, which is at the end of the php-file and no longer wrapped in the php-tags. So its like standard html. This way I avoid the uncaught syntax error.
<script type='text/javascript'>
$(document).ready(function (){
var passedArray = '<?php echo json_encode(array($test_array)); ?>';
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
console.log(p);
console.log(passedArray[p]['eventBody']);
$('#info').text(passedArray[p]);
});
});
</script>
Outcome:
I can console.log the array, which shows as a test:
[[{"UUID":"60762d3eb9949596701a2dfb700cd2c9","eventBody":"Hallo"},{"UUID":"620c16ced5097bf60f718abca7d979f8","eventBody":"Ciao"}]]
I see also that when I click a link that the UUID key is passed to the Javascript-Script:
60762d3eb9949596701a2dfb700cd2c9
But when I want to assign the related eventBody-element I receive this error:
Uncaught TypeError: passedArray[p] is undefined
As I have the array and the key I assume it must be a syntax error in this line:
console.log(passedArray[p]['eventBody']);
So two questions left:
How would I access one element of the given array?
How can I then populate the DIV with the element ['UUID']['eventBody']? Not sure if this is the way to go: $('#info').html().passedArray[p];
Resolution (with Uwe's help):
function findme(p) {
var passedArray = '<?php echo json_encode($test_array); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
thanks to your support here (Kudos to Uwe) here is the solution:
As we use jQuery we need to include this in the head:
echo '<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>';
The Javascript-Function (written in HTML, not in PHP tags):
function findme(p) {
var passedArray = '<?php echo json_encode($eventInfo); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
I was not able to find a way to write the whole code within PHP tags, as the double echo (Start and inside the array handover) and the additional PHP?-tags always generates syntax errors - thus the JS function is written as HTML-code outside the PHP code.
In the PHP the UUID of the array is passed onClick to the JS function - looks like
echo ' Find the element by UUID Brackets -- '.$UUID.'';
Please pay attention to the escaped quotation marks - important to avoid an error in JS that allows no identifiers starting with a number.
The DIV is marked by
echo '<p id="result"></p>';
For testing I made an array like this:
$eventInfo= array();
$eventInfo[] = array('UUID' => '60762d3', 'eventBody' => 'Text 1');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 2');
$eventInfo[] = array('UUID' => '6076299', 'eventBody' => 'Text 3');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 4');

Jquery Autocomplete and MySQL ID Value

hoping someone can help me out with something.
I've got a piece of code which allows the Jquery Autocomplete. What I'm wanting to do is to use the ID(primary key) from my MySQL table and then use that to POST on to another screen.
How would I go about getting the ID into a hidden value from the Jquery code?
Here are my snippets.
Jquery
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'JQUERYTEST.php'
});
});
</script>
Html
<div class="ui-widget">
<label for="shop">Shopname: </label>
<input id="shop">
</div>
Php/MySQL
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'aurora';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM shops WHERE shopname LIKE '%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['shopname'] . ' - '. $row['streetaddress'] . ' - ' . $row['postcode'];
}
//return json data
echo json_encode($data);
?>
Thanks!
Firstly, you will have to use an Ajax call to get the data from the server. So, change your autocomplete function and add an ajax call to receive a response. Then you will have to loop the JSON array in jquery. I have created the id as the whole string with shopname, streetaddress and postcode. Currently, your code doesn't inserts the ID parameter from the database. You can create an id depending on your needs. Then dynamically I have created the HTML and then placed it inside the <div class="ui-widget">
<script>
$( function() {
$( "#skills" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
var html = "";
$.each(data, function(i, item) {
var arr = item.split('-');
html += "<label for='shop'>Shopname:"+arr[0]+" </label><input id='"+item+"' type='hidden'><br>";
});​
$('.ui-widget').html(html);
}
});
}
});
});
</script>
Try this out. I hope this helps you.

Ajax autocomplete doesn't return correct value

I have an ajax autocomplete where it returns the full name of the user. However, when there are instances where some names or values are the same, it doesn't return the correct value. Rather, it returns the first value in the dropdown. Even if it has 4 same occurences, it still returns the first value.
When I click Stannis Arryn Baratheon, it returns Stannis Targaryen Baratheon.
Here is my php code (sql/php code; ad.php):
<?php
include('config.php');
if($_POST)
{
if($_POST['search_keyword'])
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
//$name = $row['fullname'];
//$copiedname = $row['fullname'];
//$b_name= '<strong>'.$similar.'</strong>';
//$final_name = str_ireplace($similar, $b_name, $name);
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
HTML input form:
<form method="post" action="try.php" name="try">
<div class='web'>
<input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
<input type="hidden" name="resID" id="resID"/>
<div id="result"></div>
<input type="submit" name="try" value="Submit">
</div>
AJAX/JS/JQUERY CODE (i think this is where the problem occurs):
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "ad.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").on("click", function(e)
{
/*var $clicked = $(e.target);
var $name = $clicked.find('.returnName').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
var $clicked = $(e.target);
var $id = $clicked.find('.returnID').html();
var id = $("<div/>").html($id).text();
$('#resID').val(id);
*/
$name = $('span.returnName',this).html();
$name = $("<div/>").html($name).text().toString();
$('#search_keyword_id').val($name);
$id = $('span.returnID',this).html();
$id = $("<div/>").html($id).text().toString();
$('#resID').val($id);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
jQuery("#result").hide();
}
});
});
</script>
It really returns the first value even if I click the second or third or fourth value. Where did I go wrong in my code? Please help me. Thank you so much!
Your code is currently collecting all elements with class returnName in #result, and by calling .html() on that collection jQuery will only return the html of the first element found. The same goes for the your returnID search. This is why you are only getting the first returned entry.
Modify your #result click handler to only trigger for elements with class show, since that is the element that will contain your data.
jQuery("#result").on("click", ".show", function(e){
Then all you have to do is search for the elements with class returnName and returnID and call .text().
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
So all together
jQuery("#result").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
});
Though note there are probably better ways of returning your data, and utilizing it rather than transporting it in html elements. For example use data-* attributes instead of using a separate span element to contain your id.
Another option is to use jQuery-UI's autocomplete that does most of the client side work for you and just return the raw data in JSON format from your php script.
In your php code, change this:
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
With this:
<div class="show" align="left">
<span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>
And your new jquery function:
jQuery("#result").on("click","'.returnName" function(e)
{
var choosenName = $(this).html();
var choosenId = $(this).data('id');
$('#search_keyword_id').val(choosenName );
$('#resID').val(choosenId );
});

Cannot integrate jQuery variable into php

I try to make a query from database to get the list of users based on their country using php/mysql and jquery.
I have a mysql query that extracts the countries form database in a select options field. After this, i put a jquery code to automatically get the table with users based on the selected country. This is how jquery code looks like:
<script>
$( "#tara" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += "<table class='table table-bordered table-striped'>" +
"<thead><tr><th><p><?php echo _('Tara');?></p></th></tr></thead>" +
"<tbody>" +
"<?php
$variabilatara = 182;
$test = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") ?>" +
"<?php while($row=mysql_fetch_object($test))
{
echo "<tr>";
echo "<td><p>$row->nume</p></td>";
echo "</tr>";
}
?>" + $( this ).val() + " ";
});
$( "#testare" ).html( str );
})
.change();
</script>
My question is: How to put the $( this ).val() into php instead of $variabilatara, so it will looks something like: $variabilatara = $( this ).val(); and the sql query will modify on change of selected country. Thank you!
What you are trying to do is called AJAX. Sounds complicated, but it really isn't. See these examples for a simplistic explanation. Do not just look at them -- copy/paste to your server and make them work. Change the values. See how it works - really very simple.
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Your code is a bit difficult for me to follow, but should be refactored something like this. (I am unsure where strTara figures in the code, but I'm sure you will be able to figure it out from here).
javascript/jQuery:
var strTara = <?php echo _('Tara');?>
$( "#tara" ).change(function () {
selVal = $(this).val();
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'variabilatara=' + selVal,
success: function(data){
var tblHead = "
<table class='table table-bordered table-striped'>
<thead><tr><th><p>strTara</p></th></tr></thead><tbody>
";
$( "#testare" ).html( tblHead + data );
}
});
});
another_php_file.php: (your PHP AJAX processor file)
<?php
$var = $_POST['variabilatara'];
$out = '';
$result = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") or die(mysql_error());
while($row=mysql_fetch_object($result)){
$out .= "<tr>";
$out .= "<td><p>" .$row->nume. "</p></td>"; //<== fixed
$out .= "</tr>";
}
$out .= '</tbody></table>'; //<== fixed
echo $out;
?>

Ajax script loading/Displaying only once

This script displaying the dynamic content for once thereafter its not working
Here is the code:
$(document).ready(function(){
$('.getmore').on('click',function(){
var last_id = $(this).attr('id');
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/getmore.php',
data: 'last_id='+last_id,
beforeSend: function(){
$('.getmore').html('<img src="../images/loader.gif" alt="Loading..." />');
},
success: function(data){
$('.getmore').remove();
$('#comments').append(data);
}
});
});
});
Here is the complete php code:
<?php
mysql_connect('localhost','root','') or die('Error... Couldnt connect..');
mysql_select_db('mydb') or die('Error... Couldnt select the Db..');
$records = mysql_query(' SELECT * FROM `compare_post_comments` WHERE `post_id`=37 limit 5 ');
if(mysql_num_rows($records)){
echo '<div id="ajax_comment">';
echo '<ul id="comments">';
while($data = #mysql_fetch_array($records) ){
echo '<li>'.$data['comments'].'</li>';
$last_record = $data['sno'];
}
echo '<li class="getmore" id="'.$last_record.'">Get More</li>';
echo '</ul>';
echo "<span id='cmmnts'></span>";
echo '</div>';
}
?>
getmore.php code
<?php
if( ( isset($_POST['last_id'])!=null ) && $_POST['last_id']!="" ){
$last_id = $_POST['last_id'];
//echo "::".$last_id;
$qry = " SELECT * FROM `compare_post_comments` WHERE `post_id`=37 and sno > ".$last_id." limit 5 ";
//echo "::".$qry;
$comments = mysql_query($qry) or die('Error..');
if( mysql_num_rows($comments) ){
while( $data = mysql_fetch_array($comments) ){
echo "<li>".$data['comments']."</li>";
$last_id=$data['sno'];
}
echo "<li class='getmore' id='".$last_id."'>Get More</li>";
}else{
echo "<li class='nomore'>No More</li>";
}
}else{
echo "<li class='nomore'>No More</li>";
}
?>
ajax call working for once, thereafter its not clickable.
I dont have much knowledge about ajax and javascript, explanation is appreciated.
Try the deferred syntax of on instead:
$(document).on('click', '.getmore', function...
This will survive DOM changes. This answer presumes that your loaded data contains an object with class="getmore", as you are removing it from the DOM on success. If not you need to remove the remove as suggested by NewInTheBusiness, but probably replace it with empty() instead to remove the loading progress.
Note I have recently found problems with the version of on that only takes the event and function. In jQuery 1.10.3 it seems to not be firing when it should.
It's because you remove the getmore class after success.
Remove this line of code:
$('.getmore').remove();
Check your firebug console for any error
Remove this line $('.getmore').remove();
Delegate the click event to the element's static parent or to the document.
Try,
$(document).on("click",'.getmore', function( event ) {
});
Just try live or bind in-place of "on" :
$('.getmore').live('click',function(){
}
or
$('.getmore').bind('click',function(){
}

Categories