Welcome Guest, Not a member yet? Register   Sign In
JQuery UI Sortable + CodeIgniter + JSON2
#1

[eluser]sunnyd[/eluser]
I am currently working on a small image organiser. I am using JQuery UI and also using Douglas Crockford json2.js file.

So far I have everything setup properly. Well I hope I have. But when I move an image to a new location, the new image order is not being saved.

database structure:

Code:
-- ----------------------------
-- Table structure for `images`
-- ----------------------------
DROP TABLE IF EXISTS `images`;
CREATE TABLE `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `src` varchar(255) NOT NULL,
  `alt` varchar(255) DEFAULT NULL,
  `order` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of images
-- ----------------------------
INSERT INTO `images` VALUES ('1', 'img1.jpg', null, '1');
INSERT INTO `images` VALUES ('2', 'img2.jpg', null, '2');
INSERT INTO `images` VALUES ('3', 'img3.jpg', null, '3');
INSERT INTO `images` VALUES ('4', 'img4.jpg', null, '4');
INSERT INTO `images` VALUES ('5', 'img5.jpg', null, '5');

Controller Code:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
* @property Img_model $img_model
*/

class Images extends Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('img_model');
        // $this->output->enable_profiler(TRUE);
    }

    public function index() {
        $data['images'] = $this->img_model->get_all_images();
        $this->load->view('list_images',$data);
    }

    public function updateOrder() {

        $data = file_get_contents('php://input');

        $data = json_decode(utf8_decode($data), true);

        $images = $data['d'];

        foreach ( $images as $key => $value ) {
           $id = $value['order'];
           $order = $key;

           try {
               $this->img_model->update_image_order($id , $order);
               // $e = $this->db->query('UPDATE images SET order = '. $order . ' WHERE id = ' . $id);
           }
           catch (Exception $e) {
               echo "failed";
           }
        }

        echo "saved";    

    }

}

Model:

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Img_model extends Model {

    function __construct(){
        parent::__construct();
        
    }

    function get_all_images() {
        $this->db->order_by('order');
        $query = $this->db->get('images');
        return $query->result();
    }

    function update_image_order($id, $order) {

        // die($id . ' ' . $order);
        $this->db->set('order' , $order + 1, FALSE);
        $this->db->where('id' , $id);
        $this->db->update('images');
        // return true;
        // print_r($order);
        // print_r($query);

    }

}
#2

[eluser]sunnyd[/eluser]
HTML:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
&lt;html &gt;
&lt;head&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt;
    &lt;title&gt;Untitled Document&lt;/title&gt;
&lt;style&gt;
    #outerWrap { width:1004px; margin:auto; position:relative; background-color:#eee; border:1px solid #999; }
    #outerWrap:after { content:"."; display:block; visibility:hidden; clear:both; }
    h1 { font:italic normal 24px Georgia, Serif; text-align:center; margin:10px 0; }
    p { margin:0; font:12px Arial, Sans-serif; padding:0 10px; }
    #left { width:218px; float:left; }
    #images { margin:0; padding:0; float:left; width:786px; }
    #images li { list-style-type:none; float:left; cursor:move; margin:10px 10px 0 0; width:200px; height:200px; border:1px solid #999; }
    #images .vacant { border:3px dotted #66d164; width:200px; height:200px; background-color:#ffdead; }
    .success, .failure { margin:0 0 0 10px; padding:4px 0 4px 26px; position:absolute; bottom:18px; font-weight:bold; }
    .success { background:url('&lt;?php echo base_url() . APPPATH; ?&gt;assets/img/tick.png') no-repeat 0 1px; color:#12751c; }
    .failure { background:url('&lt;?php echo base_url() . APPPATH; ?&gt;assets/img/cross.png') no-repeat 0 0; color:#861b16; }
&lt;/style&gt;

&lt;body&gt;


<div id="outerWrap">
    <div id="left">
        <h1>Image Organiser</h1>
        <p>Re-order the images by dragging an image to a new location. Your changes will be saved automatically.</p>
    </div>
    <ul>
        <div id="images">
        &lt;?php foreach ($images as $image): ?&gt;
            <li id='&lt;?php echo $image->id; ?&gt;'><img >src; ?&gt;" alt="&lt;?php echo $image->src; ?&gt;" title="&lt;?php echo $image->src; ?&gt;"/></li>
        &lt;?php endforeach; ?&gt;
        </div>
    </ul>
</div>
[removed][removed]
[removed][removed]
[removed][removed]
[removed][removed]
[removed]
    $(function() {

        //make li sortable
        $("#images").sortable({
            placeholder: "vacant",
            update: function(e, ui) {


                    //create vars
                    var orderArray = [], wrap = {};

                    //reset 'saved' message
                    $(".success", $("#left")).remove();

                    //process each image
                    $("#images img").each(function(i) {

                    //build img object
                    var imgObj = {
                        "id": $(this).parent().attr("id").split("_")[1],
                        "order": i + 1
                    };

                    //add object to array
                    orderArray.push(imgObj);
                    });

                    //wrap in object
                    wrap.d = orderArray;

                    

                    //pass to server
                    $.ajax({
                    type: "POST",
                    url: "images/updateOrder",
                    data: JSON.stringify(wrap),
                    contentType: "application/json; charset=utf-8",
                    success: function(data) {
                        alert(data);
                        if (data === "saved") {
                            $("<p>").text("New order saved!")
                                .addClass("success").appendTo("#left");
                        } else {
                            $("<p>").text("Save failed")
                                .addClass("failure").appendTo("#left");
                        }
                    }
                    });
                    

                  }
              });
    });
[removed]

&lt;/body&gt;
&lt;/html&gt;

Can anyone tell me if my code is wrong somewhere here... cant seem to figure out why its just not saving the new order in the system.
#3

[eluser]Skuja[/eluser]
If you send your data via ajax POST method, then why dont you receive it with CI $this->input->post() method?




Theme © iAndrew 2016 - Forum software by © MyBB