Obtain the JSON response from the servlet

Is there a way to get a JSON response from a servlet in JavaScript? I am using AJAX post to send data to the servlet.

 Here is my AJAX code

 $.ajax({
            type: "POST",
            url: "formDelegationServlet",
            data: {
                jsonfield: JSON.stringify(dataString) // pay attention here!
            },
            dataType: "json",
            // if a response is received from the server
            success: function (response) {
                // valid country code, display information
                if (response.success === true) {
                    console.log("response: " + response);
                    $("#kota_merchant").val(response.rows.kota_merchant_del);
                    $("#alamat_merchant").val(response.rows.alamat_merchant_del);
                    $("#province_merchant").append(response.rows.prov_merchant_del);

                }
                // show error message
                else {
                    $("#ajaxResponse").html("<div><b>Merchant Name is Invalid!</b></div>");
                }
            },
            // If no response is received from the server
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("Something went wrong: " + textStatus);
                $("#ajaxResponse").html(jqXHR.responseText);
            }
        });

This is my servlet code

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONArray array = new JSONArray();
                for (int i = 0; i < dataMerchant.size(); i++) {
                    JSONObject obj = new JSONObject();
                    EntityMerchant entityMerchant = dataMerchant.get(i);

                    if (entityMerchant.getNamaMerchant() == null) {
                        obj.put("nama_merchant_del", "");
                        obj.put("success", false);
                    } else {
                        obj.put("nama_merchant_del", entityMerchant.getNamaMerchant());
                        obj.put("success", true);
                    }
                    if (entityMerchant.getAlamatMerchant() == null) {
                        obj.put("alamat_merchant_del", "");
                    } else {
                        obj.put("alamat_merchant_del", entityMerchant.getAlamatMerchant());
                    }
                    if (entityMerchant.getKota() == null) {
                        obj.put("kota_merchant_del", "");
                    } else {
                        obj.put("kota_merchant_del", entityMerchant.getKota());
                    }
                    if (entityMerchant.getProvinsi() == null) {
                        obj.put("prov_merchant_del", "");
                    } else {
                        obj.put("prov_merchant_del", entityMerchant.getProvinsi());
                    }
                    if (entityMerchant.getPassword() == null) {
                        obj.put("pas_merchant_del", "");
                    } else {
                        obj.put("pas_merchant_del", entityMerchant.getPassword());
                    }
                    array.add(obj);

                }
                em.close();
                JSONObject jsonobj = new JSONObject();
                jsonobj.put("rows", array);
                out.print(jsonobj.toString());
}

This is my response JSON

{"rows":[{"nama_merchant_del":"MAJU SUKSES OCEAN","success":true,"alamat_merchant_del":"JL. DIPONEGORO
 NO.  1B","kota_merchant_del":"JAKARTA PUSAT","prov_merchant_del":"DKI JAKARTA","pas_merchant_del":"0"
}]}

I have attempted this several times but without success. Can anyone offer assistance?

Answer №1

Start by defining the content type and then proceed with initializing your printwriter object using the following code:

PrintWriter out = null;     
res.setContentType("application/json; charset=UTF-8");
out = res.getWriter();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Just a quick question about using AJAX

