Welcome Guest, Not a member yet? Register   Sign In
jquery post & serialize
#1

[eluser]Wimm_vw[/eluser]
Working with jquery ui 1.8.5 & jquery 1.4.2

View
Code:
[removed]
$(document).ready(function() {
$("#list").sortable({
handle : '.handle',
update : function () {  
$("#info").post("/gallery/sortable", $('#list').sortable('serialize'));
}
});
});
[removed]

and in the body
<pre><div id="info">Waiting for update</div></pre>
                    
<ul id="list">
<li id="listItem_1">
<img src="assets/images/arrow.png" alt="move" width="16" height="16" class="handle" /> 5db7b2181d4ab70e90321b91b4ee0b76.jpg</li>

...........
</ul>


Controller
Code:
function sortable()
{
  print_r($_POST);        
}

Getting no result in my info-div.

Something's going wrong with the post method?
#2

[eluser]slowgary[/eluser]
Hi Wimm_vw,

This is a Javascript problem, not a CodeIgniter problem. That may be why you haven't gotten any responses. That being said, the problem is that you can't call the jQuery $.post() method on an element. It works like this:
Code:
&lt;script&gt;
$.post(
     '/gallery/sortable',
     $('#list').sortable('serialize'),
     function(data, textStatus){
          if(textStatus == 'success'){
               $('#info').html(data);
          }
     }
);
&lt;/script&gt;
#3

[eluser]Wimm_vw[/eluser]
Great that works! Thanks a lot! Really :-)
#4

[eluser]boldyellow[/eluser]
I'm also wrestling with sortable list items (big surprise, I'm a designer who's not JS saavy and still learning CI).

And yet... it kinda works: list items drag and the array is echoed in the #info box.

But the row order does not update in the database. And it doesn't seem very MVC (it calls on a separate PHP file).

It's not gonna be a long list, so performance is not huge concern.


Database: gallery_names
Code:
| id  |  name  |  order |


View
In the view header:
Code:
$(document).ready(function() {
    $("#sortable-list").sortable({
      update : function () {
          var order = $('#sortable-list').sortable('serialize');
          $("#info").load("http://localhost/ci/process-sortable.php?"+order);
      }
    });
});

And in the view body:

Code:
<div id="info">Waiting...</div>

<ul id="sortable-list">
    <li id="listfield_01">Gallery 1</li>
    <li id="listfield_02">Gallery 2</li>
    <li id="listfield_03">Gallery 3</li>
</ul>


Separate PHP File: process-sortable.php

Code:
foreach ($_GET['listfield'] as $order => $item) :
    $sql[] = "UPDATE `gallery_names` SET `order` = $order WHERE `id` = $item";
endforeach;

echo '<pre>';
print_r ($sql);
echo '</pre>';


Taking a stab here...

When the header script posts, it should go to the controller which gets the $_POST.

The controller loads a model with a variation of the process-sortable code and updates the db(?)

Thanks for any guidance!
#5

[eluser]slowgary[/eluser]
By default, CodeIgniter deletes the $_GET array. By using a separate file, you're getting around that but as you mentioned, it won't be very MVC.

What do you mean by "the order doesn't update in the database"? Have you tried to execute the query? process-sortable.php doesn't seem to do that, unless there's more that you haven't pasted.
#6

[eluser]InsiteFX[/eluser]
Code:
$str_get = parse_str($_SERVER['QUERY_STRING'], $_GET);

InsiteFX
#7

[eluser]boldyellow[/eluser]
Thanks for the followup slowgary.

Quote:By default, CodeIgniter deletes the $_GET array. What do you mean by "the order doesn't update in the database"?

I have an "order" column in my table. So my original query outputs the sequence of the list items (ORDER_BY order ASC).

The list items drag and drop fine with JQuery Sortable.

But after the list items are moved to new positions in the ul, the order column is not updated in the db with the new sequence.

As far as executing the query, I'm trying to understand in MVC terms how the JQuery actions trigger an update to the db after the list items get moved around.
#8

[eluser]slowgary[/eluser]
I see. There are a few things I'd recommend... let's walk through the JS first so you get a better understanding of what's going on.

