passing parameter from javascript to servlet - java

I am retrieving all the contacts of a user from gmail and yahoo, I have added the checkbox, the user needs to select the desired email id to which he need to send email. I need to collect all user selected email id's and save them in a string send that string to another servlet where I am sending emails.
I was able to add the check box dynamically but I am not able to collect the emails and save them in a string. This is the code I have written to add check box before all the emails,
kindly help me to put those selected email id's in a string
I used the following code, but still I am not able to do it.You can have a look at the demo of this app http://ec2-50-16-183-101.compute-1.amazonaws.com/SocialAuthNew/
To get the contacts from Gmail type google in the text box and for yahoo type yahoo and click on submit button
List<Contact> contactsList = provider.getContactList();
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><script type='text/javascript'>");
out.println("function getAllContacts(size){ var selected_list='';");
out.println("for(var c=0;c<size;c++){if(document.getElementById('mailCheckbox'+c).checked==true){selected_list=selected_list+document.getElementById('lblmail'+c).innerHTML+':';}}");
out.println("document.getElementById('final_mailing_list').innerHTML=selected_list;}</script>");
out.println("<title></title>");
out.println("</head>");
out.println("<body>");
for(int i=0;i<contactsList.size();i++){
System.out.println(contactsList.get(i).getFirstName()+" : "+contactsList.get(i).getLastName()+":"+contactsList.get(i).getEmail());
out.println("<h1> Imported conatcts from your mail are:-</h1>");
out.println("<input type='checkbox' id='mailCheckBox"+i+"' name='mailCheckbox'></input>");
/* out.println(contactsList.get(i).getFirstName());
out.println(contactsList.get(i).getLastName());*/
out.println("<label id='lblmail"+i+"'>"+contactsList.get(i).getEmail()+"</label>");
}
int size=contactsList.size();
out.println("<input type='button' value='GetContact' onclick='getAllContacts("+size+");'/> ");
out.println("<div id='final_mailing_list'></div></body>");
out.println("</html>");
}

Try this:
1) Wrap your email in a DOM element to make it easier to access
out.println("<span>" + contactsList.get(i).getEmail() + "</span>");
2) Using something like e.g. JQuery for normalizing access to the DOM on the client, do
function getSelectedEmails() {
var emails = [];
$('body').find('input[name="mailCheckbox"]:checked').each(function() {
emails.push($(this).closest('span').text());
});
return emails;
}
This returns the emails in an array - which you can easily concatenate into a string if you want with e.g.
var emailString = emails.join(", ");
...although I think using an array is usually better (perhaps JSON encoded if you need to serialize it).

s using array is much easier. i have used array and gave the check box name as check1 and on the click of submit button i have called the following function. this function alerts the value of the selected check boxes and passes the action to servlet
<script>
function onCallForInterview()
{
var selectedIds;
var count=0;
for (i=0; i<document.frm.check1.length; i++)
{
if (document.frm.check1[i].checked==true)
{
if(count==0){
selectedIds=document.frm.check1[i].value;
count=count+1;
}
else
selectedIds=selectedIds+","+document.frm.check1[i].value;
}
}
alert(selectedIds);
document.frm.action="<%=contextPath%>/SearchCandInfo? action=selectcanforinterview&ids="+selectedIds;
document.frm.submit();
}
</script>

A slightly more primitive way to achieve this,
Create a bunch of Check-Box as you are doing now but with the difference that all of htem should have the same name i.e. do the following correction in your code
out.println("<input type='checkbox' id='mailCheckBox' name='mailCheckbox'></input>");
Now retrieve all the values of such text boxes on your server side using following call on request object,
String[] emailIds = request.getParameterValues("mailCheckBox");
Hope this helps.

Related

How do I add user input in Plivo's SMS API?

