Servlet
String getCodeList = (new JSONArray(rmsCodeList)).toString();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(getCodeList);
Jquery
$(document).ready(function() {
var getdata;
$.post("GetItemCode", function(data) {
getdata=data;
});
});
working fine, I get the complete array on getdata
Write Two
String getCodeList = (new JSONArray(rmsCodeList)).toString();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(getCodeList);
String getNameList = (new JSONArray(rmsNameList)).toString();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(getNameList);
How can I get two array on different variable
$(document).ready(function() {
var getdata1;
var getdata2;
$.post("GetItemCode", function(data) {
getdata1=?;
getdata2=?;
});
});
Put the two arrays in a JSONObject and retrieve it in Javascript
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
new JSONObject()
.put("codeList", new JSONArray(rmsCodeList))
.put("nameList", new JSONArray(rmsNameList)).toString()
);
Then in Javascript you retrieve it as a property of the returned object.
$(document).ready(function() {
var getdata1;
var getdata2;
$.post("GetItemCode", function(data) {
getdata1 = data.codeList;
getdata2 = data.nameList;
});
});
Send a JSON object containing two array values and set each one to the desired JavaScript variable.
Although you're writing the code like you're making a synchronous call, which will likely lead to problems.
Related
I am planning to post entire form data in JSON format to Struts2 Action. Below are my code snippets. Correct me where I am going wrong or Help me so that I can get all values in the Action file correctly. All of my SOPs in Action file is displayed as null
var MyForm = $("#companyform").serializeArray();
var data = JSON.stringify(MyForm);
$.ajax({
type: 'POST',
url:'createcompany.action?jsonRequestdata='+data,
dataType: 'json',
success: function(data){
console.log(stringify(data));
}});
My form data is turned into [{"name":"tan","value":"rrr"},{"name":"pan","value":"adf"},{"name":"tod","value":"1"}]
Struts2 Action File:
String jsonRequestdata;
public String execute() throws Exception {
JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata);
JSONObject json = (JSONObject) jsonArr.get(0);
System.out.println("TAN=" + json.get("tan"));
System.out.println("PAN=" + json.get("pan"));
System.out.println("TOD=" + json.get("tod"));
return "success";
}
Present OUTPUT
TAN=null
PAN=null
TOD=null
To send data with the POST request you should use data property like this
$.ajax({
type: 'POST',
url:'createcompany.action'
data: 'jsonRequestdata='+data
dataType: 'json',
success: function(data){
console.log(JSON.stringify(data.jsonRequestdata));
}
});
To get the data in the action bean you need to use public setter
public void setJsonRequestdata(String data){ this.jsonRequestdata = data; }
To return data back to the success callback function use public getter
public String getJsonRequestdata(){ return this.jsonRequestdata; }
To return JSON from the action use result type json.
<result type="json"><param name="includeProperties">jsonRequestdata</param></result>
Note, if you add json interceptor to the action config you can use JSON data in the request. Using Content-Type: "application/json" with the request will trigger Struts2 to parse the request and deserialize it to the action bean automatically.
Since I am using name,value I must get it by using name. Below is the working code
JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata);
for(int i=0;i<jsonArr.size();i++){
JSONObject json=(JSONObject) jsonArr.get(i);
System.out.println("name=" + json.get("name"));
System.out.println("value=" + json.get("value"));
}
I'm facing difficulties understanding the logic here. Ok, so let's say I have a class
#RequestMapping(value="/GetPersons", method = RequestMethod.GET)
public void loadPersons(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
OutputStream out = response.getOutputStream();
List<Person> persons = personDAO.loadPersons();
Iterator iterator = persons.iterator();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
while (iterator.hasNext()) {
JSONObject object = new JSONObject();
object.put("name", person.GetName());
jsonArray.add(object);
}
jsonObject.put("data", jsonArray);
OutputStreamWriter writer = new OutputStreamWriter(out);
try {
writer.write(jsonObject.toString());
}finally {
writer.close();
}
}
And then I have a simple script in my index.jsp
function loadPersons(json) {
var obj = JSON.parse(json);
var Person = obj.data;
for (i = 0; i < myArr.length; i++) {
$('#myId).append('<li>Test</li>');
}
}
$.ajax({
url: "http://localhost:8080/Persons/getPersons",
success: function (data) {
loadPersons(data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
So my question is the following... What is the logic that goes on here? How is the JSONObject data passed to the $.ajax success and the function. The function takes an argument "data" but what is going to be passed? The whole getPersons method from the java or?
The point here is to dynamically populate a simple dropdown by calling json object with ajax.
In your loadPersons method, you use the JSONObject and JSONArray classes to build a Java representation of a JSON object that will look like this:
{
"data": [
{
"name": "whatever person.getName() evaluated to"
},
{
"name": "another person.getName() call"
}
]
}
This is the JSON data that is sent, as text, in the response from your servlet.
The jQuery ajax function does additional work with this response, finally turning it into a Javascript object, which is then passed to your success callback as the data parameter. This Javascript object looks similar:
{
data: [
{
name: "whatever person.getName() evaluated to"
},
{
name: "another person.getName() call"
}
]
}
And you could access the value of the first name with: data.data[0].name
In this specific case, you're writing the JSON string content directly in the response of the request. This is done in these lines:
//Obtain the output stream from the response
OutputStream out = response.getOutputStream();
//Wrap the output stream into a writer
OutputStreamWriter writer = new OutputStreamWriter(out);
try {
//write in the writer that will write on the HTTP response
writer.write(jsonObject.toString());
}finally {
//close writer and free resources
writer.close();
}
So, the response from the server will be a string that contains your data. This comes from these lines of code:
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
while (iterator.hasNext()) {
JSONObject object = new JSONObject();
object.put("name", person.GetName());
jsonArray.add(object);
}
jsonObject.put("data", jsonArray);
Then, the $.ajax from jquery will execute the callback function defined in success, where it receives the response from the server as the argument:
$.ajax({
//removed code for explanation purposes...
success: function (data) {
//data is the response from the server on a successful execution
//of the HTTP request to the server
//do something here with the response from the server
//in this case, call the loadPersons function
loadPersons(data);
}
});
In loadPersons function, you deserialize the data from the json string into a JavaScript json object, then create HTML from the json data there.
First click the link http://localhost:8080/Persons/getPersons on any browser,if your spring service is running currently,you will see JSON data in your browser. The same data is getting fetched by the AJAX call inside your index.jsp.
$.ajax({
url: "http://localhost:8080/Persons/getPersons",
success: function (data) {
loadPersons(data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
P.S - i think you will have to add below line also to this ajax call
dataType :'json'
In the ajax call, success and failure are callback function which are invoked when browser get the response from server,success is executed in case of (2XX) while failure is invoked in case of error response,success function takes an argument data,which is JSON,same as you would have seen in your previous step.
Then as you received data from server,it is in JSON format(I suppose),you will have to parse it to convert it to object,and then you are fetching the data and setting it to the html elements.
$('#myId).append('<li>Test</li>');
Hello I have been looking at other threads like mine and I can't seem to get my code working!
I need to send the JS array containing ints to a servlet this is current code:
Javascript code:
function sendReminderEmails(){
$("#sendReminderEmails").click(function(){
var people = null;
var peopleBatch1 = null;
$.ajax({
type: "POST",
url:"getAllUnregisteredPeople",
async: false,
success: function(data){
people =JSON.parse(data);
}
});
peopleBatch1 = people.splice(0,200);
$.post("sendReminderEmails", {people:peopleBatch1, mode : "insert"} , function(data){
});
});
}
Servlet Code:
protected void doPost(HttpServletRequest request, HttpServletResponse response){
String peopleIDs[] = request.getParameterValues("people");
}
It keeps returning null! Can someone tell me if I am doing something wrong ?
You must use JSON.stringify to send your JavaScript object as JSON string.
Change your code
var obj = { people: peopleBatch1, mode: "insert" };
$.post("sendReminderEmails",JSON.stringify(obj) , function(data) {});
On Servlet side you need you use
String jsonStr = request.getParameter("people");
then Convert this jsonStr to JSON object.
in "$ajax" you need to pass the required parameter, eg
var myArray={'john', 'paul'};
$.ajax ({
type: "POST",
url:"getAllUnregisteredPeople",
data: {people: myArray}
async: false,
success: function(data) {
people = JSON.parse(data);
}
});
I am doing a toy program that asks user to input "username" and "fullname" on an html form, the form will be submitted by AJAX to the following method in Spark framework (see here for Spark:
post("/admin/user/signup", "application/json", (request, response) -> {
String username = request.queryParams("username");
String fullname = request.queryParams("fullname");
System.out.println("username is: " + username +", full name is: " + fullname);
Map<String, Object> registerResults = new HashMap<String, Object>();
registerResults.put("success", "successfully registered " + username);
return new MyMessage("successful registration!");
}, new JsonTransformer());
And the following is my AJAX code that supposedly submits and receives the response from the above post() method:
<script>
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>
However, the AJAX code cannot receive the JSON object, instead the JSON object is simply printed on the web page /admin/user/signup:
{"message":"successful registration!"}
So I am asking for help how to return the JSON object to AJAX request in Spark? thanks
You do realize that you are submitting the form. So instead of the supposed AJAX call the form is being submitted and hence the resulting page ...
So you should stop the form submit propagation by simply adding
event.preventDefault();
OR return false; at the end of the submit handler.
in the form submit handler.
<script>
$(document).ready(function() {
$('#registerForm').submit(function(event) {
event.preventDefault();
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>
Instead of return new MyMessage("successful registration!");
Just pass like this return new MyMessage(registerResults);
now,you are not returning this registerResults map value.
I hope you are using play framework.then it should work
And one more thing,you should deny the form from submitting. so, use
$('#registerForm').submit(function(e) {
e.preventDefault();
// do your stuff here
});
You can not treat json as HTML by using html() function, you need to parse it by parseJson() function from jQuery: http://api.jquery.com/jquery.parsejson/
var obj = jQuery.parseJSON(data);
$('.starter-template').html(obj.message);
I have to json array in my servlet.
I want to fetch json array value and print in to jsp page using ajax.
below is code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
jsp
I got error msg here.
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
error : function() {
alert("Error");
},
success : function(data) {
alert(data);
}
});
See, if you want to pass that from servlet to jsp you need not to make a request (ajax), since servlet and jsp both exists at server side.You just set that json array as a request attribute or session attribute and get it in jsp and display(with loop).NO need of ajax there.
If You need to fetch the data with synchronous call:
In servlet
PrintWriter out = response.getWriter();
out.println(htags);
I won't clutter SO with another full example,see this SO post:How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?
Try this
servlet code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String jsons = "["+htags+","+trends+"]"; //Put both objects in an array of 2 elements
out.print(jsons);
and on you jsp page
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
contentType:"application/json",
error : function() {
alert("Error");
},
success : function(data) {
var data1=data[0],
var data2=data[2],
alert(data1[0]);
}
});
Servlet can use this to send json array or json object to client.
JSONArray jsonArray = [{:}, {:}];
response.getWriter.write(jsonArray.toString());
In JSP page, this method call the request JSON to Servlet and catch the json array or json object with annonymous function(JSON.parse is used to convert string to json object or json array) method.
$("button").click(function(){
$.get("ServletToJSP",function(data,status){
alert("Data: " + JSON.parse(data) + "\nStatus: " + status);
});
});
in servlet:
String uri = request.getRequestURI();
if (uri.equalsIgnoreCase(uri)) {
response.setContentType("application/json");
/* get the json array */
response.getWriter().write(array.toJSONString());
}
jquery:
$('#buttonid').on('click', function() {
var url="your url";
$.ajax({
type : 'POST',
url : url,
data : null,
error : function(xhr, status, error) {
alert("error");
},
success : function(data) {
alert("success");
$.each(data, function(key, val) {
console.log(val);
}
});
});