0

I'm trying to submit a form using JavaScript one my tests have been completed. I keep on getting a JavaScript error saying Uncaught TypeError: formElement.submit is not a function.

This is my code where the event listener is added:

window.onload = function () 
{ 
    //Event Listeners
    var messageForm = document.getElementById("messageForm");
    messageForm.addEventListener("submit",handleSubmit);
}

This is my function, the error is occurring when executing formElement.submit();. Here is my entire function:

function handleSubmit(ev) {
    //Prevent default form submittion
    ev.preventDefault();

    //Validate the form
    var isValid = validation(this), 
                error, 
                formElement = this,
                submitButton = this.querySelector("input[type=submit]");

    //Check if validation passes
    if (isValid == true) {
        //Check if a file has been selected
        var file = this.querySelector("input[type=file]");

        if (file != "") {
            //Generate a new form
            var f = document.createElement("form");
            f.setAttribute("method", "POST");
            f.setAttribute("enctype", "multipart/form-data");

            //Create FormData Object
            var formData = new FormData(f);

            //Append file
            formData.append("image", file.files[0], "image.jpg");
            formData.append("source", "message");

            //Uploaded
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "php/uploadImage.php", true);
            xhr.onload = function(e) {
                if (xhr.status == 200) {
                    //Parse XML response
                    if (window.DOMParser)
                    {
                        parser=new DOMParser();
                        xmlDoc=parser.parseFromString(xhr.responseXML,"text/xml");
                    }
                    else // Internet Explorer
                    {
                        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.async=false;
                        xmlDoc.loadXML(xhr.responseXML);
                    }

                    var imageuploaded = xmlDoc.getElementsByTagName("uploaded").nodeValue;
                    var imageerror = xmlDoc.getElementsByTagName("imageerror").nodeValue;

                    if (imageuploaded != "") {
                        formData.append("location",imageuploaded);
                        formElement.submit();
                    } else {
                        message = "Error uploading image: " + imageerror;
                    }
                } else {
                    message = "Unable to submit form! Please contact admin: " + xhr.description;
                }
            };

            //Progress
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var currentPercentage = Math.round(e.loaded / e.total * 100)-1;
                    submitButton.innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
                    submitButton.style.backgroundSize = (currentPercentage+1) + "% 100%";
                    if (currentPercentage==99) {
                        submitButton.innerHTML = "Processing image";
                    }
                }
            };

            //Send data
            xhr.send(formData);

        } else {
            //Submit form with no file
            this.submit();
        }
    } else {
        //Validation failed
        ev.preventDefault();

        message = "Error: Please ensure you have completed required information!";
    }
}
Martyn Ball
  • 4,679
  • 8
  • 56
  • 126
  • 1
    [I highly suggest you to use jQuery for AJAX requests instead of vanilla XHR requests since it has been built to be the most cross-compatible with every browser.](http://api.jquery.com/jquery.ajax/) – GiamPy Sep 13 '15 at 20:24
  • So `formElement` is always a `
    ` element?
    – Bergi Sep 13 '15 at 20:28
  • 1
    @GiamPy: afaik, jQuery neither handles `FormData` well nor enables `onprogress` handlers. But really there's no need to include jQuery just for a bit of XHR. – Bergi Sep 13 '15 at 20:29
  • [Yes you can @Bergi](http://stackoverflow.com/a/8244082/2362433) – GiamPy Sep 13 '15 at 20:31
  • Btw, `xhr.responseXML` *is* an xml document. No need to parse it using a `DOMParse` or the M$ equivalent. If you really would need to do that, you at least should parse the `.responseText`. – Bergi Sep 13 '15 at 20:31
  • [You should have a look a this question anyway.](http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery?lq=1) – GiamPy Sep 13 '15 at 20:33
  • 1
    I avoid using jQuery, as I like to know how to do it myself instead of other peoples functions and code. I know it's quicker, but I just like doing it myself, I learn more. – Martyn Ball Sep 13 '15 at 20:34
  • @GiamPy, that's all jQuery answers. I want just JavaScript. – Martyn Ball Sep 13 '15 at 20:35
  • @Bergi Yes, formElement is always a form. – Martyn Ball Sep 13 '15 at 20:40
  • There are some obvious problems and it appears there are more problems (especially cross-browser support) than that. On top of that it appears there are some relevant pieces of code missing. All this makes it daunting (if not impossible) to answer your exact question. Apart from Bergi's suggestion's I'd like to add that the string `[object HTMLInputElement]` is not equal to an empty string so your nested if will always 'generate a new form'. Also, why add an empty 'location' field to your in-memory form 'f' on error and then submit the 'physical' form 'formElement'? – GitaarLAB Sep 13 '15 at 22:41
  • Best to start that handler again from scratch and build it up in sections (adding some console.log or poor-mans-break-point 'alert's to verify how it runs). Start by figuring out the cross-browser method of getting events and cancel default methods, then build on top of that *in sections*, small parts at a time. That way, you know when (what section of your handler) breaks. Such refactoring usually helps you pinpoint much more precisely where your code breaks and if you can't find a solution to that specific problem, then (may I suggest?) ask again. – GitaarLAB Sep 13 '15 at 22:45

0 Answers0