Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send data with ajax using ckeditore?

I have a form in django. it's 'composing mail' form. I send this form from view to my template and i apply ckeditor to chang the body style. i want this form to be posted by ajax. and when ckeditor is used, value of body field isn't send with request.POST. i use this line of code to use ckeditor:

CKEDITOR.replace('id_body'); 

(without using ckeditor, every thing works fine.)

<form id="compose_form" action="compose/" method="post">
        {% csrf_token %}
        {{ form.non_field_errors }}
        <div>
            <div class="form-field">
                <label for="id_recipient">{% trans 'recipient' %}:</label>
                {{ form.recipient }}               
                {{ form.recipient.errors }}
            </div>
            <div class="form-field">
                <label for="id_subject">{% trans 'subject' %}:</label>
                {{ form.subject }}
                {{ form.subject.errors }}
            </div>
        </div>
        <div class="form-field">
            {{ form.body }}
            {{ form.body.errors }}
        </div>        
            <input id="messages-submit" type="submit" value=""Send"/>
        </div>
    </form>

and i use this script to send form data via ajax:

<script type="text/javascript">
        $(function() {
            $('#compose_form').submit(function() {
                var temp = $("#compose_form").serialize();                
                $.ajax({
                    type: "POST",
                    data: temp,
                    url: 'compose/',
                    success: function(data) {
                      // do s.th
                    }
                });
                return false;
            });
        });
    </script>

with this script, body value isn't send to request.POST(i mean it sends empty string in body field), when i add the below line to my script, it sends value of body field, but it isn't ajax any more. Can you please help me what to do?

like image 258
user1597122 Avatar asked Nov 11 '12 09:11

user1597122


1 Answers

The reason that the data in the editor isn't included in the form is because the editor isn't a part of the form. It needs to update the form element you have associated it with. For this to happen you need to tell the editor to update the form element.

So in the submit function for your form you need to grab data from the editor.

This should do the trick:

$(function() {
        $('#compose_form').submit(function() {
            for (var instance in CKEDITOR.instances)
                CKEDITOR.instances[instance].updateElement();
            var temp = $("#compose_form").serialize();
            etc etc...
like image 169
Sheena Avatar answered Nov 14 '22 19:11

Sheena