sending javascript array to jsp using ajax - javascript

So, I'm working on a MULTIPLE CHOICE QUESTION entry page and i want to handle it completely with ajax. I want to be flexible with the number of options the question has.
Here's the jquery part:
$("#QuestionModPageSubmitButton").click(function(){
var QuesDesc=$("#QuesDesc").val();
var Options=[];
var QuestionId=$("#QuestionId").attr("data-id");
var CorrectOption=$('input[type="radio"]:checked').val();
var TotalOptions=$("#TotalOptions").attr("data-total");
var SubjectId=$("#SubjectId").attr("data-id");
for(var i=0;i<TotalOptions;i++)
{
Options.push($("#Option"+i).val());
}
$.ajax({
type:"POST",
url:"ajax/ModifyQuestion.jsp",
data:{
Subject:SubjectId,
QID:QuestionId,
Question:QuesDesc,
OptionValues:Options,
Correct:CorrectOption,
TotalOptions:TotalOptions},
});
});
I want to sent the Options Array to the jsp page "ModifyQueston.jsp".
Here's the jsp code i use for reading the sent data:
int SubjectId=Integer.parseInt(request.getParameter("Subject"));
int QuestionId=Integer.parseInt(request.getParameter("QID"));
String Question=request.getParameter("Question");
String[] Options=request.getParameterValues("OptionValues");
int CorrectOption=Integer.parseInt(request.getParameter("Correct"));
int TotalOptions=Integer.parseInt(request.getParameter("TotalOptions"));
But with these codes I'm not able to read the array in the jsp page. I get NullPointerException when i try to read the length of the Options array or when i try to read values by providing index.
I guess the script part of sending the data to jsp is fine. So the question is how to get it into jsp page.
I tried converting the array into a single string by separating each value with a '-' and then reading it using getParameter() function and then using split() function to separate it back to Array.
Script:
var OptionsString="";
for(var i=0;i<TotalOptions;i++)
{
Options.push($("#Option"+i).val());
OptionsString+=(Options[i]+((i<TotalOptions-1)?" - ":" "));
}
JSP:
String[] Options=(request.getParameter("OptionValues")).split("-");
It works fine. But I don't want to do it this way because if any of the options already contains '-' the Code will crash.
So, how to get this done?

Okay, so after a couple of weeks of research I found out a way to send the array from js to jsp. The previous code needed just a little modification.
Here's the js part which needed modification.I just had to add brackets as in arrays, in the data section.
$.ajax({
type:"POST",
url:"ajax/ModifyQuestion.jsp",
data:{
Subject:SubjectId,
QID:QuestionId,
Question:QuesDesc,
Correct:CorrectOption,
"Options[]":Options
},
});
Notice that I wrote Options as "Options[]". This makes jsp understand that the variable being sent is an array.
Now, the jsp page didn't really require much modification.
String[] Options=request.getParameterValues("Options[]");
And any further operations can be performed as normal strings.
So, yeah that worked for me!..

You can sending multiple value by ajax. From the controller end (for spring framework) you just save it in a string. the data will bind with comma separated values. to do that, you need an array from javascript end, i mean your jsp side.
for checkbox you can use:
var idVal = [];
var i = 0;
$('.case:checked').each(function() {
idVal[i] = $(this).val();
i++;
});
From controller side you can get the value:
String[] id = req.getParameter("id_").split(",");
As the same way you can do this for dropdown (options).This is worked for me when using spring framework.
Thanks.

Related

Java Script + JSON Parsing and converting into Array

I'm looking for help in converting a particular elements in JSON message to an array using java script at run time. We wanted the script to be more generic. Actually we were trying the following which worked for single element and while changing it to handle for multiple elements at run time its not working.
//Working for Single element - Static
var bodyContext = JSON.parse(response.content)
if(bodyContext.companylist.company.constructor !== Array){
bodyContext.companylist.company = [bodyContext.companylist.company]
}
The above code works and converts Company in JSON message as a Array, Where as the below we tried for multiple elements is not working
//Not Working for multiple elements - dynamic
var bodyContext = JSON.parse(response.content)
var elementName = "";
//Loop runs every time and changes the value of elementName at every iteration
if(bodyContext.elementName .constructor !== Array){ //not working
bodyContext.elementName = [bodyContext.elementName] //Not working
}
instead of looking for "bodyContext.companylist.company" and converting into Array, "bodyContext.elementName" is checked and added to the bodycontext object.
how to handle this. ElementName variable along with JavaScript object is not recognized.
Please help.
you can JSON.parse(data) then you can fetch data from Javascript object like
$.each(Obj,function(key,value){
});
You'll want to use
bodyContext[elementName]
since
bodyContext.elementName
looks for a field in bodyContext named elementName, not the a field named after the value in elementName.
Also, you initialize elementName with "", and this won't match anything on the first iteration.

pass JS Objects in URL