The first line of your Javascript is referred to as "on DOM ready". This means that the code within will be run as soon as all of the HTML has been downloaded, but before all of those bulky images are downloaded. That's the best time to run your Javascript, as in most cases you can't run it any sooner but very infrequently do you want to wait for all of the images to load. There's actually a shorter version of what you are using:
Code:
// your version.  all of your DOMready code goes between these two lines:
$(document).ready(function(){
     // code here
});
// shorter version... does the exact same thing:
$(function(){
     // code here
});

Next, you basically just have one call to jQueryUI's sortable() function, which takes a collection of list-items and makes them sortable, offering a bunch of other features to ease development. Now you need to call the sortable() method on a jQuery object, which is really just a reference to a specific place in your document, or a collection or these references. In your case, sortable expects that you're calling it on an unordered list <ul> I believe (correct me if I'm wrong). This is where the dollar sign function comes into play $().

Something you should know is that every time you call the dollar sign function, you're asking jQuery to traverse through your entire document (every single tag) finding matching elements. In some cases, this can be quick, like in the case below. This is because you're passing it an ID, which is unique and maps directly to only object which can be retrieved using Javascript's native document.getElementById('#myID'); In other cases, you may be asking jQuery to do a LOT of traversing and checking on elements. In all cases, regardless of how easy or difficult the selection may be, it's recommended that you CACHE the selection. This can be done very simply:
Code:
var my_variable_name = $("#sortable-list");
// or:
var $my_sortable = $("#sortable-list");
// usually it's a good idea to start your variable names with a dollar sign when they refer to a jquery object, then you (or anyone else) will always know what it points to
By caching the selector, you can now avoid asking jQuery to do the DOM traversal unnecessarily. In your case, you've already made the same call twice (" $('#sortable-list') "). Here's your code with the changes so far:
Code:
$(function(){
     var $my_sortable = $("#sortable-list");
     $my_sortable.sortable({
          update: function(){
               var order = $my_sortable.sortable('serialize');
               $("#info").load("http://localhost/ci/process-sortable.php?"+order);
          }
     });
});
Now sortable(), just like many plugins, has many possible parameters that you can pass it. In your case, you're only passing it one. That's the 'update' parameter, which is a callback function that gets called after an update is made. In your callback function, you've captured the serialized list data and passed it to "process-sortable.php" by making a call to jQuery's load() method. You're doing two things here, calling the serverside script, and sticking the output from that script into the element on your current page with an ID of #info.

Where the problem appears to lie is that nowhere in your "process-sortable.php" are you ever actually executing that SQL statement. It appears that it is just being displayed on the page.

What I would recommend is to copy that query and paste it into something like phpMyAdmin and see if it executes without any errors. If it works, all you need to do is actually execute it in your serverside script instead of printing it to the screen.

As far as the MVC portion of it is concerned, the idea would be to take whatever code you have that's processing the sortable list data and put that into one of your CodeIgniter controllers. Then in the controller, do whatever preprocessing you might need to do to the data before passing it to a model for saving to the database.

I hope this helps. Let us know.
#9

[eluser]boldyellow[/eluser]
Wow... thanks slowgary for that thorough education to get me oriented... you should offer college credits...or charge tuition.

Based on your explanation, I tweaked and tested (and googled) to get the jQuery Sortable working in a procedural fashion.

View
Header script:
Code:
$(function(){
    var $my_sortable = $("#sortable-list");
    $my_sortable.sortable({
        handle : '.grabber',  // this is an icon users use to move the list item
        update : function () {
             var order = $my_sortable.sortable('serialize');
             $.post('http://localhost/ci/process-sortable.php', order);
        }
    });
});

Body is same:

Code:
<ul id="sortable-list">
    <li id="listfield_01">Gallery 1</li>
    <li id="listfield_02">Gallery 2</li>
    <li id="listfield_03">Gallery 3</li>
</ul>


Separate PHP File: process-sortable.php

Code:
// conn to the db here
$position = $_POST['listfield'];
for ($i = 0; $i < count($position); $i++) {  
    mysql_query("UPDATE `gallery_names` SET `order`=" . $i . " WHERE `id`='" . $position[$i] . "'");  
}


Now I'll work on translating this code into a more MVC-friendly format.

If (or more likely, when) I hit a wall, I'll post back. Thanks again!




Theme © iAndrew 2016 - Forum software by © MyBB