Before submitting my PHP page, I need to send an email. The mail script is in a file called sendmails.php. Is it possible to use JavaScript to send an AJAX request to send the email before submitting the page? Here is an example: function submit_page() { ...

What could be causing req.params to come back as undefined?

I have reviewed two similar questions here, but none of the suggestions in the comments seem to be resolving my issue. app.get('/:id', function(req,res) { console.log(req.params.id); }); app.get('/:id', function(req, res) { db.que ...

Fill a JavaScript array with values inserted in the middle position

I'm having trouble populating an array: var arr2 = ["x", "y", "z"]; I want to insert a random number/value between each original value using a for loop, like this: for (let i = 1; i < arr2.length; i+2) { arr2.splice(i, 0, Math.random()); } B ...

Why does my Observable remain perpetually unfulfilled?

I recently started learning javascript and came across the Angular 2 Documentation where I discovered that Promises can be replaced with Observables. While experimenting with a simple code, I noticed that in addition to the expected result, I am also getti ...

Easily transfer files without the need to refresh the page by utilizing the power of AJAX

In my page file-upload.jsp, I have the following code snippet: <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="upload_file" name="upload_file" multiple="" /> <in ...

Issue with Canvas Update in Loop while Using Three.js Library

In the code snippet provided, it takes in a number of scans which is always set to 2880. The canvas is divided into 2880 sectors to cover a full 360°. The code runs a loop from 0 to 2880, rendering colored points in each sector from the center of the canv ...

Tips for emphasizing v-list-item on click (Vue)

I am currently working on a side menu that changes based on the selected router model. My goal is to have the selected page highlighted when clicked. I would like this functionality for all the submenus as demonstrated in this example. Below are snippets ...

An array of dictionaries that are the same except for one dictionary containing an unspecified key

A while ago, I wrote some sample code to generate Euler diagrams from an array of dictionaries. Strangely enough, it only works when the array is explicitly defined in my .js file; using input from a .json file to construct it incrementally does not yield ...

Troubleshooting Problem with Angular JS Ng-Repeat

I have a specific situation where I want to showcase the elements that exist in only one array. If an element is also present in another array, there is no need to display it. My HTML structure looks like this: <div ng-repeat="array1Value in array1"&g ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

"An ActionResult is received as null when the model is passed as an

Has anyone encountered a situation where the model is null when passed to the controller? I inserted an alert in the ajax call to verify the value and it seemed correct, but upon debugging on the first line of the controller's ActionResult, it shows a ...

Serializing data in OData protocol

Struggling for the past 2 months to devise a unique solution for custom serializing an entity returned from an OData controller. Desperately seeking assistance! The scenario is fairly straightforward, and I have distilled it even further to pinpoint the i ...

Exploring the features of AngularJS, one can delve into the ControllerAs syntax

Currently, I am in the process of developing a directive and following the guidelines outlined in the John Papa style guide. In line with this, I have adopted the ControllerAs syntax approach and implemented a small directive as shown below: (function() { ...

Unwillingness of Ajax to accept Names containing apostrophes as a parameter

$(".loadingPnl").removeClass('hdn'); var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl; var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/S ...

Issue: [ng:areq] The parameter 'TasksCtrl' should be a function, but it is currently undefined

I seem to be encountering an error and I'm struggling to identify the cause. Is there something I overlooked? js var app = angular.module('Todolist', []); app.controller('TasksCtrl', [ '$scope', function($scope) { ...

Is there a Java library available for JSONiq implementation?

After exploring the JSONiq specification (www.jsoniq.org), I noticed that most implementations are standalone deployments such as Zorba, VXQuery, etc. These solutions are primarily focused on querying JSON-based databases or processing large JSON documents ...

JavaScript's `indexOf` function can sometimes return false when it should actually return true

I'm having trouble detecting if a specific text is present within a string. Even though the text I am looking for is clearly there, my code seems to ignore it and goes straight to the else part of the statement. Here is the snippet of code causing th ...

Issue with parsing work positions from FaceBook user profiles

Hey there, I'm currently facing an issue while trying to retrieve the name of a work position from Facebook's graph API. This is what I have attempted so far (in JSON): https://graph.facebook.com/me?access_token=ABCDEFGHIJKABCDEFGHIJKABCDE ...

What is the best method for accessing multiple tabs using a URL and variable within Java Selenium?

It is necessary for me to launch more than 100 pages (https://same URL/"different page") and I am looking to utilize a for loop with variables in order to open a specific number of them simultaneously. However, the Java selenium code that I have ...

Is there a way for me to either fulfill a promise or face failure?

Currently, I am working on creating a Thennable function that may return a promise based on its parameters. However, there is a possibility that the parameters are invalid which would require breaking the promise chain with something unexpected. What can b ...