Archive for the ‘jquery’ Category

Drag & Drop with PHP & jQuery

The ability to drag and drop content on a page and have it save the order can make for a great user interface and is actually relatively easy to execute with a few lines of jQuery. You’ll need to include the jQuery user interface library which you can find here: Jquery Google API. All the files needed to get this up and running are in the download at the bottom of this post.

In this tutorial we’re going to be looking at 2 main PHP pages. the index.php page which contains the contents and functionality to perform the drag and drop and the updateList.php file which is a simple piece of code to update the listOrder column in the database using PHP and MySQL. Additionally you will need to add your database details to the connect.php file in the download package.


$(document).ready(function(){
	  function slideout(){
  setTimeout(function(){
  $("#response").slideUp("slow", function () {
      });

}, 2000);}

    $("#response").hide();
	$(function() {
	$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update: function() {

			var order = $(this).sortable("serialize") + '&update=update';
			$.post("updateList.php", order, function(theResponse){
				$("#response").html(theResponse);
				$("#response").slideDown('slow');
				slideout();
			});
		}
		});
	});

});

Here’s a summary of whats going on in the code above.

1. To start with we have a simple function that will slide up the ‘response’ div which contains the message once the data is saved in the database.
2. We then move to the section that enables us to drag and drop the boxes. we then set the variable ‘order’ which contains the data to be posted via ajax to our database update script.
3. Once the ajax request has been executed we then display the response in the div #response

This is the section in the index.php page that retrieves the results from the database in the correct order.


 <div id="list">

    <div id="response"> </div>
    <ul>
      <?php
                include("connect.php");
				$query  = "SELECT id, text FROM dragdrop ORDER BY listorder ASC";
				$result = mysql_query($query);
				while($row = mysql_fetch_array($result, MYSQL_ASSOC))
				{

				$id = stripslashes($row['id']);
				$text = stripslashes($row['text']);

				?>
      <li id="arrayorder_<?php echo $id;?>"><?php echo $id;?> <?php echo $text;?>
        <div class="clear"></div>
      </li>
      <?php } ?>
    </ul>
  </div>

Below is the code from the ‘updateList.php’ file. Its pretty self explanatory, we have a MySQL update script wrapped with a foreach loop which adds the list order number in the database and echo’s the response.


<?php
include("connect.php");
$array	= $_POST['arrayorder'];
if ($_POST['update'] == "update"){
$count = 1;
	foreach ($array as $idval) {
		$query = "UPDATE dragdrop SET listorder = " . $count . " WHERE id = " . $idval;
		mysql_query($query) or die('Error, insert query failed');
		$count ++;
	}
	echo 'All saved! refresh the page to see the changes';
}
?>
  • Comments Off

jQuery UI Sortable with TABLE

Drag and drop sorting on a web application? This thought is so far fetched several years ago - and now everybody is or can do that easily with jQuery. Looking at the tutorials and documentation in jQuery’s website, it lays out a simple method to call to make our list to become sortable.


$(function() {
   $("#sortable").sortable();
   $("#sortable").disableSelection();
});

With our corresponding HTML:


<ul id="sortable">
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
</ul>

Here is a demo on how that works.
Now what if we are using TABLE instead of UL or OL??

Easy - Use TBODY tag. So using the example above, let’s convert the list into a table:


<table id=anothersortable>
    <tbody class=content>
        <tr><td>one</td></tr>
        <tr><td>two</td></tr>
        <tr><td>three</td></tr>
        <tr><td>four</td></tr>
    </tbody>
</table>
[sourcecode]

Then our jQuery to be as such:
[sourcecode language="php"]
$(function() {
    $("#anothersortable tbody.content").sortable();
    $("#anothersortable tbody.content").disableSelection();
});
[sourcecode]
Click for demo for the simple table.
You can even make this having sub-sort - or with children sorting. Like this:
[sourcecode language="php"]
<table id=subsortsortable>
    <tbody class=content>
        <tr><td>one</td></tr>
        <tr><td>two</td></tr>
        <tr><td>
            <table><tbody class=subcontent>
                <tr><td>three.one</td></tr>
                <tr><td>three.two</td></tr>
            </tbody></table>
        </td></tr>
        <tr><td>four</td></tr>
    </tbody>
</table>