I have already searched from this question in SO. But none of the answers worked for me, so I am posting this once more in the hope to find an answer that works for me.
Is there a way to pass JS/JSON objects through URL? Suppose I have a JS Object like so:
var jObj = {"color":"red","shape":"square"}
Now suppose I want to pass it to a URL like so:
window.open("/process/jObj"); //here I want the var defined above to be passed
I tried various options like JSON.stringfy, encodeURIComponent, escape..but I am not able to pass it around. Any idea how this can be achieved in pure JS?
I would like to pass it so that in the next page (process.php) such that there I can get the values of jObj and use it for further processing. Basically I am looking for an option where I can pass the object to the effect of ?color=red&shape=square without having to squash and reformat the object too much
Here is one thing you can do
var jObj = {"color":"red","shape":"square"}
var urlParam = []
for (var i in jObj){
urlParam.push(encodeURI(i) + "=" + encodeURI(jObj[i]));
}
window.open("/process/?" + urlParam.join("&"));
this should produce your result

How to parse JSON Array in java script

I am returning SQL Query result as a JSONArray to a JSP page. Now i want to show the data. I have written a code but it is working fine only for 23 objects in the JSONArray if JSONArray contains more the 23 object eval or JSON.parse function doesn't work. Please let me know how to solve this problem.
Below is the JS code i have written to iterate over this JSONArray.
var data = '<%=(JSONArray) request.getAttribute("resultArray")%>';
data = eval("(" + data + ")");
$(document).ready(function() {
var table = $('<table/>').appendTo($('#column'));
var rows = $('<tr/>').appendTo(table);
$.each(data, function(rowid, row) {
var rows = $('<tr/>').appendTo(table);
$.each(row, function(column, data) {
($('<td/>').text(data)).appendTo(rows);
})});
});
Just don't let JSP print it as a JS string syntax within quotes (which obviously needs to be parsed in order to get a JS object). Get rid of those quotes. JSON is already in proper JS object syntax. That's also all what "JSON" stands for.
var data = <%=request.getAttribute("resultArray")%>;
$(document).ready(function() {
// ...
});
By the way, using scriptlets in JSP is a poor practice. If you're on JSP 2.0 already (which is out for almost a decade already), just use EL.
var data = ${resultArray};
$(document).ready(function() {
// ...
});
Note, also here, just don't quote it. It becomes otherwise a JS string instead of a JS object.
Unrelated to the concrete problem, is it absolutely necessary to introduce the extra JSON/jQuery step here? Why don't you just use for example JSTL to let JSP generate the desired HTML in the server side instead of JS/jQuery in the client side?

Parsing malformed JSON with Javascript

