I have created a tooltip using javascript and have an html page using that tooltip.
Here is my tooltip:
$(document).ready(function () {
//Tooltips
$(".tip_trigger").hover(function (e) {
tip = $(this).find('.tip');
var tipText = $(e.target).attr('ti');
tip.html(tipText);
tip.show(); //Show tooltip
}, function () {
tip.hide(); //Hide tooltip
}).mousemove(function (e) {
var mousex = e.pageX + 20; //Get X coodrinates
var mousey = e.pageY + 20; //Get Y coordinates
var tipWidth = tip.width(); //Find width of tooltip
var tipHeight = tip.height(); //Find height of tooltip
//Distance of element from the right edge of viewport
var tipVisX = $(window).width() - (mousex + tipWidth);
//Distance of element from the bottom of viewport
var tipVisY = $(window).height() - (mousey + tipHeight);
if (tipVisX < 20) { //If tooltip exceeds the X coordinate of viewport
mousex = e.pageX - tipWidth - 20;
} if (tipVisY < 20) { //If tooltip exceeds the Y coordinate of viewport
mousey = e.pageY - tipHeight - 20;
}
tip.css({ top: mousey, left: mousex });
});
});
Here is HTML:
<div class="container">
<h1><span>Simple Example</span></h1>
<map name="Koala" class="tip_trigger">
<area ti="This is the left eye" shape="rect" coords="373,365,404,402" href="#" />
<area ti="Right Eye" shape="rect" coords="641,405,681,448" href="#" />
<div class="tip"></div>
I want the database value to display where "ti" is... ex. ti="database value"
How can this be done? I will be using MySQL along with php. All help I will be very grateful for.
Create a help table in mysql:
CREATE TABLE `help` (
`helpID` varchar(100) NOT NULL,
`helpText` text NOT NULL,
UNIQUE KEY `helpID` (`helpID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
For a generic tooltip, on the page where you want the help tip, put this html:
<span id="productSKUHelp" class="helpTip questionMark"></span>
Since you want the tooltip to appear when your cursor is in a certain spot, you should be able to use your mousemove function and call showTip.
Add the following JQuery:
function showTip(thisTip){
var postdata = {
helpTip: thisTip.attr('id')
};
$.ajax({
type : "post",
url : "/getHelpRPC.php",
dataType: "html",
data : postdata,
success : function(data){
if(data.length > 0){
var origContent = thisTip.html();
thisTip.removeClass("questionMark").addClass('helpTipBox');
thisTip.html(data);
}else{
$('#helpTipBox').html("error");
}
},
error : function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
$(document).on('mouseenter', '.helpTip', function(){
var thisTip = $(this);
helpTipTimer = setTimeout(function(){
showTip(thisTip);
},
1000);
})
$(document).on('click', '.helpTip', function(){
showTip($(this));
})
$(document).on('mouseleave', '.helpTip', function(){
clearTimeout(helpTipTimer);
$(this).html('').removeClass('helpTipBox').addClass('questionMark');
});
Add the following CSS:
.helpTip{
padding-left:3px;
z-index:900;
}
.questionMark:after{
color:maroon;
cursor:pointer;
content:"?";
top:2px;
position:relative;
padding:0 3px;
}
.helpTipBox{
padding:5px;
background-color:#97abcc;
position:absolute;
curson:text;
}
Create the getHelpRPC.php RPC:
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB);
if($mysqli->connect_errno){
printf("Connect failed: %s %s %s\n", $mysqli->connect_error, __FILE__, __LINE__);
exit();
}
$helpID = $_POST['helpTip'];
if($helpID != ""){
$querystr = "SELECT helpText FROM help WHERE helpID ='" . $mysqli->real_escape_string($helpID) . "'";
$res = $mysqli->query($querystr);
$rowCount = $res->num_rows;
if($rowCount > 0){
$row = $res->fetch_object();
echo $row->helpText;
} else {
echo "error selecting help.";
}
}
Now all you need to do is create a unique id in the span and add the corresponding record to the table.
Related
I try to get deeper into Leaflet + MySQL Connection, but I'm start loosing the overview. I have a database geomarkers with multiple markers, which have stored different attributes. I want to apply a functionality for the user, to delete markers which are not of interest by clicking "delete" in the marker's Popup-Box. But here its getting complicated. How can I get the individual id (from database) for the marker which is selected (click on delete in PopUp), and how can I pass this to a PHP-Command, that this point will be deleted in the database? I used The $_Post method to upload the data, but in this case thinks wont work.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"/>
<link rel="stylesheet" href="http://leaflet.github.io/Leaflet.draw/leaflet.draw.css"/>
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Norican">
</head>
<body>
<div id="map" >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!--<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js"></script>-->
<script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"></script>
<script src="http://leaflet.github.io/Leaflet.draw/leaflet.draw.js"></script>
<script>
$(document).ready(function() {
getUsers();
});
var map = L.map('map').setView([47.000,-120.554],13);
mapLink =
'OpenStreetMap';
L.tileLayer(
'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
attribution: 'Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)',
maxZoom: 18,
}).addTo(map);
var greenIcon = L.icon({
iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png',
iconSize: [30, 38], // size of the icon
});
function getUsers() {
$.getJSON("getData.php", function (data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var id = data[i].id;
var species = data[i].species;
var diameter = data[i].average_diameter;
var quality = data[i].quality;
var damage = data[i].damage;
var notes = data[i].additional_information;
var marker = L.marker([data[i].lat, data[i].lng], {icon: greenIcon}).addTo(map);
marker.bindPopup(id + "<br>" + species + "<br>" + diameter + "<br>" + quality + "<br>" + damage + "<br>" + notes + "<br>" + "<br>" +
'<input type="submit" id = "delete" name="action" data-value = " + id + " value="Delete" method = "post"/>');
}
})
}
</script>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#delete').click(function(d){
var id = document.getElementById("delete").getAttribute("data-value");
$.ajax({
type: 'POST',
url: 'delete.php',
data: {id:id}
success: function(data) {
alert(data);
}
error: function(data){
alert('Something went wrong while deleting.');}
});
});
});
</script>
</script>
</body>
</html>
getData.php
<?php
$connect = mysqli_connect("localhost", "root", "", "useraccounts");
$sql = "SELECT * FROM geomarker";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($data = mysqli_fetch_assoc($result))
{
$json_array[] = $data;
}
echo json_encode($json_array);
?>
delete.php
<?php
if(isset($_POST)){
$id = $_POST['id'];
$connect = mysqli_connect("localhost", "root", "", "useraccounts");
$sql = "DELETE FROM geomarker WHERE id = ($id)";
$result = mysqli_query($connect, $sql);
if($result){
echo 'Data successfully deleted.';
}else{
echo 'There were erros while deleting the data.';
}
}
?>
If your
'<a href="#" id = "delete" data-value = id >delete</a>'
is in some way winding up calling a function delete() somewhere and passing it the data-value attribute, all you may need to do is to write it so that the actual value of the ID at the point this is being defined is used:
'<a href="#" id = "delete" data-value = "' + id + "' >delete</a>'
#DrSnuggles In this way you can get to the delete function in the popup
marker.on('popupopen', function(e) {
// your delete function
});
Update example
let config = {
minZoom: 7,
maxZomm: 18,
};
const zoom = 16;
const lat = 52.2297700;
const lon = 21.0117800;
let points = [
[52.230020586193795, 21.01083755493164, 'point 1'],
[52.22924516170657, 21.011320352554325, 'point 2'],
[52.229511304688444, 21.01270973682404, 'point 3'],
[52.23040500771883, 21.012146472930908, 'point 4']
];
const map = L.map('map', config).setView([lat, lon], zoom);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// loop that adds many markers to the map
for (let i = 0; i < points.length; i++) {
const lat = points[i][0];
const lng = points[i][1];
const popupText = `<button data-value="test-${i+1}" class="delete">${points[i][2]}</button>`;
marker = new L.marker([lat, lng])
.bindPopup(popupText)
.addTo(map);
marker.on('popupopen', function(e) {
const btns = document.querySelectorAll('.delete');
btns.forEach(btn => {
btn.addEventListener('click', () => {
alert(btn.getAttribute('data-value'));
})
})
});
}
* {
margin: 0;
padding: 0
}
html {
height: 100%
}
body,
html,
#map {
height: 100%;
margin: 0;
padding: 0
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"></script>
<div id="map"></div>
Final code:
Finally I managed to puzzle everything together, getUsers() get some adjustment:
function getUsers() {
$.getJSON("getData.php", function (data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var id = data[i].id;
var species = data[i].species;
var diameter = data[i].average_diameter;
var quality = data[i].quality;
var damage = data[i].damage;
var notes = data[i].additional_information;
var popupText = `<button data-value= "${data[i].id}" class="delete">Delete</button>`;
var marker = new L.marker([data[i].lat, data[i].lng], {icon: greenIcon}).addTo(map);
marker.bindPopup("ID:"+ id + "<br>" + "Species: " + species + "<br>" + "Diameter: " + diameter +"cm" + "<br>" +"Quality: " + quality + "<br>" +"Damage: " + damage + "<br>" +"Notes: " + notes + "<br>" + "<br>" + popupText);
marker.on('popupopen',function(e){
const btns = document.querySelectorAll('.delete');
btns.forEach(btn => {
btn.addEventListener('click', () => {
var id = btn.getAttribute('data-value');
$.ajax({
type: 'POST',
url: 'delete.php',
data: {id1:id},
success: function(data){
alert(data);},
error: function(data){
alert('Something went wrong.');}
});
})
});
});
}
})
}
and also delete.php gets some adjustment:
<?php
$id= $_POST['id1'];
$connect = mysqli_connect("localhost", "root", "", "useraccounts");
$sql = "DELETE FROM geomarker WHERE id = ($id)";
$result = mysqli_query($connect, $sql);
if($result){
echo 'Data successfully deleted.';
}else{
echo 'There were erros while deleting the data.';
}
?>
Thx for the help!
I want to upload multi-file (more than 1000 files, with total more than 2GB).
In PHP, i use function
if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $original_file))
{
$stamp = '../contents/wm_watermark.png';
$this->create_watermark_photo($original_file, $stamp, $view_file, $ext);
$this->makeThumbnail($view_file, $thumb_file, $this->max_width_thumb, $this->max_width_thumb);
//insert photo info to DB
$this->Photo->create();
$this->Photo->save(
array(
'Photo' => array(
'folder_id' => $data_from_preparing_fileInfoList[$i]['sub'],
'name' => $filename
)
)
);
$status = '1';
$count++;
}
I found out that, when use move_upload_file , it didn't upload right now. It only keep in waiting stack. When this function run completedly, then it move file to server.
So, when i use upload process, it gain 100% , this ajax url still run.
$("#image_upload_form").ajaxSubmit({
//url: '/admin/photoGroup/ajax_upload_photo', //photo upload process bar
type: 'POST',
dataType: 'json',
data: { data_from_preparing: data_from_preparing},
beforeSend: function() {
//dialog 1
$("#upload-photo-process .progress-bar").css('width', '0');
$('#upload-photo-process').modal('show');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
console.log('percentComplete' + percentComplete);
console.log('position: ' + position);
console.log('total' + total);
var mbPosition = position / 1024 / 1024;
var mbTotal = total / 1024 / 1024;
var txtProcess = percentComplete + '% | ' + mbPosition + 'Mb/' + mbTotal + 'Mb';
var pVel = percentComplete + '%';
$("#upload-photo-process .process-status").html(txtProcess);
$("#upload-photo-process .progress-bar").css('width', pVel);
},
/* complete call back */
complete: function(xhr) {
if (xhr.statusText == "OK") {
$('#upload-photo-process').modal('hide');
$('#upload-done').modal('show');
}
}
/*success: function(data_from_photo_upload) {
}*/
});
Now, i want to when upload progress gain 100%, all of files uploaded to server.
How do i can that?
Thank in advanced.
try this it may work..
//attach
function sendFileToServer(formData, status, file) {
var uploadURL = "index.php?p=ticket-attach&ajax=1"; //Upload URL
var extraData = {}; //Extra Data.
var jqXHR = $.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType: false,
processData: false,
cache: false,
data: formData,
dataType: "json",
success: function(data) {
if (data['error'] == "") {
status.setProgress(100);
status.setFileNameSize(data['fname'].split(",")[0], file.size);
status.appendFN(data['fname']);
//var namef= ;
} else {
//alert(data['error']);
status.errorMsg();
}
}
});
status.setAbort(jqXHR);
}
function createStatusbar(obj) {
this.statusbar = $("<div class='statusbar' id=''></div>");
this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
this.abort = $("<div class='abort'>×</div>").appendTo(this.statusbar);
this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
obj.append(this.statusbar);
this.setFileNameSize = function(name, size) {
var sizeStr = "";
var sizeKB = size / 1024;
if (parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
} else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
this.filename.html(name);
this.size.html("(" + sizeStr + ")");
this.statusbar.attr("sizev", size);
$("#attach_size").attr("sizev", parseInt($("#attach_size").attr("sizev")) + size);
this.setTotalSize();
}
this.setTotalSize = function() {
//set total size
var size = parseInt($("#attach_size").attr("sizev"));
var sizeStr = "";
var sizeKB = size / 1024;
if (parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
} else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
if (sizeStr != "" && size > 0) $("#attach_size").html("(" + sizeStr + ")");
else $("#attach_size").html("");
}
this.setProgress = function(progress) {
var progressBarWidth = progress * this.progressBar.width() / 100;
this.progressBar.find('div').animate({
width: progressBarWidth
}, 10).html(progress + "%");
if (parseInt(progress) >= 100) {
this.progressBar.hide();
if ($.isFunction(tinymce.get)) tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
//this.abort.hide();
} else {
if ($.isFunction(tinymce.get)) tinymce.get('mail_body').isNotDirty = 1;
$("#save_status").html("Not saved");
}
}
this.setAbortFD = function() {
var sb = this.statusbar;
var ts = this;
this.abort.click(function() {
$.ajax({
type: "POST",
url: "index.php?p=ticket-dattach&ajax=1",
data: "fname=" + sb.children(".filename").children("input").val(),
//dataType: "json",
success: function(data) {
tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
},
error: function() {
alert('File is not deleted');
}
});
//alert(sb.children(".filename").children("input").val());
$("#attach_size").attr("sizev", (parseInt($("#attach_size").attr("sizev")) - parseInt(sb.attr("sizev"))));
sb.remove();
ts.setTotalSize();
});
}
this.setAbort = function(jqxhr) {
var sb = this.statusbar;
var ts = this;
this.abort.click(function() {
jqxhr.abort();
if (sb.children(".progressBar").children("div").html() == "100%") {
$.ajax({
type: "POST",
url: "index.php?p=ticket-dattach&ajax=1",
data: "fname=" + sb.children(".filename").children("input").val(),
//dataType: "json",
success: function(data) {
tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
},
error: function() {
alert('File is not deleted');
}
});
$("#attach_size").attr("sizev", (parseInt($("#attach_size").attr("sizev")) - parseInt(sb.attr("sizev"))));
sb.remove();
} else {
sb.remove();
}
ts.setTotalSize();
});
}
this.appendFN = function(fn) {
this.filename.append("<input type=\"hidden\" name=\"ticket_attach[]\" value=\"" + fn + "\" />");
}
this.errorMsg = function() {
var sb = this.statusbar;
sb.children(".progressBar").children("div").html("File Error");
sb.children(".progressBar").show();
sb.children(".filename").children("input").remove()
}
}
function toggle_class(clas) {
$("." + clas).toggle();
}
function insert_attach(input) {
var files = input.files;
$.each(files, function(idx, file) {
var fd = new FormData();
fd.append('ticket_attach', file);
var obj = $(".note-attachbox");
var status = new createStatusbar(obj); //Using this we can set progress.
status.setFileNameSize(file.name, file.size);
sendFileToServer(fd, status, file);
});
$("#afile_browser").val("");
}
.abort {
color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="note-attachbox" id="attachbox" style="position: relative; display: inline;"></div>
<input type='file' id='afile_browser' onchange='return insert_attach(this);' style="opacity: 0; position: relative; display: inline; cursor: pointer; width: 100px; padding: 1px 0px; border: medium none;" multiple>
<div style="cursor: pointer; color: rgb(59, 179, 36); display: inline-block; font-weight: bold; font-size: 20px; vertical-align: middle; background: none; width: auto; padding: 5px 0px; margin-left: -105px;">+<i style="font-size: 15px; font-weight: normal;">Attach files<span id="attach_size" sizev="0"></span ></i>
</div>
Hello You can follow the below approach to get it done.
I have try my best to make the example as simple as possible.
You need to implement this approach in your code to reach the result.
The below code is working and tested.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
User Uploads
Contains user upload details upload_id, image_name, user_id_fk(foreign key) and timestamp etc.
CREATE TABLE `user_uploads` (
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)
Javascript Code
$("#photoimg").live('change',function(){})- photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').live('change', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.
index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple="true" />
</div>
</form>
ajaxImageUpload.php
Contains PHP code. This script helps you to upload images into uploads folder and it will rename image file into timestamp+session_id.extention format to avoid duplicates. This system will store image files into user_uploads with user session id tables
<?php
error_reporting(0);
session_start();
include('db.php');
$session_id='1'; //$session id
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //Image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
} //foreach end
}
?>
db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
CSS
Style for image blocks.
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
Basically I want my tooltip to display company names once company_id is being hovered. However instead of displaying "Company A" for example, it just displays "Company". I realized that it's just printing everything before a space.
Here's the script:
<script type="text/javascript">
$(document).ready(function() {
// Tooltip only Text
$('.masterTooltip').hover(function(){
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>')
.text(title)
.appendTo('body')
.fadeIn('slow');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip')
.css({ top: mousey, left: mousex })
});
});
</script>
and here's my codes
<?php
$companyCtrl = new company_controller();
$companyInfoArr = $companyCtrl->retrieveAllCompanyInfo();
foreach($companyInfoArr as $info) {
$company_id = $info->getCompanyID();
$company_name = $info->getCompanyName();
echo "<a href='#' title=".$company_name." class='masterTooltip'>".$company_id."</a> <br>";
}
?>
There's not problem when i manually enter the text like this
Your Text
In this line:
echo "<a href='#' title=".$company_name." class='masterTooltip'>".$company_id."</a> <br>";
You need to add quotes around the title, so the HTML you're generating will be properly formed. Like this:
echo "".$company_id." <br>";
I have a functional pagination I built but I now have an issue where the amount of data returned is making the pagination large. I have read through a lot of posts about this issue and havent found anything that was decently close to what I thought I needed. I am looking for my pagination bar to limit the pages. Prev 1 2 3 4 5 6 . . . 11 Next Prev 1 . . . 6 7 8 9 10 11 Next
Jquery
$(function() { //Manage Users Table and Search form JS Start
//loads table page 1 upon loading page.
load_table(1);
/*$("#users_table").tablesorter({
debug: true
}); */
//upon search being clicked the table loads at the first page of result set.
$('#user_search_btn').click(function() {
load_table(1);
});
//global var for the clicking of pages and prev and next buttons.
var page = 1;
$('a.page_link').live('click', function() { //gets the number assigned to the data-page and puts it in page var. load table for page
page = $(this).data('page');
load_table(page);
});
$('#prev').live('click', function() {
//truthy loads page 1 if page - 1 equals 0. falsey loads page - 1.
if(page - 1 == 0) {
page = page;
$('#prev a').removeAttr('href');
}
else {
page = page - 1;
load_table(page);
}
});
$('#next').live('click', function() {
//truthy loads page at its current num which is also max_page
if(page + 1 > max_pages) {
page = page;
$('#next a').removeAttr('href');
}
//falsey loads page if hasnt hit max limit yet + 1
else {
page = page + 1;
load_table(page);
}
});
});
//sets gloabl var to use in multiple functions.
var max_pages = null;
function load_table(page_num) { //function to load the table with data from the providers page. passing a page_num for ajax call reuse.
var search_name = $('#user_name_input').val();
var search_email = $('#user_email_input').val();
var search_company = $('#manage_company_input').val();
var admin_option = $('#admin_user_dropdown option:selected').val();
var active_option = $('#active_user_dropdown option:selected').text();
var page_option = $('#page_limit_dropdown option:selected').val();
$.ajax({
type: 'POST',
url: 'providers/manage_users.php',
data: {mode: 'table_data', company: search_company, name: search_name, email: search_email, admin: admin_option, active: active_option, page_limit: page_option, page_num: page_num},
dataType: 'json',
success: function(data) {
if(data.success == true) {
// sets max_pages each to a rounded up number of the total rows divided by the limit.
max_pages = Math.ceil(data.total_rows / page_option);
//clears out previous data in the table and pagination bar
$('#table_body').html('');
$('#pagination_list').html('');
//Cycles through each row of data in the json array and assigns them to vars.
$.each(data.row, function(j, object) {
var group_id = (object.group_id);
var acct_id = (object.acct_id);
var company = (object.company);
var first_name = (object.first_name);
var last_name = (object.last_name);
var name = (first_name + ' ' + last_name);
var email = (object.email);
var city = (object.city);
var admin = (object.admin);
var active = (object.active);
if(active == 1) {
active = 'yes';
}
else {
active = 'no';
}
//sets each row to a single row from json array
row_show(group_id, acct_id, company, name, email, city, admin, active);
});
//checks if only 1 page of data no pagination bar
if(max_pages > 1) {
pagination();
//sets the current page to the active class
$('#page_'+page_num+'').addClass('active');
//makes the previous and next buttons on the bar active class when conditions are met.
if(page_num == 1) {
$('#prev').addClass('active');
}
if(page_num == max_pages) {
$('#next').addClass('active');
}
}
}
}
});
}
function row_show(group_id, acct_id, company, name, email, city, admin, active){ //function to setup the table row and 5 colmuns of data that the ajax call cycles through.
var html = '\
<tr>\
<td><div><a title="'+company+'" id="company_'+group_id+'" href="edit_facility.php?id='+group_id+'">'+company+'</a></div></td>\
<td><div><a title="'+email+'" id="company_'+acct_id+'" href="edit_user.php?id='+acct_id+'">'+email+'</a></div></td>\
<td><div>'+name+'</div></td>\
<td><div>'+city+'</div></td>\
<td><div>'+admin+'</div></td>\
<td><div>'+active+'</div></td>\
</tr>';
//attachs the above data to the table.
$('#table_body').append(html);
}
function pagination() { //function to make the pagination bar
var current_page = 1;
var html = '<li id="prev">‹ Prev</li>';
//loops through each page according to max_pages and gives it a li el and a el
while(max_pages >= current_page) {
html += '<li id="page_'+current_page+'">';
//data-page used later when clicked to get the current page to load in the ajax call.
html += '<a class="page_link" href="#" data-page="'+current_page+'">'+(current_page)+'</a>';
current_page++;
html += '</li>';
}
html += '<li id="next">Next ›</li>';
$('#pagination_list').append(html);
}
HTML
<table id="users_table" class="tablesorter table table-bordered table-condensed">
<thead id="table_head">
<td><strong>Company</strong></td>
<td><strong>Email</strong></td>
<td><strong>Name</strong></td>
<td><strong>City</strong></td>
<td><strong>Role</strong></td>
<td><strong>Active</strong></td>
</thead>
<tbody id="table_body">
</tbody>
</table>
<div id="user_pagination" class="pagination pagination-centered">
<ul id="pagination_list">
</ul>
</div>
CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT
);
jquery_pagination.js
$(document).ready(function()
{
//Display Loading Image
function Display_Load()
{
$("#loading").fadeIn(900,0);
$("#loading").html("<img src="bigLoader.gif" />");
}
//Hide Loading Image
function Hide_Load()
{
$("#loading").fadeOut('slow');
};
//Default Starting Page Results
$("#pagination li:first")
.css({'color' : '#FF0084'}).css({'border' : 'none'});
Display_Load();
$("#content").load("pagination_data.php?page=1", Hide_Load());
//Pagination Click
$("#pagination li").click(function(){
Display_Load();
//CSS Styles
$("#pagination li")
.css({'border' : 'solid #dddddd 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
//Loading Data
var pageNum = this.id;
$("#content").load("pagination_data.php?page=" + pageNum, Hide_Load());
});
});
config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd)
or die("Opps some thing went wrong");
?>
pagination.php
<?php
include('config.php');
$per_page = 9;
//Calculating no of pages
$sql = "select * from messages";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="jquery_pagination.js"></script>
<div id="loading" ></div>
<div id="content" ></div>
<ul id="pagination">
<?php
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
</ul>
pagination_data.php
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$sql = "select * from messages order by msg_id limit $start,$per_page";
$result = mysql_query($sql);
?>
<table width="800px">
<?php
while($row = mysql_fetch_array($result))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
?>
<tr>
<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>
</tr>
<?php
}
?>
</table>
CSS Code
#loading
{
width: 100%;
position: absolute;
}
li
{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}
li:hover
{
color:#FF0084;
cursor: pointer;
}
Try this. It should help you.
I have form like this :
<input type='hidden' name='seq' id='idseq' value='1' />
<div id='add_field' class='locbutton'><a href='#' title='Add'>Add</a></div>
<div id='remove_field' class='locbutton2'><a href='#' title='Delete'>Delete</a></div>
<div id="idcover">
1.<br />
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]'
disabled></div>
</div>
</div>
<br /><br />
<div id='idtotalcover' class='totalcover'>
Total <div class='total'><input type='text' name='total' id='idtotal' disabled /></div>
</div>
This is the jquery script:
<script type="text/javascript">
$(document).ready(
function ()
{
$("input[id^=score],input[id^=weight]").bind("keyup", recalc);
recalc();
var counter = $("#idseq").val();
$("#add_field").click(function ()
{
counter++;
$.ajax({
url: 'addinput.php',
dataType: "html",
data: "count="+counter,
success: function(data)
{
$('#idcover').append(data);
$('.dua input').keyup(function()
{
var $duaInput = $(this);
var weight=$duaInput.val();
var score=$duaInput.closest(".group").find('.satu input').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$duaInput.closest(".group").find('.tiga input').val(data);
}//success
});//ajax
});
}//success
});//ajax
});
});
function recalc()
{
var a=$("input[id^=score]");
var b=$("input[id^=weight]");
$("[id^=weightscore]").calc("(score * weight)/100",{score: a,weight: b},
function (s)
{
return s.toFixed(2);
},
function ($this){
//function($("[id^=weightscore]")){
// sum the total of the $("[id^=total_item]") selector
//alert($this);
//var sum = $this.sum();
var sum=$this.sum();
$("#idtotal").val(sum.toFixed(2));
}
);
}
</script>
This is the php code:
<?
$count=$_GET['count'];
echo"
<br>
$count
<div class='group' >
<div class='satu'>
<input type='text' name='score[$count][]' id='score[$count][]'>
</div>
<div class='dua'>
<input type='text' name='weight[$count][]' id='weight[$count][]'> %
</div>
<div class='tiga'>
<input type='text' name='weightscore[$count][]' id='weightscore[$count][]' disabled>
</div>
</div>";
?>
When I click the Add button, i cant get value on new form so that the new form cannot be calculated. What can i do to get total value on dynamic value ?
I remember reading this exact same question yesterday and I still have no idea of what you're trying to do.
Why are you adding inputs through AJAX instead of creating them in Javascript from the beginning? AJAX calls are expensive and are recommended to be used when you need to update/retrieve values from the server.
Why are you trying to do your calculations on the server side anyway? If you're dealing with dynamic input, you should be doing the calculations client side, then update the server when you're done.
Why do you use obscure name/id attribute values?
Anyway,
I created this example, it contains two different solutions, one with a ul and a table. Hopefully, the example matches what you're trying to do and might give you some insight.
I use a timer to update simulated server data. The timer is set to the variable update_wait. The other dynamic calculations are done client side.
I'll post the Javascript code as well, in case you don't like to fiddle
Example | Javascript
var update_server_timer = null,
update_wait = 1000; //ms
var decimals = 3;
/**********************
List solution
**********************/
function CreateListRow(){
var eLi = document.createElement("li"),
eScore = document.createElement("div"),
eWeight = document.createElement("div"),
eWeightScore = document.createElement("div");
var next_id = $("#cover li:not(.total)").length + 1
eScore.className = "score";
eWeight.className = "weight";
eWeightScore.className = "weightscore";
//Score element
var eScoreInput = document.createElement("input");
eScoreInput.type = "text";
eScoreInput.name = "score_"+next_id;
eScoreInput.id = "score_"+next_id;
eScore.appendChild(eScoreInput);
//Weight element
var eWeightInput = document.createElement("input");
eWeightInput.type = "text";
eWeightInput.name = "weight_"+next_id;
eWeightInput.id = "weight_"+next_id;
var eWeightPerc = document.createElement("div");
eWeightPerc.className = "extra";
eWeightPerc.innerHTML = "%";
eWeight.appendChild(eWeightInput);
eWeight.appendChild(eWeightPerc);
//Weightscore element
var eWeightScoreInput = document.createElement("input");
eWeightScoreInput.type = "text";
eWeightScoreInput.name = "weight_"+next_id;
eWeightScoreInput.id = "weight_"+next_id;
eWeightScore.appendChild(eWeightScoreInput);
$(eScore).keyup(function(){
CalculateListRow($(this).closest("li"));
});
$(eWeight).keyup(function(){
CalculateListRow($(this).closest("li"));
});
//item element
eLi.appendChild(eScore);
eLi.appendChild(eWeight);
eLi.appendChild(eWeightScore);
return eLi;
}
function CalculateListRowTotal(){
var fTotal = 0;
$("#cover li:not(.total) div:nth-child(3) input").each(function(){
var fVal = parseFloat($(this).val());
if(isNaN(fVal)) fVal = 0;
fTotal += fVal;
});
fTotal = parseFloat(fTotal.toFixed(decimals));
$("#cover li.total div input").val(fTotal);
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateListRow($Li){
var fScore = parseFloat($("div.score input", $Li).val()),
fWeight = parseFloat($("div.weight input", $Li).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("div.weightscore input", $Li).val(parseFloat(fRes.toFixed(decimals)));
CalculateListRowTotal();
}
$("#cover li div.weight input, #cover li div.score input").keyup(function(){
CalculateListRow($(this).closest("li"));
});
function AddListRow(){
$("#cover li.total").before(CreateListRow());
RestartUpdateServerTimer();
}
function RemoveListRow(){
$("#cover li.total").prev().remove();
CalculateListRowTotal();
}
$(".left_container .menu .add").click(function(){ AddListRow(); });
$(".left_container .menu .rem").click(function(){ RemoveListRow(); });
/**********************
Table solution
**********************/
function CreateTableRow(){
var eTr = document.createElement("tr"),
eTds = [document.createElement("td"),
document.createElement("td"),
document.createElement("td")];
var next_id = $("#cover2 tbody tr").length + 1;
$(eTds[0]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "score_"+next_id;
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eInput;
});
$(eTds[1]).append(function(){
var eRelativeFix = document.createElement("div"),
eInput = document.createElement("input"),
eExtra = document.createElement("div");
eRelativeFix.className = "relative_fix";
eInput.type = "text";
eInput.name = eInput.id = "weight_"+next_id;
eExtra.innerHTML = "%";
eExtra.className = "extra";
eRelativeFix.appendChild(eInput);
eRelativeFix.appendChild(eExtra);
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eRelativeFix;
});
$(eTds[2]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "weightscore_"+next_id;
return eInput;
});
for(i = 0; i < eTds.length; i++){
eTr.appendChild(eTds[i]);
}
return eTr;
}
function CalculateTableRowTotals(){
var $rows = $("#cover2 tbody tr"),
$totals = $("#cover2 tfoot tr th");
var fTotal = [];
//Each row
$rows.each(function(){
var $columns = $("td", this);
//Each column
$columns.each(function(i, e){
var fVal = parseFloat($("input", e).val());
if(isNaN(fVal)) fVal = 0;
if(isNaN(fTotal[i])) fTotal[i] = 0;
fTotal[i] += fVal;
});
});
for(i = 0; i < fTotal.length; i++){
fTotal[i] = parseFloat(fTotal[i].toFixed(decimals));
}
fTotal[1] = (fTotal[2]/fTotal[0]*100).toFixed(decimals)+"%";
fTotal[2] = parseFloat(fTotal[2].toFixed(decimals));
$totals.each(function(i, e){
$(this).text(fTotal[i]);
});
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateTableRow($Tr){
var fScore = parseFloat($("td:nth-child(1) input", $Tr).val()),
fWeight = parseFloat($("td:nth-child(2) input", $Tr).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("td:nth-child(3) input", $Tr).val(parseFloat(fRes.toFixed(decimals)));
CalculateTableRowTotals();
}
function AddTableRow(){
if($("#cover2 tbody tr").length == 0){
$("#cover2 tbody").append(CreateTableRow());
}else{
$("#cover2 tbody tr:last-child").after(CreateTableRow());
}
RestartUpdateServerTimer();
}
function RemoveTableRow(){
$("#cover2 tbody tr:last-child").remove();
CalculateTableRowTotals();
}
$(".right_container .menu .add").click(function(){ AddTableRow(); });
$(".right_container .menu .rem").click(function(){ RemoveTableRow(); });
$("#cover2 tbody tr td:nth-child(1) input, #cover2 tbody tr td:nth-child(2) input").keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
/**********************
Server data
- Simulates the data on the server,
- whether it be in a SQL server or session data
**********************/
var ServerData = {
List: {
Count: 3,
Total: 5.50
},
Table: {
Count: 3,
Totals: [65, 8.46, 5.50]
}
};
function UpdateServerData(){
//List
var ListCount = $("#cover li:not(.total)").length,
ListTotal = $("#cover li.total input").val();
//Table
var TableCount = $("#cover2 tbody tr").length,
TableTotals = [];
$("#cover2 tfoot th").each(function(i, e){
TableTotals[i] = parseFloat($(this).text());
});
var data = {
json: JSON.stringify({
List: {
Count: ListCount,
Total: ListTotal
},
Table: {
Count: TableCount,
Totals: TableTotals
}
})
}
//Update
$.ajax({
url: "/echo/json/",
data: data,
dataType: "json",
type:"POST",
success: function(response){
ServerData.List = response.List;
ServerData.Table = response.Table;
var displist = "Server data<h1>List</h1><ul><li>Count: "+ServerData.List.Count+"</li><li>Total: "+ServerData.List.Total+"</li></ul>",
disptable = "<h1>Table</h1><ul><li>Count: "+ServerData.Table.Count+"</li>";
for(i=0; i<ServerData.Table.Totals.length; i++)
disptable += "<li>Total "+i+": "+ServerData.Table.Totals[i]+"</li>";
disptable += "</ul>";
$("#server_data").html(displist+"<br />"+disptable).effect("highlight");
}
});
}
function RestartUpdateServerTimer(){
if(update_server_timer != null) clearTimeout(update_server_timer);
update_server_timer = setTimeout(function(){
UpdateServerData()
}, update_wait);
}
UpdateServerData();
Update
Since you have a hard time grasping the concept, here's a copy paste solution that will work for you without having to use AJAX. I would like to point out that your HTML markup and general coding is a total mess...
Example | Code
<script type="text/javascript">
$(document).ready(function(){
function CreateInput(){
var $group = $("<div>"),
$score = $("<div>"),
$weight = $("<div>"),
$weightscore = $("<div>");
var group_count = $("div.group").length+1;
$group.addClass("group");
$score.addClass("satu");
$weight.addClass("dua");
$weightscore.addClass("tiga");
var $input_score = $("<input>"),
$input_weight = $("<input>"),
$input_weightscore = $("<input>")
$input_score
.attr("name", "score["+group_count+"][]")
.attr("type", "text")
.attr("id", "score["+group_count+"][]");
$input_weight
.attr("name", "weight["+group_count+"][]")
.attr("type", "text")
.attr("id", "weight["+group_count+"][]");
$input_weightscore
.attr("name", "weightscore["+group_count+"][]")
.attr("type", "text")
.attr("id", "weightscore["+group_count+"][]")
.attr("disabled", true);
$input_score.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$input_weight.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$score.append($input_score);
$weight.append($input_weight);
$weightscore.append($input_weightscore);
$group.append($score)
.append($weight)
.append($weightscore);
return $group;
}
function CalculateGroup($group){
var fScore = parseFloat($(".satu input", $group).val()),
fWeight = parseFloat($(".dua input", $group).val()),
fWeightScore = parseFloat((fScore*(fWeight/100)).toFixed(2));
if(isNaN(fWeightScore)) fWeightScore = 0;
$(".tiga input", $group).val(fWeightScore);
CalculateTotal();
}
function CalculateTotal(){
var fWeightScoreTotal = 0;
$("#idcover div.group div.tiga input").each(function(){
var fTotal = parseFloat(parseFloat($(this).val()).toFixed(2));
if(isNaN(fTotal)) fTotal = 0;
fWeightScoreTotal += fTotal;
});
fWeightScoreTotal = parseFloat(fWeightScoreTotal.toFixed(2));
$("#idtotalcover div.total input").val(fWeightScoreTotal);
}
$(".satu input, .dua input").keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$("#add_field a").click(function(e){
$("#idcover").append(CreateInput());
e.preventDefault();
});
$("#remove_field a").click(function(e){
$("#idcover div.group:last-child").remove();
CalculateTotal();
e.preventDefault();
});
});
</script>