Adjust our jQuery to be as such:


$(function() {
   $("#subsortsortable tbody.content").sortable();
    $("#subsortsortable tbody.content").disableSelection();
     $("tbody.subcontent").sortable();
    $("tbody.subcontent").disableSelection();
});

Click for demo of this one.

  • Comments Off

While we were working on http://www.duettographics.com Administration control panel, they required the ability to sort their images in easy way, so after some googeling we find many separate tutorials for this. So, we decided to write one simple tutorial that can describe the whole thing.

In this tutorial, we’ll work on sorting menu items.

Requirements : sortable jQuery UI, PHP & MySQL server support.

  1. Create a new MySQL Database called `test_db` and a new table called `menu
    CREATE TABLE IF NOT EXISTS `menu` (
      `id` int(11) NOT NULL auto_increment,
      `title` int(11) NOT NULL,
      `sort` int(2) NOT NULL,
      PRIMARY KEY  (`id`)
    )
  2. Create new php file called “menu_list.php”, this file will be our main file to sort the menu items .

    
    <!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=utf-8" />
    <title>Sorting Items on the fly using jQuery UI, PHP &amp;amp;amp;amp; MySQL</title>
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script>
    <script>
    $(document).ready(
    function() {
    $("#sortme").sortable({
    update : function () {
    serial = $('#sortme').sortable('serialize');
    $.ajax({
    url: "sort_menu.php",
    type: "post",
    data: serial,
    error: function(){
    alert("theres an error with AJAX");
    }
    });
    }
    });
    }
    );
    </script>
    </head>
    <body>
    <h1>Menu List</h1>
    
    <ul id="sortme">
    <?php
    // Connecting to Database
    mysql_connect($hostname, $user_name, $password) or die ('Cant Connceto to MySQL');
    
    // Selecting Database
    mysql_select_db($db_name) or die ('Cant select Database');
    
    // Getting menu items from DB
    $result = mysql_query("SELECT * FROM `menu` ORDER BY `sort` ASC") or die(mysql_error());
    while($row = mysql_fetch_array($result)) {
    echo '<li id="menu_' . $row['id'] . '">' . $row['title_en'] . "</li>\n";
    }
    ?>
    </ul>
    </body>
    </html>
    

    Create a new file for AJAX purpose to update sorting called “sort_menu.php”

    
    <?php
    // Connecting to Database
    mysql_connect($hostname, $user_name, $password) or die ('Cant Connceto to MySQL');
    
    // Selecting Database
    mysql_select_db($db_name) or die ('Cant select Database');
    
    $menu = $_POST['menu'];
    for ($i = 0; $i < count($menu); $i++) {
    mysql_query("UPDATE `menu` SET `sort`=" . $i . " WHERE `id`='" . $menu[$i] . "'") or die(mysql_error());
    }
    ?>
    

    Finally, this should works fine with you, but If you faced any

  • Comments Off
<a href=“#” OnClick=DoAction(1,’Jose’); > Click </a>

Using POST

function DoAction( id, name )
{
    $.ajax({
         type: “POST”,
         url: “someurl.php”,
         data: “id=” + id + “&name=” + name,
         success: function(msg){
                     alert( “Data Saved: “ + msg );
                  }
    });
}

Using GET

function DoAction( id, name )
{
     $.ajax({
          type: “GET”,
          url: “someurl.php?id=” + id + “&name=” + name,
          success: function(msg){
                     alert( “Data Saved: “ + msg );
                   }
     });
}

 
  • Comments Off

jquery simple

#testDiv {
	background-color:#3399CC;
	font: 12px Tahoma, Arial, sans-serif;
	color:#FFFFFF;
	width: 150px;
	height: 100px;
	text-align:center;
}
.testClass {
	background-color:#FF0000;
	font: 12px Tahoma, Arial, sans-serif;
	color:#FFFFFF;
	width: 150px;
	height: 100px;
	text-align:center;
}

* #testDiv และ .testClass ใน css เอาไว้แค่กำหนดหน้าตาเฉยๆ ไม่มีผลกับ jquery

<script src=“jquery.js” type=“text/javascript”><!–mce:0–></script>

เป็นการเรียกโหลด jquery.js เข้ามา

<a onclick=“$(’#testDiv’).show();” href=“javascript:void(0);”>Show</a>
<a onclick=“$(’#testDiv’).hide();” href=“javascript:void(0);”>Hide</a>

ดสำคัญมันอยู่ตรงนี้ onclick=”$(’#testDiv’).show();” คำสั่งนี้คือการ เลือกที่จะทำงานกับ
div (ขึ้นต้นด้วย #) ที่ชื่อว่า #testDiv นั่นเอง

 
<div id=“testDiv”>ข้อความ .. .. .. ข้อความ</div>
<a onclick=“$(’.testClass’).show();” href=“javascript:void(0);”>Show</a>
<a onclick=“$(’.testClass’).hide();” href=“javascript:void(0);”>Hide</a>

ในทำนองเดียวกัน onclick=”$(’.testClass’).show();” คำสั่งนี้คือการ เลือกที่จะทำงานกับ
class (ขึ้นต้นด้วย .) ที่ชื่อว่า .testClass นั่นเอง

 
<div class=“testClass”>ข้อความ .. .. .. ข้อความ</div>
  • Comments Off

อย่างที่ทราบกันครับว่าการส่ง-รับค่าแบบ AJAX นั้นสามารถส่งได้ 2 แบบ คือแบบ POST และ GET ซึ่งก้อเหมือนเราส่งค่าผ่าน HTML Form ธรรมดาทั่วไปนั้นเอง และ jQuery ก้อมีฟั่งชั่นรองรับที่ง่ายแสนง่าย ให้พวกเราใช้งานอยู่แล้วครับเรามาเริ่มกันเลยครับ
การส่ง-รับค่าแบบ POST
แบบที่ 1 (ไม่มีการส่งค่า Parameter)

  1. $.post(“ชื่อไฟล์ที่ต้องการดึงข้อมูล”, function(data){
  2. //คำสั่ง
  3. });

ตัวอย่าง JavaScript ในไฟล์ test.html

  1. $(document).ready(function(){ //เริ่มทำงานเมื่อโหลดเพจเสร็จ
  2. $.post(“test.php”, function(data){ //data จะเก็บค่าที่ return กลับมา
  3. alert(“Data is ”+data); //แสดงข้อความใน Alert box
  4. });
  5. });

โค๊ดในไฟล์ test.php

  1. echo ‘Hi, AJAX’; //return คำว่า ”Hi, AJAX”

ผลที่ได้คือ
0011.jpg
แบบที่ 2 (มีการส่งค่า Parameter)

  1. $.post(“ชื่อไฟล์ที่ต้องการดึงข้อมูล”, [JSON], function(data){
  2. //คำสั่ง
  3. });

ตัวอย่าง JavaScript ในไฟล์ test2.html

  1. $(document).ready(function(){ //เริ่มทำงานเมื่อโหลดเพจเสร็จ
  2. $.post(“test2.php”,{fname: “ทดสอบ”, lname: “นอนสบาย”}, function(data){ //มีการการส่งค่า fname และ lname ไปด้วย
  3. alert(“Data is ”+data); //แสดงข้อความใน Alert box
  4. });
  5. });

โค๊ดในไฟล์ test2.php

  1. $fname = $_POST["fname"]; // รับค่าแบบ POST
  2. $lname = $_POST["lname"];
  3. echo “Hi, {$fname} {$lanme}”; //return ค่าที่รับมาแบบ POST

ผลที่ได้คือ
0021.jpg
การส่ง-รับค่าแบบ GET
สำหรับการส่งแบบ GET นั้นสามารถทดสอบได้ด้วยโค๊ดเดียวกัน เพียงแต่เปลี่ยนจากฟังก์ชั่น $.pos() เป็น $.get() และเปลี่ยนการรับข้อมูลในไฟล์ PHP จาก $_POST เป็น $_GET

  • Comments Off

Time

Mp3

Msn status

  • manon2029@hotmail.com is

Chat with Meeh

Donate

    If you find an article useful, then please make a donation.

หมวดหมู่

UserOnline

Counter

  • Visitors today: 23
  • Visitors yesterday: 48
  • Visitors per day: 1,085
  • Max. visitors per day: 255
  • Total page views: 155,891
  • Page views of this page: 1,085
  • Currently online: 1
  • Max. online: 23
  • Total visitors: 33,987
  • counterStatistics