Sagar Chhaniyara
Sagar Chhaniyara

Reputation: 35

Ajax code issue

I have the following code:

function add_post() {
    if (document.getElementById("blogTitle").value.trim() == "") {
        alert("Please Insert Blog Title");
        return;
    }

    if(CKEDITOR.instances.editor1.getData() == "") {
        alert("Please Insert Blog Details");
        return;
    }

    var data = new FormData(document.getElementById("file_add"));
    var xhr = new XMLHttpRequest();
    var de=CKEDITOR.instances.editor1.getData();  
    xhr.open("POST", "upload.php", false)
    xhr.send(data + "&de=" + de);

    if (xhr.status == 200) { 
        alert(xhr.responseText);
        if(xhr.responseText == 2) {
            document.getElementById("res").innerHTML="Please Upload The File";     
        }

        if(xhr.responseText == 1) {
            document.getElementById("res").innerHTML="Blog Created"; 
            document.getElementById("blogTitle").value="";
            document.getElementById("editor1").value="";   
        }
    }
    else {
        output.innerHTML += "Error " + xhr.status + " occurred uploading your file.<br />";
    }  
}

I am using CKEDITOR in textarea to get formated text. I use CKEDITOR.instances.editor1.getData() to get the textarea value. On other hand I have used FormData because I want to upload form and file using ajax. I tried to send data but the data couldn't be sent. I have stored textarea value in de variable.

Upvotes: 1

Views: 87

Answers (1)

Quentin
Quentin

Reputation: 943537

Your form data object is not a string. You can't just concatenate more data into it with +.

Replace:

xhr.send(data+"&de="+de);

with

data.append("de", de);
xhr.send(data);

Upvotes: 2

Related Questions