2013年3月11日 星期一

[Django] refresh div with JQuery

Example:

Template 1 

<script>

function refresh_infos(element){
    var id = "test"
    $.ajax({
        type: "POST",
        url: '/part_update/',
        data: {'id':id},
        success: function(data) {
            $('#testDIV').html(data);
        }
    });
}
</script>
<div id="testDIV"></div>



View 

def part_update(request):

    id = request.POST.get('id', "")
   
    #/* get infomation */
    infos = DB.objects.filter(id = id)
   

    return render_to_response('supply/template.html', { 'infos': infos })

Template 2 
    {% for info in infos %}
        <p>{{ info.id }}</p>
    {% endif %}


Urls 
    adding:
    (r'^/part_update/$','part_update'),

2013年3月9日 星期六

[Codeigniter]ajax upload


Simple Example:

Controller:

public function upload_file(){
        $file_element_name = $_POST['file_element_name'];
        $config['file_name'] = "test.jpg";
        $config['upload_path'] = "/upload/";
        $config['allowed_types'] = 'gif|jpg|png|doc|txt|pdf';
        $config['max_size']  = 1024 * 8;
        $config['encrypt_name'] = FALSE;
        $config['remove_spaces'] = TRUE;
        $this->load->library('upload', $config);
            if (!$this->upload->do_upload($file_element_name)){
                $status = 'error';
                $msg = $this->upload->display_errors('', '');
            }else{
                $data = $this->upload->data();
                $file_id = true;
                if($file_id){
                    $status = "success";
                    $msg = "File successfully uploaded";
                }else{
                    unlink($data['full_path']);
                    $status = "error";
                    $msg = "Something went wrong when saving the file, please try again.";
                }
            }
            @unlink($_FILES[$file_element_name]);
        }
        $upload_info = $this->upload->data();
        echo json_encode( array(
            "status" => $status,
        ));
}


View:

<form method="post" action="" id="form">
        <input type="file" name="file" id="file" />
</form>

<script type="text/javascript">
    $(function() {
        $('#form').submit(function(e) {
            $.ajaxFileUpload({
                url         :'<?=site_url("upload/")?>',
                secureuri      :false,
                fileElementId  :'file',
                dataType    : 'json',
                data        : {
                    'file_element_name' : 'file'
                },
                success  : function (data){
                    alert(data.status);
                }
            });
            return false;
      });
    }
</script>