I have found other question regarding on this, but still im having a problem,When i check getParamerterValues, its always return null, and i think im having trouble redirecting it to my controller.Bare with me, in new to web app.
arr = [];
$(document).on("click","#idhere",function(){
$.post("servlet.html","ids="+arr+"",function(response){
});
});
or is there something like converting array of javascript to JSON of array in JSP so i can pass it to my servlet?
String arr [] = request.getParameterValues("ids");
if(arr != null){//this line doesnt return true even my array contains item}
change
String arr [] = request.getParameterValues("arr");
to
String arr [] = request.getParameterValues("ids");
Its always return null, and i think im having trouble redirecting it to my controller
I couldnt see any code to pass the values to the controller. In your jquery function , you have something like this $.post("servlet.html","ids="+arr+"",function(response){
It is not possible to post a value to the other html file from jsp. if you are trying to pass the values to the servlet.
try something like this ,
$(document).on("click","#idhere",function(){
$.post("servletName","ids="+arr+"",function(response){
});
});
Note: servletName refers to the url , mapped in your web.xml for the servlet you are trying to post the data.
Also make sure you jquery function is posting the data correctly to the controller through the browser console .
As the examples below show, the post method wants an json object as the data parameter.
This should do the job
$.post("servlet.html",{"ids": arr.join()},function(response){
});
Examples: Example: Request the test.php page, but ignore the return
results.
1 $.post( "test.php" ); Example: Request the test.php page and send
some additional data along (while still ignoring the return results).
1 $.post( "test.php", { name: "John", time: "2pm" } ); Example: Pass
arrays of data to the server (while still ignoring the return
results).
1 $.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } ); Example:
Send form data using ajax requests
1 $.post( "test.php", $( "#testform" ).serialize() );
see http://api.jquery.com/jquery.post/
Related
I'm currently working on an application built in Scala with Spray routing.
So for dealing with a JSON document sent over POST, it's pretty easy to access the variables within the body, as follows;
respondWithMediaType(`application/json`) {
entity(as[String]) { body =>
val msg = (parse(body) \ "msg").extract[String]
val url = (parse(body) \ "url").extractOpt[String]
However, I'm now trying to write an additional query with GET, and am having some issues accessing the parameters sent through with the query.
So, I'm opening with;
get {
respondWithMediaType(`application/json`) {
parameterSeq { params =>
var paramsList = params.toList
So, this works well enough in that I can access the GET params in a sequential order (just by accessing the index) - the problem is, unfortunately I don't think we can expect GET params to always be sent in the correct order.
The list itself prints out in the following format;
List((msg,this is a link to google), (url,http://google.com), (userid,13))
Is there any simple way to access these params? For example, something along the lines of;
var message = paramsList['msg']
println(message) //returns "this is a link to google"
Or am I going about this completely wrong?
Apologies if this is a stupid question - I've only switched over to Scala very recently, and am still getting both acquainted with that, and re-acquainted with Java.
What I usually do is use the parameters directive to parse the data out to a case class which contains all the relevant data:
case class MyParams(msg: String, url: String, userId: Int)
parameters(
"msg".as[String],
"url".as[String],
"userId".as[Int]
).as[MyParams] {
myParams =>
// Here you have the case class containing all the data, already parsed.
}
To build your routes you could use the parameters directives. I'm not sure if this is what you're looking for, anyway you could use them as:
get {
parameters('msg) { (msg) =>
complete(s"The message is '$msg'")
}
}
Spray directives can be easily composed so you can use combine them in any way you want.
I hope that helps you.
I am trying to send some data from jsp to servlet using ajax call; In my java script I have the following method:
function sendMessage(){
var cellPhones=[];
var title=$('#subject').val();
var text=$('#smsText').val();
var groupsName=$('#dg').datagrid('getSelections');
for(var i=0;i<groupsName.length;i++){
cellPhones.push(groupsName[i].cellphone);
}
alert(cellPhones);
$.ajax({
type:"POST",
url:"<%=basePath%>/SendMsgServlet?flag=sendSms",
data:{
title:title,
text:text,
cellPhones:cellPhones
}
}).done(function(){
alert("ok");
})
}
and in my doPost method I have:
if("sendSms".equals(flag.trim())){
String title=request.getParameter("title");
String text=request.getParameter("text");
String[] cellPhones=request.getParameterValues("cellPhones");
this.sendSms(title,text,cellPhones,request,response);
}
The problem is that the cellPhones is null, nut the alert is not null, Could anybody help me please?
Why dont you create a class, which will have array as an attribute. set the field value and then set the obj to request. This will not only help you in the servlet but can also be used incase you want to send some data back to your jsp.
I solved the problem, All I had to do was to convert cellphones to string,no need to hidden element I just added this line of code:
var cellPhone=cellPhones.toString();
At ajax you are sending values as array like:
url= "cellPhone[]=121212&cellPhone[]=121212&cellPhone[]=121212"
But, at servlet you are trying to get value as single value. You need to get values as array []. Try,
String[] cellPhones=request.getParameterValues("cellPhones[]");
|- Use array sign
I googled a lot but I can't solve my problem. I'm new on jsp, in my application in the main jsp I retrive from a table an array of strings (portfolio items) through a scriptlet in javascript. I have to POST the array to another jsp and passing as parameter into a java method to calculate some portfolio stats (historical data are stored in src directories). The code I wrote is:
//obj is the array
var obj= $('#tablePtf td:nth-child(1)').map(function(response){
return $(this).text();
}).get();
//POST
$.ajax({
type: "POST",
url: "calculatePtf.jsp",
data: {portfolio:obj},
success: function(){
alert('ok');
},
error: function(){
alert('error');
}
});
on the server side (caluclatePtf.jsp):
String[]r=request.getParameterValues("portfolio");
calculate(r);// my method
This causes the NullPointerException on 'r' , so I'm wrong in posting the array. The 'obj' array is not empty (tested).
I tried also dynamically writing hidden inputs setting the 'name' attribute to 'portfolio' and submitting the form but the exception persists.
Where am I wrong? Sugestions for better solution are well accepted. Thanks
Solved, the problem wasn't POST but the starting function for retrieving obj array. Just changed in:
var obj=$('#tablePtf td:nth-child(1)').text();
and now works as aspected.
I am trying to capture data from the google analytics cookie and have it populate hidden fields which will then send that information to my database in Silverpop. I have the UA code inserted on my webform, and via google analytics I can see that there is someone on the site(me). But I have tried several variations of javascript I have found on here to extract the campaign and source from the google cookie, and on form submit, have that information sent to my database. Any help would be greatly appreciated. Thank You
Okay, just gonna throw it out there that since GA uses first party cookies, you can use server-side code to parse the cookie. I don't know java well enough to give you that code, but the info is stored in the __utmz cookie and the value looks something like this:
21733335.1344455611.17.2.utmcsr=camp_source|utmccn=camp_name|utmcmd=camp_medium|utmctr=camp_term|utmcct=camp_content
The leading numbers and dots are a hash and visitor id and other stuff you don't really need to worry about, so you can just strip it. Then you can just explode at the pipe and will have an array of name=value pairs that you can further split at the equal sign.
I just mention this because it would be more efficient and tamper-proof to do it server-side. You don't need to even worry about passing it in a form; you can do it on the very first page view request.
But if you really want to do this with client-side code, or need some guidance about parsing the cookie, here is the javascript example:
<script type='text/javascript'>
// function to retrieve the GA campaign values
function getGACampaignCodes() {
var cv = {};
var utmz=document.cookie.match(/ __utmz=([^;]*)/);
if (utmz!=null&&typeof(utmz[1])!='undefined') {
utmz = utmz[1];
utmz = utmz.replace(/^[0-9.]+/,'').split('|');
for (var c=0,l=utmz.length;c<l;c++) {
var cn = utmz[c].split('=');
switch (cn[0]) {
case 'utmcsr' : cv.source=cn[1];
case 'utmccn' : cv.name=cn[1];
case 'utmcmd' : cv.medium=cn[1];
case 'utmctr' : cv.term=cn[1];
case 'utmcct' : cv.content=cn[1];
}
}
}
return cv;
}
// function to populate the hidden fields
function addGAToFormFields() {
var cv = getGACampaignCodes();
var f = document.forms['someForm'];
for (c in cv)
if (cv.hasOwnProperty(c))
f['ga['+c+']'].value = cv[c];
}
// call this when document is ready
addGAToFormFields();
</script>
</body>
</html>
Not sure what the java version would look like but this is an example of the posted vars in php:
Array
(
[ga] => Array
(
[source] => camp_source
[name] => camp_name
[medium] => camp_medium
[term] => camp_term
[content] => camp_content
)
)
I'd like to query a .cfm page via Android but I'm not sure what method I should be using to do so - any suggestions?
Example:
http://www.sheriff.org/apps/arrest/results.cfm?lname=smith&fname=
P.S.
Would I use something along the lines of this?
http://androidexample.com/AsyncroTask_Example_To_Get_Server_Data_-_Android_Example/index.php?view=article_discription&aid=59&aaid=84
use an ajax call with the url with the appropriate first and last name parameters, and then extract the result table from the return value.
see a working jsfiddle sample here: http://jsfiddle.net/FhHXK/
code:
$('#get').click(function () {
$.ajax({
url:'http://www.sheriff.org/apps/arrest/results.cfm?lname=a&fname=b',
type: 'GET'
}).done(function (data){
var result = $(data).find('table.datagrid');
console.log(result.html());
$('body').append(result);
});
});