Home > Software design >  Upload File using XMLHttpRequest not working. Page is getting refreshed on clicking upload button
Upload File using XMLHttpRequest not working. Page is getting refreshed on clicking upload button

Time:12-10

I am trying to make a form that takes the files from user and post in a url and gets it JSON response using XMLHttpRequest. But it's doesn't working in the manner.

My all codes are here => https://codepen.io/mrbotdeveloper/pen/YzrWegj (I am not promoting anything please help)

So when the user presses the upload button then the page automatically gets reloaded and didn't posted data on the link.

Please help to get out of it.

Thanks in advance.

I am a beginner in Web Developement. So, please help me.

CodePudding user response:

  1. Try changing

     <button  onclick="checkFile('${file}')".
    

    in the injected HTML to

     <button type="button"  onclick="checkFile('${file}')">
    

    The default type of button is "submit".

    Alternatively remove the <form></form> tag pair surrounding the button element - you do not appear to be using a form.

  2. Consider using the whole viewport as the drop zone. If users drop files outside a smaller zone, and the browser recognizes the file type, it may load the file dropped in place of your web page.

  3. Follow the XHRRequest response and responseType documentation on MDN (or search for duplicate questions) to get JSON data returned by the server.

    That is to say set the XRH.responseType to "json" before sending. Example code to recheck the response after receipt as well:

     function getResponse(XHR) {  // XRH = XHRHTMLRequest object
         if(XHR.responseType == "json") {
             return XHR.response;
         }
         if( XHR.responseType == "text" || !XHR.responseType) {
             return JSON.parse(XHR.Rresponse);
         }
         throw TypeError("XHR response type is not JSON");
     }
    
  • Related