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.
Related
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]);
I'm having some troubles with different back-end processing of POST rest calls. I have two different objects which are updated through two different POST methods in my back-end. I catch the objects as a JsonNode, and in order to parse the attributes which I need to update, i create an iterator like so :
final Iterator<String> fieldNames = attributes.fieldNames();
The problem comes when I send my data from angular, in one case I need to explicitly send it like angular.toJson(data) in order to properly grab all the field names, and in the other case I just send the data (without the angular json conversion). Why is this behavior occurring ? Does this have to do with how I create the $http post call ? Here are the two different calls from angular:
$http.post(URL, angular.toJson(data)).success(function(data){
/*whatever*/ }).error(function(data) {
/*whatever*/ });
//Second call looks like this
var promise = $http({method: 'POST', url:URL, data:data, cache:'false'});
//this one i resolve using $q.all
I truncated the code to just the important stuff. My data is created like this currently(tried multiple ways in order to skip the need for toJson):
var data = "{\"Attribute1:\"+"\""+$scope.value1+"\","+
"\"Attribute2:\"+"\""+$scope.value2+"\"}";
How do I need to send the json data in order for it to correctly be converted to a JsonNode in my back-end, so I can properly iterate the fieldNames ?
I did manage to come to a common solution which consumes the json correctly in my back-end. I declared my json objects in angular like this :
$scope.dataToSend = {
"SomeAttribute" : "",
"SomeOtherAttribute" : ""
};
And then added my values like so :
$scope.dataTosend.SomeAttribute = someValue;
$scope.dataTosend.SomeOtherAttribute = someOtherValue;
No longer need to send the data with angular.toJson().
I am combining wicket and jQuery for some project.
I have in HTML:
<a wicket:id="link" testAttr="test"></a>
And using jQuery I modify this attribute when other components on the page are clicked. My question here is how to obtain the current value of attribute "testAttr" from Java? I am fetching the value on every ajax call and see with inspect element that is changed, so no problem with that.
I have tried with getMarkupAttributes() but I always get value "test" and not the current one which I see on the page with inspect element. Also tried with AttributeModifier and Appender, onComponentTag, but had no luck.
Does anybody have an idea what to do here?
You have to send the current attribute value to the server as a 'dynamic extra parameter':
link.add(new AjaxEventBehavior("click") {
updateAjaxAttributes(ARA ara) {
super.updateAttributes(ara);
ara.getDynamicExtraParameters()
.add("return {'q' : jQuery('#' + attrs.c).attr('testAttr') };");
}
onEvent(ART art) {
RequestCycle requestCycle = RequestCycle.get();
String val = requestCycle.getRequest()
.getRequestParameters()
.getParameterValue("q")
.toString();
// ...
}
});
im trying to figure out how to get javascript to grab each users "twitchname" field from their profile, and have it add it to the list of streamers.
Currently, we have to type in everyone's channel name in the JS code Below: console_purgatory being the name, but we have added a profile field where they add it to their profile, we just want to get that field for every user and add it to here.
var members = ['console_purgatory'];
This is the PHP thats currently able to display the users twitch name.
<?php echo xprofile_get_field_data( 'TWITCH TV Url', $current_user->ID ); ?>
Im very new to JS so if you need more info please let me know.
Thanks.
I think there are two ways.
First
You can place PHP code inline in your JavaScript in .php files. THis is not very nice looking mixture of code but it works.
<script>
var members = ['console_purgatory'];
var id = <?php echo xprofile_get_field_data( 'TWITCH TV Url', $current_user->ID ); ?>
</script>
Second
You can use ajax requests to separate services to obtain ID.
service.php contains
<?php
echo xprofile_get_field_data( 'TWITCH TV Url', $current_user->ID );
script.js - this uses jQuery.ajax() function (more here)
var members = ['console_purgatory'];
var id = undefined;
$.ajax({
url: "service.php",
data: data,
async: false,
success: function( data ) {
id = data;
}
});
console.log(id); // <-- id is equal to 'data' which is equal to echo in service.php
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