简体   繁体   中英

Ajax doesn't send the value of a textarea (CKEditor) on the first try, but it sends it on the second try

I have a textarea in my HTML that loads CKEditor 4. Then I will send the data of my HTML form to a PHP file that processes the inputs.

       $.ajax({
            xhr: function(){
                //blah blah blah
                return XHR;
            },
            type: "POST",
            url: "process.php",
            data: formData,
            processData: false,
            contentType: false,
            mimeType: "multipart/form-data",
            success: function (response) {
                //blah blah blah
            },
            error: function(XHR, textStatus, error){
               //blah blah blah
            }
        });

In the PHP file, I first sanitize all the inputs and then pass them to the database. It turns out that the value of the textarea in my page, which its name is "description", is not sent via ajax the first time that I press the submit button (I have verified this by writing the content of $_POST[] in a file on the server to facilitate the debugging process) but the second time I press the submit button on my HTML form, the value of the description textarea is sent with no issue!

I first assumed that it can be due to the fact that the value of the description textarea contains HTML codes and it is sanitized by PHP. But I removed the sanitation thing for it and the problem persisted. I have written thousands of lines of code so far, but I won't mind revealing more codes if need be. I just avoided to do so to prevent this post from becoming unnecessarily long.

Any help is appreciated. Thanks in advance.

Edit This is how I fill the formData variable:

   $("#form").submit(function (event) {
        event.preventDefault();
        var formData = new FormData(this);
        loading_start();
        submitForm(formData);
    });

And I need to upload files simultaneously during the submission of this form.

如果不需要将文件上传到服务器,请尝试使用.val()函数获取textarea内容。

I found the issue causing this weird behavior. For future reference, CKEditor needs to be updated before you can submit the value of the textarea that holds its data. To force CKEditor to update itself, you can use the following code:

   for(var instanceName in CKEDITOR.instances)
            CKEDITOR.instances[instanceName].updateElement();

The credit for the above code goes to the user who has posted it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM