Vinb
Vinb

Reputation: 11

Ajax Json Parse Error in jQuery

I am getting the following parse error from the Ajax call. "SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"

               $.ajax({
                        type: "POST",
                        url: "QueryOrder",
                        data: dataString,
                        dataType: "json",
                        success: function(
                            data) {;
                            alert("I am in Success");
                            alert(data);

                        },
                        error: function(jqXHR,
                            textStatus,
                            errorThrown) {
                            alert("Error Return from Ajax");
                            alert(jqXHR
                                .getResponseHeader('Content-Type'));
                            alert(jqXHR.responseText);
                            alert(jqXHR);
                            alert(errorThrown);
                            alert(textStatus);
                        }
                    }); //end of Ajax call

I have verified the json object which is getting generated in the servlet code and its valid

{"orderObj":[{"FIRST_NAME":"John","LAST_NAME":"Mkay"}]}

and response.setContentType("application/json"); is used to set the response.

I have used tried the following jQuery lib versions

and getting the same parse eof error.

I have also tried changing the dataType to 'Json', 'text', 'json/text' and even removing the dataType parameter and nothing is working. Please let me know how to resolve this issue

Upvotes: 0

Views: 4842

Answers (4)

Vinb
Vinb

Reputation: 11

Issue got resolved by adding

response.getWriter().write(myObj.toString());

to the servlet code. Thanks all for your support.

Upvotes: 1

Domain
Domain

Reputation: 11808

use out.println(myObj) instead of system.out.println(myObj) as sop prints to console and your ajax call is coming back with no response!

I'm not sure if " System.out.println(response.getContentType();" is useful .. Try commenting it!!

Upvotes: 0

Vinb
Vinb

Reputation: 11

Posting the entire code. Ajax call is returning null JSON object

**************HTML****************************************

    <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Modal form</title>
<link rel="stylesheet"
    href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
    type="text/javascript"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
body {
    font-size: 62.5%;
}

h1 {
    font-size: 1.2em;
    margin: .6em 0;
}

div#orders-contain {
    width: 450px;
    margin: 30px 0;
}

div#orders-contain table {
    margin: 1em 0;
    border-collapse: collapse;
    width: 150%;
}

div#orders-contain table td, div#orders-contain table th {
    border: 1px solid #eee;
    padding: .6em 10px;
    text-align: left;
}
}
</style>
<script>
    $(document).ready(function() {
        $("#query-order").click(function(e) {
            dataString = "countryCode=";
            alert("on Load");
             $.ajax({
                    type: "POST",
                    url: "QueryOrder",
                    data: dataString,
                    dataType: "json",
                    success: function(
                        data) {
                        alert("I am in Success");
                        alert(data);
                    },
                    error: function(jqXHR,
                        textStatus,
                        errorThrown) {
                        alert("Error Return from Ajax");
                        alert(jqXHR
                            .getResponseHeader('Content-Type'));
                        alert(jqXHR.responseText);
                        alert(jqXHR);
                        alert(errorThrown);
                        alert(textStatus);
                    }
                }); //end of Ajax call
        }); // end of click function
    });
</script>
</head>
<body>
    <div id="orders-contain" class="ui-widget">
        <h1>Orders:</h1>
        <table id="Orders" class="ui-widget ui-widget-content">
            <thead>
                <tr class="ui-widget-header ">
                    <th>Order Number</th>
                    <th>Customer Number</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Date of Order</th>
                    <th>Address</th>
                    <th>Order Total</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </div>
    <button id="query-order">Query Orders</button>
</body>
</html>

*****************************Servlet code************************

package com.order.pkg;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.*;

public class QueryOrder extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
           doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */ 
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");        

        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400"); 
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            System.out.println("Driver loaded");

            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            String user = "dbtest";
            String pwd = "dbtest";
            Connection DB_mobile_conn = DriverManager.getConnection(url, user,
                    pwd);
            System.out.println("Database Connect ok");

            String query = "select * from ORDER_HEADERS";

            ArrayList<Order> orderList = new ArrayList<Order>();


            if (query != null) {
                Statement query_stmt = DB_mobile_conn.createStatement();
                ResultSet query_rs = query_stmt.executeQuery(query);
                while (query_rs.next()) {
                    Order orderobj = new Order();
                    orderobj.setFIRST_NAME(query_rs.getString("FIRST_NAME").trim());
                    orderobj.setLAST_NAME(query_rs.getString("LAST_NAME").trim());
                    orderList.add(orderobj);
                }
                query_rs.close();
                query_stmt.close();
            }

            Gson gson = new Gson();
            JsonObject myObj = new JsonObject();
            JsonElement orderObj = gson.toJsonTree(orderList);
            myObj.add("orderObj", orderObj);
            System.out.println(myObj);      

            System.out.println(response.getContentType());              

        } catch (Exception exp) {
            System.out.println("Exception = " + exp);
        }
    }
}

Upvotes: 0

Verhaeren
Verhaeren

Reputation: 1661

I think your problem is that you have to send the data to the server in a proper json serializer:

data: JSON.stringify(dataString),

Upvotes: 0

Related Questions