SitePoint Sponsor

User Tag List

Results 1 to 10 of 10
  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Post Jquery, PHP, MySQL - Sortable List

    I am trying to make a sortable list with Jquery that updates my database with the positions of each item in a list. I know PHP, but I don't know JQuery at all and I was hoping someone could help me get on the right track.

    I searched around on the web and found this example in different forums, but it doesn't seem to work for me.

    Here's my xhtml list:
    HTML Code:
    <ul id="sortme">
     <li id="foo_1" class="sortitem">Lorem</li>
     <li id="foo_2" class="sortitem">Foo</li>
     <li id="foo_3" class="sortitem">Bar</li>
     <li id="foo_4" class="sortitem">Ipsum</li>
    </ul>
    
    <div id="data" style="background-color: #CCCCCC; padding: 15px; border:solid 1px #999;">
    </div>
    Here is my JavaScript:
    Code:
    <script type="text/javascript">
      $(document).ready(function() {
        $("#sortme").sortable({
          accept : 'sortitem',
          onchange : function (sorted) {
          serial = $.SortSerialize('sortme');
    	  
         $.ajax({
                      url: "sortdata.php",
                      type: "POST",
                      data: serial.hash,
                      complete: function(feedback){ $('#data').html(feedback); },
                      success: function(feedback){ $('#data').html(feedback); },
                      error: function(feedback){ $('#data').html(feedback); }
                  });
    	
    
              }
          });
     	}
    );
    </script>
    Here's my PHP:
    PHP Code:
    <?php require_once ("connection.php"?>
    <?php 
    require_once ("function.php"?>
    <?php
    $sortme 
    $_POST['sortme'];
    for (
    $i 0$i count($sortme); $i++) {
      
    mysql_query("UPDATE images SET position=$i WHERE id=$sortme[$i]");
    }
    ?>
    So, from what I understand, Serialize should pass the lists Id's as an array via Post data to my PHP script: sortdata.php. Then I should use PHP to grab the Post data from the Array? Let me know if this is right or if I am way off.

    How do I tell what the Javascript is actually sending sortdata.php and what format it is really in? To me it looks like it should return something to the #data DIV, but right now it isn't.

    Right now the script isn't working, and I don't know how to debug it to see if it's the Javascript that's wrong or if it's my update statement with my PHP. Any advice/help would be appriciated...thanks.

  2. #2
    ♪♪ ♪ ♪ ♪ ♪♪ ♪ ♪♪ Markdidj's Avatar
    Join Date
    Sep 2002
    Location
    Bournemouth, South UK
    Posts
    1,551
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    There is another way to do this, which would use your current php script, and work with or without javascript.
    The commented lines you will need to code yourself.
    Code:
    <?php
     
    if(isset($_GET["live"])) $live=$_GET["live"]; else $live=0;
    if(isset($_GET["sort"])) $sort=$_GET["sort"]; else $sort=$string;
     
    //----validate input----//
     
    if($live==1){
     
    //----output javascript headers----//
     
    } else {
     
    //----output html headers if needed----//
     
    }
     
    //----calculate and sort outputHTML----//
     
    if($live==1){
    echo "document.getElementById(\"area\").innerHTML=\"".str_replace("\"","\\\"",$outputHTML)."\""
    } else {
    echo $outputHTML
    }
    The replace on outputHTML for the javascript output may have to be played around with as I didn't test it, but as your echoing a javascript string you will need to escape all quotes.

    There are 2 ways to trigger the output. If you want search engines to index it, use links;
    Code:
    <a href="index.php?sort=lorem" title="Sort By Lorem">Lorem</a>
    this can be sent using javascript by using the changeScript function (http://www.sitepoint.com/forums/showthread.php?t=201860)
    Code:
    <a href="index.php?sort=lorem" title="Sort By Lorem" onclick="changeScript('index.php?sort=lorem&live=1')">Lorem</a>
    If you don't wish the sorts to be indexed by search engines, as they may not be enough changes to the page, then you can use submit inputs instead;
    Code:
    <input type="submit" value="Lorem" onclick="changeScript('index.php?sort=lorem&live=1')">
    Hope it's of interest
    LiveScript: Putting the "Live" Back into JavaScript
    if live output_as_javascript else output_as_html end if

  3. #3
    SitePoint Enthusiast
    Join Date
    Aug 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply, but I am trying to use jQuery. Plus, maybe I am wrong, but I don't think this is really what I am looking for. I'd rather stick with the example I originally posted.

  4. #4
    SitePoint Enthusiast
    Join Date
    Aug 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK, I changed my UL to:
    HTML Code:
    <ul id="myList">
     <li id="foo_1" class="sortitem">Lorem</li>
     <li id="foo_2" class="sortitem">Foo</li>
     <li id="foo_3" class="sortitem">Bar</li>
     <li id="foo_4" class="sortitem">Ipsum</li>
    </ul>
    and my JavaScript to this:
    Code:
    <script type="text/javascript">
    
      $(document).ready(function() {
        $("#myList").sortable({
            update : function(e, ui)
            {
                serialize("#myList");
            }
        });
      });
      
      function serialize(s) {
        var str = [];
    	for(i=1; i< $('#myList').children().size(); i++) {
       	  var key = 'position['+i+']=';
    	}
        var delimiter = '&'
    	
        $(s + "> *").not('.ui-sortable-helper').each(function() {
    	  str.push(key+this.getAttribute('id'));	
        });
    	
        $("#data").html(str.join(delimiter));
    	
      }; 
    
    </script>
    it outputs something like this in the #data div:
    position[4]=foo_2&position[4]=foo_1&position[4]=foo_3&position[4]=foo_4

    How do I get the position[i] to increment each time instead of just being the total number of <li> elements?

    I have no idea if I am on the right track, but I thought if I could get an array like this, I could use grab the key/values in PHP.

    I really could use the help if anyone is willing to give me some advice. Thanks

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    The for loop appears to be in the wrong place. I think that it should be in the function that pushes the value onto the array, where the for loop checks if the current element is the same as one from the set that its looping through.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    SitePoint Enthusiast
    Join Date
    Aug 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the response! Well, I am slowly getting closer.

    The JavaScript outputs the correct string now, but how do I grab it as Post data in my PHPscript: sortdata.php?

    if I copy the string that the JavaScript outputs, and manually add it to my script, the script works and updates the database:
    PHP Code:
    $myList "'1'=>' 30 ', '2'=>' 23 ', '3'=>' 31 ', '4'=>' 32 '"
    but if I try to use:
    PHP Code:
    $myListPost $_POST['myList']; 
    it doesn't work.

    Here is the JavaScript:
    Code:
      function serialize(s) {
        var str = [];
    	var i=1
        var delimiter = ', '	
        $(s + "> *").not('.ui-sortable-helper').each(function() {	 
       	  var key = '\''+i+'\'=>';	
    	  str.push(key+'\''+this.getAttribute('id')+'\'');
    	  i++	  
        });
    	
    	 $.ajax({
                      url: "sortdata.php",
                      type: "POST",
                      data: str.join(delimiter),
                     // complete: function(){ $('#data').html(); },
                     // success: function(feedback){ $('#data').html(); },
                     // error: function(){ $('#data').html(); }
    	   });
    	
        $("#data").html(str.join(delimiter));	
      };
    Any ideas?

  7. #7
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    It's time now to move this post to the PHP forum.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  8. #8
    SitePoint Enthusiast
    Join Date
    Aug 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cool!

  9. #9
    SitePoint Enthusiast
    Join Date
    Aug 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One more question, that pertains to the JavaScript side of this.

    I got the jQuery to output the actual post data and it it is escaping some of the html, like the ">". Why would it do that?

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    jquery does that so that you can see those characters instead of having them be interpreted as html tag markers.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •