I am new to Ajax and would have thought there would be plenty of examples of passing an array from java to ajax; however, I have not been able to find them. I want to pass three strings to ajax and then display them in HTML. My java code is:
System.out.println("Authenticated");
String json = new Gson().toJson(questionList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
The ajax is:
dataType: "json";
alert(responseJson);
var result = $.parseJSON(responseJson); <-- this line fails
$('#question1').val(result.question1);
$('#question2').val(result.question2);
$('#question3').val(result.question3);
The alert displays "Question 1 is a?,Question 2 is b?,Question 3 is c?".
How do I pass each of the strings to display in the HTML. I suspect I need to build the array in java differently as well as receive the result in ajax differently; however, I can not find an applicable example. I do not want to use unstring as the question could contain "," or other delimiter used.
The responseJosn you get from ajax is already been parsed. No need to parse it again. It's an Array. So the JS code would be like:
dataType: "json"; //this line should not be here
alert(responseJson);
//var result = $.parseJSON(responseJson); <-- this line fails
$('#question1').val(responseJson[0]);
$('#question2').val(responseJson[1]);
$('#question3').val(responseJson[2]);
Related
I have picked up a legacy project and I am in the process of debugging something.
I have come across a custom JavaScript function (encodeJsonIntoString) which encode URI components for JavaScript object before sending over via AJAX.
The AJAX is nothing fancy:
$.ajax({
url: URL,
method: 'POST',
datatype : 'json',
data : encodeJsonIntoString(myObj),
success: ...
});
There is no custom processData or contentType set in the ajax call. What really puzzle me is why the previous developers didn't let $.ajax's data attribute to convert the JavaScript object automatically into a URI-encoded string or didn't even try using JQuery.param() to do it but to write the whole function themselves.
For a test, I have made a simple object to test the function encodeJsonIntoString:
var testDataA = {
list: [
{
lastname:"Smith",
firstname:"John"
},
{
lastname:"Black",
firstname:"Jack"
},
{
lastname:null,
firstname:"Mary"
}
]
};
After decoding URI components, the result of the function is:
list[0][lastname=Smith&list[0][firstname=John&
list[1][lastname=Black&list[1][firstname=Jack&
list[2][lastname=null&list[2][firstname=Mary
Notice there are lack of closing square brackets(]) in some places and it uses "null" for null values.
If I run JQuery.param() and decode it, I get this:
list[0][lastname]=Smith&list[0][firstname]=John&
list[1][lastname]=Black&list[1][firstname]=Jack&
list[2][lastname]=&list[2][firstname]=Mary
See the difference? But somehow the result of the function is accepted by the server(Java/Spring - #ModelAttribute) and read into the correct list structure.
I don't have access to the server side here, but I wonder if that array syntax is correctly acceptable or is it just "tolerated" by the server? Will the server see both versions of object in the same structure format?
I am tempted to just replace it with JQuery.param() to handle more robust input data in the future which may also accept special characters.
I sent one request as URL with data to servlet, But by default servlet is modifying the data and sending as request. Can you please suggest how to maintain the request URL with data which i passed to servlet should remain same ?
Example:- when i am passing the data to servlet
http://localhost/helloservlet/servlet/ppd.abcd.build.coupons.CouponValueFormatterServlet?dsn=frd_abc_abcde&lang=ENG&val=PRCTXT|12345 &ABCDEFG
when it using the above url in servelt as request , like string abc = request.getParameter("val"), the val attribute is trimmed automatically and assigned as " val=PRCTXT|12345" but it supposed to be like " val = PRCTXT|12345 &ABCDEFG ". Please help me on this.
The servlet interprets each & in the URL as the start of a new parameter. So when it sees &ABCDEFG, it thinks you are sending a new parameter called ABCDEFG with no value (though this is technically a "keyless value" according to the specifications).
Two things to fix this, first is when you want to actually send an &, use %26 instead. This will be skipped by the code that divides up the parameters, but converted to a real & in the parameter's value.
Second is to replace spaces with +. Spaces in URLs work sometimes but can be problematic.
So your actual request URL should look like this:
http://localhost/helloservlet/servlet/ppd.abcd.build.coupons.CouponValueFormatterServlet?dsn=frd_abc_abcde&lang=ENG&val=PRCTXT|12345+%26ABCDEFG
If you're building these parameters in javascript, you can use encodeURIComponent() to fix all problem characters for you. So you could do something like this:
var userInput = *get some input here*
var addr = 'http://www.example.com?param1=' + encodeURIComponent(userInput);
I need to fill a drop down from database using ajax, Iam using two drop downs, if first drop down value is selected the second drop down value(have to be retrieved from DB based on the values selected in the first drop down) must have to be displayed. The DAO(Data Access Layer) returns 4 results as arraylist object but in http responsetext it is printing as object not the values.I tried using for loop to iterate it but i can't achieve it. Please assist me on this.
HTML Code:
// First Drop Down
Question Field :<select name="ddlAddQuestionField" id='ddlAddQuestionField' onchange="getFieldPosition()">
<option value=''>Select Question Field</option>
<option value='Security Question'>Security Question</option>
<option value='Personal Info'>Personal Info</option>
</select>
// Second DropDown
User Field Position:<select name="userFieldPosition" id="userFieldPosition" disabled="disabled"> </select>
Javascript Code
function getFieldPosition(){
var fieldName =$("#ddlAddQuestionField").val();
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("userFieldPosition").disabled=false;
alert(xmlhttp.responseText);
var response =xmlhttp.responseText;
for(var i=0;i<response.length;i++) {
var elements = "<option value='"+response[i]+"'>"+response[i]+"</option>";
$("#userFieldPosition").append(elements);
}
}
}
xmlhttp.open("POST","ApplicationController",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fieldAction=fieldPosition&fieldName="+fieldName);
}
Servelet Code
fieldPositionObj = fieldPositionDaoObj.getFieldPosition(fieldName); //Hitting the Dao
// In dao it returns arraylist object.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(fieldPositionDaoObj);
Your Problem is line
response.getWriter().write(fieldPositionDaoObj);
You are writing java Obejct Directly on Response.. I think fieldPositionDaoObj is list or aray.. so toString Representation is
(com.bean.QuestionInfoBean#23d275, com.bean.QuestionInfoBean#1ce15f6, com.bean.QuestionInfoBean#103fcaa, com.bean.QuestionInfoBean#c135d6)
Where com.bean.QuestionInfoBean#c135d6 is toString Representation of your Java Object.
I think wat you need to return there is JSON respresentation of Java Object/List/Array and your code will work
JSON (JavaScript Object Notation), is a simple and easy to read and write data exchange format. It’s popular and implemented in countless projects worldwide, for those don’t like XML, JSON is a very good alternative solution.
Your JSON Representation should look like
[ First,Middle,Full,Last]
or
[{First},{Middle},{Full},{Last}]
you can write your own method somethinglike public String getJSOnRepresentation();
and then do
response.getWriter().write(fieldPositionDaoObj.getJSOnRepresentation());
Sample example on What and how to code
Also see
http://json.org/java/
https://github.com/douglascrockford/JSON-java/blob/master/JSONString.java
https://github.com/douglascrockford/JSON-java/blob/master/JSONArray.java
https://github.com/douglascrockford/JSON-java/blob/master/JSONObject.java
I tried the below mentioned code it's working fine now.
JAVA SCRIPT:
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("userFieldPosition").disabled=false;
var response = JSON.parse(xmlhttp.responseText);
for(var i=0;i<response.length;i++){
elements += "<option value='"+response[i].fieldPosition+"'>"+response[i].fieldPosition+"</option>";
}
$("#userFieldPosition").append(elements);
}
}
SERVELET:
Gson gson = new Gson();
String json = new Gson().toJson(fieldPositionObj);
response.getWriter().print(json);
There are certain frameworks such as ExtJs which allow you to do this with out much code. The only way I can think of doing this is by placing your second drop down box inside a div tag. On selection of the 1st drop down box, call a function which will make the ajax request. Once you obtain a success response, rewrite the content of your div by creating a new drop down box with these values.
I am sendin post request from jquery like this :
$.ajax({
type: "POST",
url: "Save",
data: { conr: conr ,expiry : expiry,settings : settings}
inside servlet , i am able to get parameters (conr , expiry , settings)
but the problem is that
the settings parameter contains serialized form data : like this :
high=true&ci=false&title=qTip+as+Button+Menu&private=true&email=abc#google.com
I know that i can use string tokenizer to get data but i want to make sure that- if their is any simple way or not?
You could use the HttpComponents and let URLEncodedUtils parse it for you.
So you could just invoke URLEncodedUtils.parse(yourString,Charset.forName("UTF-8")) and you receive as return a List<NameValuePair> containing name and value associated elements. In this case something like: hight = "true", title = "qTip as Button Menu" and so on. And this all with the right decoded.
You can also use split on the settings string with "&" as a regex.
I have a JSON String stored in a database. In one of my JSP pages, I retrieve this string, and I want to be able to pass the String or the JSON object into Javascript function. The function is simply this for test purposes
function test(h){
alert(h);
}
Now I can retrieve the JSON string from the database fine, I have printed it out to the screen to ensure that it is getting it, however when I pass it in like this
<input type="button"
name="setFontButton"
value="Set"
class="form_btn_primary"
onclick="test('<%=theJSON%>'); return false;"/>
Nothing happens. I used firebug to check what was wrong, and it says there is invalid character.
So I then tried passing in the JSON object like so
Widget widg = mapper.readValue(testing.get(0), Widget.class);
Then pass in it
onclick="test('<%=widg%>'); return false;"/>
Now this will pass in without an error, and it alerts the object name, however I am unable to parse it. Object comes in like with the package name of where the widget class is stored like so
com.package.mode.Widget#ba8af9
I tried using Stringify, but that doesn't seem to work on this Jackson JSON object.
After all that failed, I tried a last resort of taking the String from the database, and encoding it in base64. However, this too fails if I do this
String test = Base64.encode(theString);
and pass that in. However if I do that, print it out to the screen, then copy what is printed out, and send that through it works, so don't quite understand why that is.
So could someone please tell me what I am doing wrong. I have tried soo many different solutions and nothing is working.
The JSON String is stored in database like this
{
"id":1,
"splits":[
{
"texts":[
{
"value":"Test",
"locationX":3,
"locationY":-153,
"font":{
"type":"Normal",
"size":"Medium",
"bold":false,
"colour":"5a5a5a",
"italics":false
}
}
]
}
]
}
Would be very grateful if someone could point me in the direct direction!!
Edit:
Incase anyone else has same problem do this to pass the JSON from JSP to the JS function
<%=theJSON.replaceAll("\"", "\\\'")%>
That allows you to pass the JSON in,
then to get it back in JavaScript to normal JSON format
theJSON = theJSON.replace(/'/g,'"');
Should work fine
I think the combination of double quotes wrapping the onclick and the ones in your JSON may be messing you up. Think of it as if you entered the JSON manually -- it would look like this:
onclick="test('{ "id":1, "splits":[ { "texts":[ { "value":"Test", "locationX":3, "locationY":-153, "font":{ "type":"Normal", "size":"Medium", "bold":false, "colour":"5a5a5a", "italics":false } } ] } ] }'); return false;"
and the opening double quote before id would actually be closing the double quote following onclick= (You should be able to verify this by looking at the page source). Try specifying the onclick as:
onclick='test(\'<%=theJSON%>\'); return false;'
You can follow the following steps
Fetch the jon string
Using the jackson or any other JSON jar file , convert the json string to json array and print the string using out.println.
Call this jsp which prints the json string
check in the firebug , you will be able to see your json .
If the Json string does not print , there can be some problems in your json format.
this is a good website for json beautification , http://jsbeautifier.org/ , really makes the string simple to read .
Thanks
Abhi