I want to parse this content using Javascript. The data looks like this:
{"ss":[["Thu","7:00","Final",,"BAL","19","ATL","20",,,"56808",,"PRE4","2015"],["Thu","7:00","Final",,"NO","10","GB","38",,,"56809",,"PRE4","2015"]]}
Every single tutorial online teaches you how to parse JSON using Twitter, but I am not quite sure how parsing with JSON works.
I would like to set this up on a website to view the NFL team scores for a fun project and a good learning experience about parsing JSON, as I could care less about Twitter stuff.
Is this possible? Any good tutorials to start with? Even some starting code?
Generally speaking, you can use JSON.parse to do this. However, that snippet that you have does not appear to be strictly valid JSON (as seen here: http://jsfiddle.net/yK3Gf/ and also by validating the source JSON here: http://jsonlint.com/).
So you will either need to parse it by hand, or get nfl.com to fix up their JSON.
As an alternative, their JSON does parse successfully when using eval(), so you could parse it with something like:
var parsedData = eval('(' + jsonData + ')');
...as shown here: http://jsfiddle.net/yK3Gf/1/
Though be aware that parsing JSON in this way is generally frowned upon (particularly when the data being parsed is being delivered by a third-party source), as it leaves you open to XSS attacks should the data happen to include any executable code inside of it.
I am in a similar position - non javascript expert working on a fun project to familiarize myself with javascript, ajax, and json.
I took three different steps to handle the problem. I welcome any feedback on improving the solution.
The first step is to query the nfl site to pull down the scores. Because the source of the json, the nfl site, is different from your site, you will have to work around the javascript security constraints against cross domain querying. I found this stackoverflow link to be a good reference. I used JSONP for the workaround. I used http://whateverorigin.org/ as the indirection site.
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://www.nfl.com/liveupdate/scorestrip/scorestrip.json') + '&callback=?', handleQueryForScoresResult);
As others have pointed out, the nfl site returns invalid json data. The following sample line illustrates the problem:
["Sun","4:25","Final",,"TEN","7","MIN","30",,,"55571",,"REG5","2012"],
Notice the empty array element values (the repeated commas with no data in between). So in my json callback function, I corrected the data by adding empty strings (two double quotes) to repeated commas before calling jquery to parse the json data:
function handleQueryForScoresResult(data) {
var jsonStr = data.contents;
jsonStr = jsonStr.replace(/,,/g, ',"",');
jsonStr = jsonStr.replace(/,,/g, ',"",');
var scoresData = jQuery.parseJSON(jsonStr).ss;
.
.
.
}
Lastly, I created GameScores object to encapsulate the json data.
function GameScore(scoreData) {
this.scoreData = scoreData;
scoreData[2] = scoreData[2].toLowerCase();
scoreData[5] = parseInt(scoreData[5]);
scoreData[7] = parseInt(scoreData[7]);
}
function GameScore_getAwayTeam() { return this.scoreData[4]; }
function GameScore_getHomeTeam() { return this.scoreData[6]; }
function GameScore_isFinal() { return this.scoreData[2]=="final"; }
function GameScore_getHomeTeamScore() { return this.scoreData[7]; }
function GameScore_getAwayTeamScore() { return this.scoreData[5]; }
function GameScore_doesHomeTeamLead() { return this.scoreData[7]> this.scoreData[5]; }
function GameScore_doesAwayTeamLead() { return this.scoreData[5]> this.scoreData[7]; }
function GameScore_getWeekId() { return this.scoreData[12]; }
GameScore.prototype.getHomeTeam = GameScore_getHomeTeam;
GameScore.prototype.getAwayTeam = GameScore_getAwayTeam;
GameScore.prototype.isFinal = GameScore_isFinal;
GameScore.prototype.getHomeTeamScore = GameScore_getHomeTeamScore;
GameScore.prototype.getAwayTeamScore = GameScore_getAwayTeamScore;
GameScore.prototype.doesHomeTeamLead = GameScore_doesHomeTeamLead;
GameScore.prototype.doesAwayTeamLead = GameScore_doesAwayTeamLead;
GameScore.prototype.getWeekId = GameScore_getWeekId;
I only added a few accessors as I did not need most of the data. Your needs may vary.
We are using mootools for stuff like that, but you can do it it plain JavaScript as well: http://www.json.org/js.html.
Let's assume you already have a valid JSON String (jsonString) to parse. (If you don't know how to retrieve a String to parse using XMLHttpRequest from the given url you will have to look into that first.)
With plain JavaScript you will have to add Douglas Crockford's JSON library (or something similar) in order to provide a parsing Function if there is no native implementation:
var json = json_parse(jsonString) ;
link
With a JavaScript library like jQuery this would be
var json = $.parseJSON(jsonString) ;
Now, traversing the resultant JSON Object is a whole other issue, because you will have to know its structure before you can retrieve specific data.
In this particular case -- if it was indeed well formed -- you would have to do the following:
var data = json.ss ;
for(var i = 0 ; i < data.length ; i++) {
var entry = data[i] ;
var day = entry[0] ; //!! the Arrays seem to have a format where the first entry always contains the data and so forth...
/* ... */
// then do something with the data bits
}
Your main problem is that fact that the JSON your pulling in is malformed or not valid according to RFC 4627.
What you can do is grab the copy the JSON data and format it using this tool http://www.freeformatter.com/json-formatter.html
After you have the formatted version then you can use the jQuery ajax call
$.ajax({
url: "your-formatted.json",
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.ss.length; i++) {
document.write("Day: " + data.ss[i][0]);
document.write("<br/>");
document.write("Time: " + data.ss[i][1]);
document.write("<br/><br/>");
}
}
});
You shouldn't actually use document.write in your application. This is only for example purpose of displaying the data.
For this specific issue (the empty indexes within the arrays from the JSON response) I did a regex replacement with a lookahead assertion. Considering that request contains the XMLHttpRequest:
request.responseText.replace(/,(?=,)/gm, ",\"\"")
This will turn ,, into ,"", and will also work in case there are more commas in sequence, so ,,, becomes ,"","",. You can use JSON.parse() afterwards.
This malformed JSON can be parsed by the dirty-json NPM package (I am the author).
You can test a demo of the parser here: https://rmarcus.info/dirty-json
The parser interprets the JSON in your original question as equivalent to the following valid JSON:
{
"ss": [
[
"Thu",
"7:00",
"Final",
"BAL",
"19",
"ATL",
"20",
"56808",
"PRE4",
"2015"
],
[
"Thu",
"7:00",
"Final",
"NO",
"10",
"GB",
"38",
"56809",
"PRE4",
"2015"
]
]
}

Process hash fragment using JavaScript

i want to get hash parameters value in my java script
for example my url should be like that
www.example.com/#!mydata=data&myopt=option
i want to get mydata in variable which will be "data" as value,
and myopt "option"
iam trying to implement google ajax cowling like here
Google Code
and i have tried to implement jquery address
but with big fail so help me either by solving 1st part or give me simple walk through tutorial to implement jquery address to my ajax requests ,thank you
This piece of code will convert any well formed (i.e. properly url-encoded) request string into an object literal with values parsed.
var s = "#!mydata=data&myopt=option";
var o = {};
$.each(s.substr(2).split('&'), function(i, elem) {
var parts = elem.split('=');
o[parts[0]] = parts[1];
});
Then you can access values like o.myopt
UPDATE
Of course, to get the value from browser's address, you should use
var s = window.location.hash;

Categories

Resources