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?