I am using Plivo's SMS API to send SMS messages. Is it possible to have an user input prompt for “SENDERS NAME”, “RECEIVER NAME” and “MESSAGE” in Plivo’s SMS API without having them to be hardcoded before I run the .js file?
var plivo = require('plivo');
(function main() {
'use strict';
var client = new plivo.Client("<MY API KEY>", "<MY API TOKEN>");
client.messages.create(
"+1<SENDER NUMBER>", // Sender's phone number with country code
"+1<RECEIVER NUMBER>", // Receiver's phone Number with country code
"<MESSAGE>", // Message
{
method: "GET", // Method used to trigger message URL.
url: "http://example.com/sms_status/" // The URL to which with the status of the message is sent
},
).then(function(response) {
console.log(response);
}, );
})();
Plivo's Developer Evangelist here. It depends upon your use case. Ideally not hardcoding values means storing values at some place like a Google Sheet, or having a front end to accept values from a user or a database. I suggest to the easiest way at this point is to prompt users right after running your js script.
const prompt = require('prompt-sync')();
var plivo = require('plivo');
const from = prompt('Please enter source number?');
const to = prompt('Please enter destination number?');
const text = prompt('Please enter the text you would like to send?');
console.log(`User input details are, From: ${from}, To:${to}, Text: ${text}`);
var client = new plivo.Client("auth_id", "auth_token");
client.messages.create({
src: from,
dst: to,
text: text,
}).then(function(response) {
console.log(response);
});
If you'd like to use a front end to prompt the user you can try this project.
If you'd like to store values using a Google Sheet and trigger an SMS whenever a row is updated you can use an automation tool like Zapier.

Tomcat JSP file doesn't return jdbm.RecordManager data

I've been looking for a solution to this for awhile. Working on a small side project to play around mini search engines. I've created a series of java classes that crawl through a certain amount of links through a webpage and stores the information into a JDBM RecordManager HTree.
When I run a print function for the contents of this RecordManager, I can get the contents just fine, but when I try to imitate this on a JSP file on my Tomcat server, the object that is supposed to be returned by this print function is empty. (Note: I have a HTML page that sends the necessary string to this JSP file)
The DataManager object, when called, is supposed to "create and Initialize a RecordManager"
The querySimilarity function is supposed to return Vector of integer pageIDs taken from the generated RecordManager.
Any ideas? The code below is from my JSP file.
<%# page import="java.util.Vector,searchEngine.*,jdbc.*" %>
<%
out.println("The words you entered are: <br>");
String arr = request.getParameter("words");
String[] a = arr.split(" ");
Vector<Integer> pageIDList = new Vector<Integer>();
DataManager dm = new DataManager();
pageIDList = dm.querySimilarity(a);
for(int i = 0; i < pageIDList.size(); i++){
out.println(pageIDList.get(i) + "<br>");
}
%>

Weird issue when using HTML form to pass information to Java Servlet

