title: JSON from Servlet to Ajax to HTML - no error message
body: <p>I am just finishing up this project. I have a JSON string</p>
  
  <pre><code>{"data":{"id":"YPekRdk","title":null,"description":null,"datetime":1429674575,"type":"image\/png","animated":false,"width":600,"height":200,"size":85694,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"deletehash":"AZi041RwarCFD3I","name":"","link":"http:\/\/i.imgur.com\/YPekRdk.png"},"success":true,"status":200}
  </code></pre>
  
  <p>I send it from my servlet</p>
  
  <pre><code>response.getWriter().write(new Gson().toJson(imgurImageJson));
  </code></pre>
  
  <p>to my ajax </p>
  
  <pre><code>$(document).ready(function () {
      $('#button').click(function () {
          var array1 = [];
  
          $('#sortable2 .selectedItemImg').each(function () {
              array1.push($(this).attr('src'));
          });
  
          $.ajax({
              url: 'generate',
              type: 'POST',
              contentType: 'text/plain',
              dataType: 'html',
              data: array1.join('\n'),
  
              success: function (data) {
                  $.each(JSON.parse(data), function (listID, mapData) {
                      $("#displayGeneratedURL").append("&lt;p&gt;" + mapData.id + "&lt;/p&gt;");
                  });
              }
          });
      });
      return false;
  });
  </code></pre>
  
  <p>and try to view it on my jsp</p>
  
  <pre><code>#displayGeneratedURL{
              color:  white; font-family: Geneva,Tahoma,Verdana,sans-serif; font-size: 12px;
          }
  
  &lt;div id="displayGeneratedURL"&gt;Result should be here somewhere&lt;/div&gt;
  </code></pre>
  
  <p>With this I was getting a browser message:</p>
  
  <pre><code>Uncaught SyntaxError: Unexpected token &lt;
  </code></pre>
  
  <p>I changed my datatype to application/json and a few other things and that error message goes away and instead just nothing happens whatsoever (as output to the screen or to that console). </p>
  
  <p>The code I am using is replicated mostly from working code I use with another servlet, however it could still be inappropriate/wrong to use with that Gson call with that json string, but I don't know. It could also be that my function in the ajax is completely wrong.</p>
  
  <p>Can you see anything that's wrong?</p>
  
  <p>Update: </p>
  
  <p>I tried changing the servlet response to</p>
  
  <pre><code>response.getWriter().write(imgurImageJson);
  </code></pre>
  
  <p>and the datatype to <code>dataType: 'text/html'</code>, there is nothing displayed still and no error messages (this gave the > error when datatype was left as text only)</p>
  
  <p>Update: I changed my ajax function to this</p>
  
  <pre><code>success: function (data) {
      alert("Hello");
  }
  </code></pre>
  
  <p>and it does not make an alert box or do anything</p>
  
  <p>IMAGE OF MY CONSOLE IS HERE</p>
  
  <p><img src="https://i.stack.imgur.com/IZivJ.jpg" alt="enter image description here">
   <a href="https://i.stack.imgur.com/IZivJ.jpg" rel="nofollow noreferrer">http://i.stack.imgur.com/IZivJ.jpg</a></p>
  
  <p>(additional plain link because otherwise it goes very tiny)</p>
  
  <p>Update: </p>
  
  <p>This is my developer console POST Response</p>
  
  <p><img src="https://i.stack.imgur.com/0wJuf.png" alt="enter image description here"></p>
  
  <p>EDIT: Here is my FULL servlet code (very messy):</p>
  
  <pre><code>/*
   * To change this license header, choose License Headers in Project Properties.
   * To change this template file, choose Tools | Templates
   * and open the template in the editor.
   */
  package mainClasses;
  
  import com.google.gson.Gson;
  import com.google.gson.JsonObject;
  import com.google.gson.JsonParser;
  import java.io.BufferedReader;
  import java.io.File;
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.net.URL;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  import java.util.Map;
  import java.util.Properties;
  import java.util.Scanner;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  import javax.servlet.ServletContext;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  //import static jdk.nashorn.internal.objects.NativeDebug.getContext;
  
  /**
   *
   * @author J
   */
  @WebServlet(name = "ImageGenerationServlet", urlPatterns = { "/generate" })
  public class ImageGenerationServlet extends HttpServlet {
  
      /**
       * Processes requests for both HTTP &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt;
       * methods.
       *
       * @param request
       *            servlet request
       * @param response
       *            servlet response
       * @throws ServletException
       *             if a servlet-specific error occurs
       * @throws IOException
       *             if an I/O error occurs
       */
      protected void processRequest(HttpServletRequest request,
              HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/html;charset=UTF-8");
          try (PrintWriter out = response.getWriter()) {
              /* TODO output your page here. You may use following sample code. */
              out.println("&lt;!DOCTYPE html&gt;");
              out.println("&lt;html&gt;");
              out.println("&lt;head&gt;");
              out.println("&lt;title&gt;Servlet ImageGenerationServlet&lt;/title&gt;");
              out.println("&lt;/head&gt;");
              out.println("&lt;body&gt;");
              out.println("&lt;h1&gt;Servlet ImageGenerationServlet at "
                      + request.getContextPath() + "&lt;/h1&gt;");
              out.println("&lt;/body&gt;");
              out.println("&lt;/html&gt;");
          }
      }
  
      // &lt;editor-fold defaultstate="collapsed"
      // desc="HttpServlet methods. Click on the + sign on the left to edit the code."&gt;
      /**
       * Handles the HTTP &lt;code&gt;GET&lt;/code&gt; method.
       *
       * @param request
       *            servlet request
       * @param response
       *            servlet response
       * @throws ServletException
       *             if a servlet-specific error occurs
       * @throws IOException
       *             if an I/O error occurs
       */
      @Override
      protected void doGet(HttpServletRequest request,
              HttpServletResponse response) throws ServletException, IOException {
          processRequest(request, response);
      }
  
      /**
       * Handles the HTTP &lt;code&gt;POST&lt;/code&gt; method.
       *
       * @param request
       *            servlet request
       * @param response
       *            servlet response
       * @throws ServletException
       *             if a servlet-specific error occurs
       * @throws IOException
       *             if an I/O error occurs
       */
      @Override
      protected void doPost(HttpServletRequest request,
              HttpServletResponse response) throws ServletException, IOException {
          processRequest(request, response);
  
          // List imageList = Arrays.asList(request.getParameter("button"));
          //
          // System.out.println(imageList);
          //
          // ArrayList &lt;String&gt; imageURLs = new
          // ArrayList(Arrays.asList(imageList));
          //
          // System.out.println(imageURLs);
          // ArrayList &lt;String&gt; imageURLs = new
          // ArrayList(request.getParameter("button"));
          // String postResponse = request.getParameter("button");
          // ArrayList&lt;Map&gt; imageMap = new ArrayList&lt;Map&gt;();
          // String[] urls1 = postResponse.split(",");
          // ImageController.controlImage(urls1);
          List&lt;String&gt; imageURLs = new ArrayList&lt;String&gt;();
          try {
              BufferedReader reader = request.getReader();
              String line;
              do {
                  line = reader.readLine();
  
                                  if (line !=null){
                  imageURLs.add(line);
                                  }
  
              } while (line != null);
          } catch (Exception e) {
          }
          ;
  
          try {
              // int size = imageURLs.length();
  
              // Our steps are:
              // 1) Retrieve array of image srcs from our jsp via jquery and parse
              // to string array.
              // 2) Process the array in ImageController to create composite
              // image, upload to local server
              // and return local image url.
              // 3) Transfer the image to imgur by sending our local image url to
              // the imgur API.
              // Retrieve the image's new imgur url in json string.
              // 4) Parse the string so that we have just the url in json format.
              // 5) Send this back to our jsp via jquery and print to screen.
              ImageController imageController = new ImageController();
  
              String filePath = imageController.controlImage((ArrayList&lt;String&gt;) imageURLs);
  
                          System.out.println(filePath);
  
              // String generatedImageFilePath =
              // ImageController.controlImage((ArrayList&lt;String&gt;) imageURLs);
              // UploadController uploadController = new UploadController();
              String imgurImageJson = UploadController.getImgurContent(filePath);
  
  
  
  //                 response.setContentType("json");
          response.setCharacterEncoding("UTF-8");
  
  //                 response.getWriter().write("hello");
                  response.getWriter().write(new Gson().toJson(imgurImageJson));
  
  //                response.getWriter().write(new Gson().toJson(imgurImageJson));
  
  //                        System.out.println(imgurImageJson);
  //
  //          Scanner file = new Scanner("imgurImageJson.json");
  //          String imgurImageJsonSample = file.nextLine();
  //          file.close();
  //
  //          JsonParser parser = new JsonParser();
  //          JsonObject obj = parser.parse(imgurImageJsonSample)
  //                  .getAsJsonObject();
  //          String imgurl = obj.get("link").toString();
  //          System.out.println(imgurl);
  
              // uploadedImageJson
              // 1) retrieve array of urls
              // 2) send to imagegenerationcontroller
              // 3) send to uploadcontroller
              // 4) retrieve and parse the json response to get the imgur url
              // 5) response from here to user
          } catch (Exception ex) {
              Logger.getLogger(ImageGenerationServlet.class.getName()).log(
                      Level.SEVERE, null, ex);
          }
  
      }
  
      /**
       * Returns a short description of the servlet.
       *
       * @return a String containing servlet description
       */
      @Override
      public String getServletInfo() {
          return "Short description";
      }// &lt;/editor-fold&gt;
  
  }
  </code></pre>