I've figured out how to use a jQuery drag-drop sortable ui. I've also figured out how to populate the jQuery list with time data from my table. But... I'm up against another brick wall.
Following is the script for test.php
<?php
session_start();
// include database connection file, if connection doesn't work the include file will throw an error message
include '../schedule/include/db_connect.php';
$date1 = "10/01/2012";
echo $date1;
// strtotime() will convert nearly any date format into a timestamp which can be used to build a date with the date() function.
$timestamp = strtotime($date1);
$start_date = date("Y-m-d", $timestamp);
$result="SELECT DATE_FORMAT(List_Dates.DB_Date, '%m/%d/%Y') as newdate, DATE_FORMAT(List_Time.TFM_Time,'%h:%i %p') as newtime
FROM List_Dates, List_Time
WHERE DATE(DATE_FORMAT(List_Dates.DB_Date,'%Y-%m-%d')) LIKE '" . $start_date . "%'
ORDER BY List_Time.TFM_Time";
$answer = mysql_query($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Sortable - Connect lists</title>
<link rel="stylesheet" type="text/css" href="../schedule/include/formats.css"/>
<link rel="stylesheet" href="../jquery/themes/custom-theme/jquery.ui.all.css">
<script src="../jquery/jquery-1.7.1.js"></script>
<script src="../jquery/ui/jquery.ui.core.js"></script>
<script src="../jquery/ui/jquery.ui.widget.js"></script>
<script src="../jquery/ui/jquery.ui.mouse.js"></script>
<script src="../jquery/ui/jquery.ui.sortable.js"></script>
<script src="../jquery/ui/jquery.ui.selectable.js"></script>
<style>
#sortable1, #sortable2 { list-style-type: none; margin: 0; padding: 0 0 2.5em; float: left; margin-right: 10px; }
#sortable1 li, #sortable2 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }
</style>
<script>
$(function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable"
}).disableSelection();
});
</script>
</head>
<body>
<div>
<ul name="timelist" id="sortable1" class="connectedSortable">
<?php
while($row = mysql_fetch_array($answer))
{
echo "<li class='ui-state-default'>". $row['newtime'] ."</li>";
}
?>
</ul>
<ul name="blocklist" id="sortable2" class="connectedSortable">
<li id="blocked" type="date" class="ui-state-highlight"></li>
</ul>
</div>
</body>
</html>
As I mentioned earlier, the script is successfully populating a sortable drag-drop list with times from my database. I can drag and drop one time from the left side timelist to the right side blocklist. Now I need to extract an array from the blocklist. I found the following:
<script>
$('ul#myList li').each(function(){
var number = $(this).find('span:first-child').text();
var fruit = $(this).find('span:first-last').text();
});
</script>
For my application it makes sense to change the syntax as follows:
<script>
$('ul#sortable2 li').each(function(){
var btime = $(this).find('span:first-child').text();
});
</script>
But... I can't figure out how to successfully use it and echo the results. Everything I've tried results in failure. Any advice is welcome.
Check the jQuery UI documentation there is a method called toArray which you can call on your sortable element to get, well, an array.
http://jqueryui.com/demos/sortable/#method-toArray
Related
I am echoing records from the database which are wrapped with html tags and was trying to put some effect on the echoed data. When I click the edit link, the textfield should shake. It works on the first element but when I click the edit link of the next element, the first textfield still shakes and not the other one.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wallpost</title>
<style>
.wallpost input[type="text"]{
width: 500px;
height: 20px;
}
.wallpost input[type="submit"]{
height: 26px;
}
.user{
font-weight: bold;
font-size: 20px;
}
.post{
font-family: Arial;
}
a{
text-decoration: none;
}
</style>
</head>
<body>
<?php
require_once 'dbconfig.php';
$user = $_SESSION['user'];;
echo '<form action="post.php" method="post" class="wallpost"><input
type="text" name="post" size="50"><input type="submit" name="wallpost"
value="Post"></form>';
$query = $con->query("SELECT * FROM statuspost ORDER BY id DESC");
while($i = $query->fetch_object()){
//echo $i->post.' '.$i->id.' <a href="wallpost.php?type=post&
id='.$i->id.'" >Remove</a>'.'<br/>';
echo '<span class="user">'.$i->user.'</span>'.'<br>'.'<span
class="post">'.$i->post.'</span>'.' <form action="editpost.php?type=post&
id='.$i->id.'" method="post"><span id="edit"><input type="text"
name="edit">
<br/><input type="submit" value="Edit"></span><a href="#"
onclick="showEdit();">Edit </a><a href="remove.php?type=post&
id='.$i->id.'" >Remove</a></form> '.'<br/><br/>';
//echo '<div id="post">'.$i->post.' '.$i->id.'<a href="#"
id="anchor" class="',$i->id,'" onclick="del();">Remove</a></div>
<br/>';
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0
/prototype.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0
/scriptaculous.js"></script>
<script>
function showEdit(){
Effect.Shake('edit');
}
</script>
</body>
</html>
Replace <span id="edit"> by something like <span id="edit'.$i->id.'"> to have different ids on each elements. Then of course, showEdit() must know which id it has to shake, so it has to take a parameter. Or even simpler: replace onclick="showEdit();" by onclick="Effect.Shake(\'edit'.$i->id.'\');"
Scriptaculous effects take either an ID or a JavaScript reference to a DOM element as their first argument, so if you add a classname to your multiple elements, you can shake all of them at once like this:
<span class="shake-me">...</span>
<span class="shake-me">...</span>
<span class="shake-me">...</span>
Inside an enumerator:
$$('.shake-me').each(function(elm){
Effect.Shake(elm);
});
I tried to use PHP and MySQL to show multiple markers on Google Maps. The code below uses PHP to connect to the database so as to get the latitude and longitude.
The problem is the map doesn't show, but once I delete this line, it works without getting the markers: "var liste_des_points=[<?php echo $listeDesPoints; ?>];". I think the problem is the PHP format.
Please help me with this .
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<?php
$connexion=mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("survey",$connexion) or die(mysql_error());
$result = mysql_query("SELECT latitude, longitude FROM appreciation order by id");
$listeDesPoints='';
while($row = mysql_fetch_array($result)){
if($listeDesPoints!='') $listeDesPoints.=',';
$listeDesPoints.='['.$row['latitude'].','.$row['longitude'].']';
}
mysql_close($connexion);
?>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyB3is760vHXhki9vS_LpiWAig8a33GP3CY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var optionsCarte = {
center: new google.maps.LatLng(34.02,-6.83),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
optionsCarte);
var liste_des_points=[<?php echo $listeDesPoints; ? >];
var i=0,li=liste_des_points.length;
while(i<li){
new google.maps.Marker({
position: new google.maps.LatLng(liste_des_points[i][0], liste_des_points[i][1]),
map: map,
});
i++;
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"> </div>
</body>
</html>
Hi i have a script that when user click load more button, ajax will request new content and
display to users, but i have issue where if all the content has been loaded and if user click load more button it cause bug and repeatedly show multiple load more button.Following is my code, need to know how to resolve this. If there is no content to load the button need to be disabled.Thanks guys !!
ajax_more.php
<?php
include("config.php");
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("select * from messages where mes_id<'$lastmsg' limit 3");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
<?php
}
?>
loadmore.php
<?php
include('config.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Twitter Style load more results.</title>
<link href="frame.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
</script>
<style>
body
{
font-family:Arial, 'Helvetica', sans-serif;
color:#000;
font-size:15px;
}
a { text-decoration:none; color:#0066CC}
a:hover { text-decoration:underline; color:#0066cc }
*
{ margin:0px; padding:0px }
ol.timeline
{ list-style:none}ol.timeline li{ position:relative;border-bottom:1px #dedede dashed; padding:8px; }ol.timeline li:first-child{}
.morebox
{
font-weight:bold;
color:#333333;
text-align:center;
border:solid 1px #333333;
padding:8px;
margin-top:8px;
margin-bottom:8px;
-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
.morebox a{ color:#333333; text-decoration:none}
.morebox a:hover{ color:#333333; text-decoration:none}
#container{margin-left:60px; width:580px }
</style>
</head>
<body>
<div style="padding:4px; margin-bottom:10px; border-bottom:solid 1px #333333; "><h3>Tutorial Link Click Here</h3></div>
<div id='container'>
<ol class="timeline" id="updates">
<?php
$sql=mysql_query("select * from messages LIMIT 3");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
?>
<li>
<?php echo $message; ?>
</li>
<?php } ?>
</ol>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
</div>
</body>
</html>
<?php
include("config.php");
$count=0;
$done=false;
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("select * from messages where mes_id<'$lastmsg' limit 3");
$check=mysql_result(mysql_query("select mes_id from messages ORDER BY mes_id ASC limit 1"));
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
if($row['mes_id']==$check){$done=true;}
$count++;
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
if($count>0 && !$done){
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
<?php
}
}
?>
Explanation: You were unconditionally outputting the more link. With the changes made, the script checks if more than 0 messages have been loaded from the table before outputting a more link. I have also updated it to check if the current batch is the last and not output the more div if it is.
try this code;
$.ajax({
**$("#load_buton").attr("disabled","disabled");**
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").append(html);
$("#more"+ID).remove();
**$("#load_buton").removeAttr("disabled");**
});
In the php section, only display the More button if your returned row size count is greater than 0
Edge cases:
If your database table size increases by n rows, you will repeat n
records each time you hit More
As above, but if records are removed, you will miss out records
Security issues:
SQL injection by sending "0'; truncate messages;--" in the last message post field
Cross site scripting - if users can submit messages with HTML/JavaScript they will be returned in the content without escaping.
In both cases above, use. MySQL escape string ( http://php.net/manual/en/function.mysql-real-escape-string.php ), or use mysqli, and use htmlentities ( http://php.net/manual/en/function.htmlentities.php )
How should I retrieve the uploaded file details from uploadify after the completion of the upload process.
I want to do a process in the uploaded file.
But when I use the uploadify it simply uploads the file to a location through the uploadify.php which I customized.
I want this uploadify process to redirect to a page after completed with the details of the file such as filename and the targeted location where I will proceed with my second operation on the file uploaded
Updates
This is what my code as of now
<style type="text/css">
body {
font: 0.8em/1.6em Arial, Helvetica, sans-serif;
}
fieldset {
width: 500px;
}
#sample {
display:table;
}
#sampleFile {
float: left;
display:table-cell;
margin-right: 15px;
}
#download {
margin-top: 15px;
display: table;
}
.dlImage {
display: table-cell;
float: left;
margin-right: 10px;
}
.dlText {
float: left;
display: table-cell;
}
.fileDetails {
color: red;
}
.releaseDate{
margin-top: -3px;
color: gray;
}
</style>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Uploadify scriptData Sample</title>
<link rel="stylesheet" href="uploadify/uploadify.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#fileUpload").fileUpload({
'uploader': 'uploadify/uploader.swf',
'cancelImg': 'uploadify/cancel.png',
'script': 'uploadify/upload.php',
'folder': 'files',
'multi': false,
'displayData': 'speed',
'onComplete' : function(event, queueID, fileObj, reponse, data) {
location.href="complete.php";
}
});
});
</script>
</head>
<body>
<div id="sample">
<div id="sampleFile">
<fieldset style="border: 1px solid #CDCDCD; padding: 8px; padding-bottom:0px; margin: 8px 0">
<legend><strong>Sélectionner l'image à imprimer :</strong></legend>
<div id="fileUpload">You have a problem with your javascript</div>
Start Upload <p></p>
</fieldset>
</div>
</body>
</html>
on the second page I do want to echo the file name that is uploaded
I have there in the second page complete.php
<?php
print_r($_FILES);
echo $_FILES['type'];
echo $_FILES['tmp_name'];
echo $_FILES['name'];
echo $_FILES['size'];
?>
Do you know that you can get the filename, filpath inside the onComplete event like this:-
onComplete: function(event, queueID, fileObj, reponse, data)
{
alert fileObj.name; //The name of the uploaded file
alert fileObj.filePath; //The path on the server to the uploaded file
location.href= "complete.php?filename="+fileObj.name+"&filepath="+fileObj.filePath; //Here you can do a javascript redirect
}
Check the documentation for further details http://www.uploadify.com/documentation/events/oncomplete-2/
Are you looking for those values? If not let me know
Updates
As per your question updates, you have 2 options.
Either to do the "some process" after the file upload in the uploadify.php. You can see the file uploadify.php which comes with the uploadify plugin. There you have the $_FILES['Filedata'] array containing all the file info. You may do the post processing here itself (by calling a function better instead of writing lots of code in uploadify's core code)
in uploadify.php
$_FILES['Filedata']['name'] //file name
Or like I said, get the file name and path inside the onComplete event. Then pass these params like this :-
location.href= "complete.php?filename="+fileObj.name+"&filepath="+fileObj.filePath;
I think this is better. You may send an ajax request instead to do the entire process (file upload + your "some process") without loading the page again.
Write a $.post() request inside the onComplete event with those parameters and post to "complete.php"
Getting parameters inside onComplete which are not available by default
You have to use the response parameter available inside onComplete
I worked on uploadify version 2.1.0 so my solution will work for sure on that version.
If you want only one parameter, you can echo that at the end of uploadify.php
I did the following thing:-
In my uploadify.php changed (this was in the original uploadify.php):-
move_uploaded_file($tempFile,$targetFile);
echo "1";
to this:-
move_uploaded_file($tempFile,$targetFile);
echo $tempFile;
and then inside the onComplete event did an explode -
var tmpName = reponse;
If however, you want to get more than one parameter inside onComplete, this is a trick I can give (this is not a good approach, but I was not able to return multiple params by any other way - I tried returning json array etc.):-
move_uploaded_file($tempFile,$targetFile);
echo $param1.'%%__%%'.$param2;
and then inside the onComplete event did an explode -
var paramsArray = explode('%%__%%',reponse);
param1 = paramsArray[0];
param2 = paramsArray[1];
you can get all the details of the uploaded file by echoing below line;
print_r($_FIELS);
OR you can echo all the fields of uploded files.
echo $_FIELS['type'];
echo $_FIELS['tmp_name'];
echo $_FIELS['name'];
echo $_FIELS['size'];
i m right if i understood you what you want to saying. but please do comment if you searching for anything else.
Thanks.
I'm using jQuery and $.post(). My code snippet is as follows for chat .php :
<?php
$msg=$_POST['msg'];
mysql_connect("localhost","root");
mysql_select_db("user");
mysql_query("INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')");
?>
and here is the code for my HTML file :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Shout!</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var status=1;
function action() {
if(status==1) {
$("#Layer1").hide("slow");
$("#Layer3").hide("fast");
$("#Layer4").hide("slow");
$("#close").attr("src","open.jpg");
status=0;
}
else if(status==0) {
status=1;
$("#Layer1").show("slow");
$("#Layer3").show("fast");
$("#Layer4").show("slow");
$("#close").attr("src","close.jpg");
}
}
function sendline() {
var msg=$("#msg").val();
$.post("chat.php",{msg:msg});
$("#msg").val(" ");
}
function typeyo() {
var text=$("#msg").val();
$("#Layer6").html(text);
}
</script>
<style type="text/css">
<!--
body {
background-color: #000000;
}
#Layer1 {
position:absolute;
width:200px;
height:115px;
z-index:1;
left: 199px;
top: 3px;
}
#Layer2 {
position:absolute;
width:69px;
height:64px;
z-index:2;
left: 570px;
top: 543px;
}
#Layer3 {
position:absolute;
width:131px;
height:91px;
z-index:3;
left: 487px;
top: 327px;
}
.style1 {
color: #FFFFFF;
font-family: "Segoe UI";
font-weight: bold;
}
#Layer4 {
position:absolute;
width:99px;
height:38px;
z-index:4;
left: 744px;
top: 485px;
}
#Layer5 {
position:absolute;
width:274px;
height:70px;
z-index:5;
left: 422px;
top: 62px;
}
#Layer6 {
width:638px;
height:356px;
z-index:5;
left: 352px;
top: 105px;
}
-->
</style></head>
<body>
<div class="style1" id="Layer3">
<textarea name="textarea" cols="30" rows="5" id="msg" ></textarea>
</div>
<div id="Layer1">Hello World!<img src="body.jpg" width="842" height="559" /></div>
<div id="Layer2"><img src="close.jpg" alt="Go Online/Offline" name="close" width="63" height="64" id="close" OnClick="action()"/></div>
<div id="Layer4">
<input type="button" value="Send Line" onclick="sendline()" /></div>
<div id="Layer6" style="color:white;font-family:Segoe UI;font-size:16px;width:500px; height:400px; overflow:auto;"></div>
</body>
</html>
Now,there seems to be some problem posting the variable msg.Im using chat.php for $.post() on the HTML code that i've provided.
There seems to be a problem with sending the "msg" here . The chat.php file is fine since if we run it directly ,and not thorugh a $.post() call it works perfectly
Kindly Help! thank you!
Your msg variable that you try to send via POST is not initialized,
add the following line at the beginning of your sendline function:
var msg = $("#msg").val();
Note: you have a big/huge security issue inserting variables from POST in MySQL queries without prior treatment.
update: I suggest you use a javascript debugger, set a breakpoint at the beginning of function sendline() and step through the code. Which one to use depends on your browser(s).
Firefox -> e.g. Firebug
IE7 -> e.g. IE Developer Toolbar
IE8+ -> just press F12 to open the developer tools that are shipping with IE.
In addition to darma's answer: Your php script is prone to sql injections (intentional/malicious as well as unintentional ones). Either use prepared, parametrized statements or escape the data properly.
working example:
test.html:
<html>
<head><title>test.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function sendline() {
var msg = $('#msg').val();
// --- add some tests on msg here, e.g. msg=="" ---
$.post(
"chat.php",
{'msg':msg},
function(data, textStatus, req) { $('#reply').text('reply: ' + data); }
);
}
</script>
</head>
<body>
<div>
<textarea id="msg" rows="5" cols="30" name="textarea"></textarea>
<button onclick="sendline()">send line</button>
</div>
<div id="reply"> </div>
</body>
</html>
chat.php:
<?php
// --- add some tests on $_POST['msg'] here
// e.g. isset($_POST['msg']) and 0<strlen(trim($_POST['msg'])) ---
// you might want to use a slightly more sophisticated error handling than "or die(mysql_error())" ...but this is only an example.
$mysql = mysql_connect("localhost","localonly", "localonly") or die(mysql_error());
mysql_select_db("test", $mysql) or die(mysql_error());
$msg=mysql_real_escape_string($_POST['msg'], $mysql);
$sql = "INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')";
// mysql_query($sql, $mysql) or die(mysql_error());
echo htmlspecialchars($sql);
update2: You still don't have any error handling in your php script. Any of the mysql_* function can fail for various reasons; test the results. You need to "see" those errors, e.g. by writing them to a log file or something...
Try
<?php
define('LOGERRORS', 1);
function dbgLog($text) {
if (LOGERRORS) {
error_log(date('Y-m-d H:i:s : ').$text."\n", 3, 'error.log');
}
}
if ( !isset($_POST['msg']) ) {
dbgLog('script called without post parameter "msg"');
die();
}
$mysql = mysql_connect("localhost","root");
if ( !$mysql ) {
dbgLog('database connection failed: '.mysql_error());
die();
}
$result = mysql_select_db("user", $mysql);
if ( !$result ) {
dbgLog('database selection failed: '.mysql_error($mysql));
die();
}
$msg=mysql_real_escape_string($_POST['msg'], $mysql);
$sql = "INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')";
dbgLog('sending query: '.$sql);
$result = mysql_query($sql, $mysql);
if ( !$result ) {
dbgLog('query failed: '.mysql_error($mysql));
die();
}