Okay so I have two Java Servlets, one for letting the user select which images to delete (DeleteImages) and another for actually deleting the images (HandleDelete). DeleteImages displays all the images in the container with a checkbox HTML form for the user to select which images to delete. Then, using POST the servlet passes that information along to HandleDelete which iterates over which images it received and deletes them.
I actually had this working, but then I tried to change the structure of the code (have DeleteImages forward to a .jsp file that output the HTML form which would then forward to HandleDelete) but that didn't work out, so I'm trying to go back to the old way and now it's not working even though I'm pretty sure it's the same as I had before.
From DeleteImages:
// retrieve image files
List<? extends SwiftObject> objs = os.objectStorage().objects().list("imageFiles");
out.println("<!DOCTYPE html><html><head><title>Object Storage - Delete</title><link rel='stylesheet' href='stylesheet.css' type='text/css' /></head>"
+ "<body>
<h1>Select images to Delete from container</h1>
<form method='POST' enctype='multipart/form-data' action='/ImageUpload/OSHandleDelete'>");
for (SwiftObject o : objs) {
// omitted code that gets the image's name, date last modified, and filepath (all Strings, I know this works)
out.println("<b>Name:</b> " + name + "<br/> <b>Time of Upload:</b> " + date + "<br/>"
+ "<input type='checkbox' name='"+name+"'> "
+ "<img src='"+filepath+"' alt='' style='max-width:800px;' /> <br/> <br/> <br/> ");
}
out.println("<input type='submit' value='Delete Images' /></form>");
out.println("</form> <br/> <br/> <div><br/><a class='return' href='index.jsp'><b>Click here to return home</b></a><br/><br/></div> <br/> <br/></body></html>");
From HandleDelete:
Enumeration<String> parameterNames = request.getParameterNames();
if (!parameterNames.hasMoreElements())
System.out.println("no parameters (null)");
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
System.out.println("*****************");
System.out.println("parameter: " + paramName);
String[] vals = request.getParameterValues(paramName);
if (vals == null)
System.out.println(" vals is null for " + paramName);
else {
for (int i = 0; i < vals.length; i++) {
System.out.println(" vals["+i+"]: " + vals[i]);
}
}
Right now I don't have HandleDelete actually doing anything besides print statements. This is because I use request.getParameter("<name>") to find out whether the user checked image of <name> (i.e. if it's null it was not checked but if it's not null it was checked).
The HTML form displays perfectly with the images and everything. My problem is that no matter what's checked in the HTML form, HandleDelete always prints to the console no parameters (null) meaning nothing was passed from DeleteImages to HandleDelete. I have a feeling the problem comes from either (1) the setAttribute statement in DeleteImages or (2) something with the HTML form. I've done a lot of searching and I'm pretty confident what I have is right though and I really can't figure out what's causing this issue (especially since I'm pretty sure this is exactly what I had before and it worked). Does anyone have any ideas?
I found the error: I included enctype=multipart/form-data
Not exactly sure why that caused the error but I removed that part and now it's passing the parameters perfectly. Thanks for your help guys!

Android - check if html code contains div with specified id

I need to make sure that a certain website code contains a div like this one:
<div id="iframe-content"> some code here... </div>
I tried this way:
elementTry = doc.select("div#iframe-content");
and next I stored it into the String
String someText;
someText = elementTry.toString();
and tried to show the output via Toast, but it gives me "null". I am sure the website contains the div with this id, so
what can I do to fix it?
EDIT:
Toast code
Toast.makeText(getContext(), "Passed: "+ someText, Toast.LENGTH_LONG).show();
Try using this
elementTry = doc.select("div#iframe-content");
String someText;
someText = elementTry.text();
Hope this helps

Input values to textfields, stream back to website

I connected to a website, used JSoup to find the "textfield" ID's, input the values, now i need to stream it out.
Can someone please help me with the correct coding to stream the "modified" doc back to the website?
if (source == enter2)
{
String URL = "http://www.clubvip.co.za/Login.aspx";
Element number;
Element pass;
Element keyword;
try {
Document doc = Jsoup.connect(URL).get();
number = doc.getElementById("ctl00_ContentPlaceHolder1_CellNumberRadText").attr("value", "number");
System.out.println(number);
pass = doc.getElementById("ctl00_ContentPlaceHolder1_PasswordRadText").attr("value", "password");
System.out.println(pass);
keyword = doc.getElementById("ctl00_ContentPlaceHolder1_KeyWordRadText").attr("value", "keyword");
System.out.println(keyword);
Why are you doing it like this?
If you need to login to that webpage, simply take arguments and send them via HTTP POST request to page where <form> points to
which is <form method="post" action="login.aspx">
Instead of what you are doing:
Jsoup.connect("http://www.clubvip.co.za/Login.aspx")//
.data("ctl00_ContentPlaceHolder1_CellNumberRadText", "number",
"ctl00_ContentPlaceHolder1_PasswordRadText", "password",
"ctl00_ContentPlaceHolder1_KeyWordRadText", "password").post();
not tested, so possibly not 100% correct...

Categories