Search code examples
servletsxmlhttprequest

How to SET the response of an XMLHttpRequest


So I have this function to send a document to a servlet that stores it in my DB and everything works fine :

function submitAttachment(formName, formId, fieldName) {
      var formData = new FormData();
      var fileName = "";
      var files = document.getElementById(fieldName + "Document").files;

      formData.append('formName', formName);
      formData.append('formId', formId);
      formData.append('fieldName', fieldName);

      for (var i = 0; i < files.length; i++) {
          var file = files[i];
          formData.append('file', file, file.name);
          fileName = file.name;
      }

      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'saveattachment', true);

      xhr.onload = function() {
          if (xhr.status === 200) { // Success
            var idDoc = xhr.responseText;
            setLinkHtml(fieldName, fileName, idDoc);
            $("#" + fieldName + "IdDocument").val(idDoc);
          }
      };

      xhr.send(formData);
}

Only, the response I get (from xhr.responseText) is \u0017.

My servlet looks roughly like this :

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        response.setContentType("text/html; charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
       request.setCharacterEncoding("UTF-8");
       PrintWriter out = response.getWriter();

        //DoStuff

        out.write(doc.getIdDocument());
    }


    //Process the HTTP Post request
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        doGet(request,response);
    }

All I want is to return a single number, what am I doing wrong?


Solution

  • Finally found it! If anyone is wondering, turns out returning a single number acted as some kind of return code. So all I needed to do was add + "" so out.write(doc.getIdDocument() + "") and it worked!