I am trying to make a mobile application. One page “allpeople.html” has a set of links which are generated via a loop from based on Information from XML file.
Basically what I want is when the user clicks the link the variable is sent to a jquery (ajax) script on the “showResult.html” page which will have a script (again jquery and Ajax)
So it is linke this
var value1=John;
var value2=Male;
//post variables to the function “theCustomFunction” on resultspage.html
$.post('resultspage.html', function(theCustomFunction:”value1”,”value2”) {
});
//on the showResult.html page
<script>
function : theCustomFunction( value1,value2) {
var name= value1;
var sex= value2;
etc ....
}
</script>
I think jquery is the best. you can send data this way too:
$.post('resultspage.html', {name:'John',sex:'male'});
you can use variables too:
var value1='John';
var value2='Male';
$.post('resultspage.html', {name:value1,sex:value2});
Related
I'm trying to send a JSON object to a JSP to parse. The JavaScript code is:
function sendData(field1, oper1, value1, field2, oper2, value2, field3, oper3, value3){
var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}, function(response){alertHere(response)});
}
function alertHere(){
window.alert("Post Successful!")
}
My submit button is:
<input type="submit" value="SEARCH" name="submit" class="srchbutton" onclick="sendData(document.getElementById('field1').value, document.getElementById('oper1').value>
There are several more fields passed in the JavaScript button on click, I just didn't want to post that long of a line.
When I try to post with text data in the form, my web developer console flashes the path to my JSP really quickly then disappears. It's too fast to see the error. If there's no data, the post is successful, as my alertHere function in $.post() is called correctly. I'm not sure if I'm missing something.
Assuming you have a servlet on the server side which handles the data you are sending from the jsp page you could create a pseudo-class using javascript, then parses it to json and finally sends it to the server. for example:
javascript and jQuery
function SomeClass (){
this.field1 = $("#field1").val();
this.oper1 = $("#oper1").val();
this.value1 = $("#value1").val();
// etc. for every field you want to send
}
note: i'm assuming every field have an id.
function alertHere(){
window.alert("Post Successful!")
}
jQuery and ajax
$("#someID").click(function(){
event.preventDefault(); <-------- if you replace the submit button for a simple button,
you don't need to do this.
var formData = new SomeClass();
$.ajax({
url:"ServletName",
data: JSON.stringify(formData),
dataType:"json",
}).done(function(response){
alertHere(response);
});
});
html
<input type="submit" value="SEARCH" id="someID" name="submit" class="srchbutton">
Try changing this line of code
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}
To
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:Json.stringify(formData)}
Not entirely sure if this would work, Just a suggestion.
Figured it out. The problem was that I wasn't passing my "response" to my success function, so:
function alertHere(){
window.alert("Post Successful!")
}
should have been:
function alertHere(response){
window.alert("Post Successful!")
}
It was probably posting correctly, but I wasn't getting a success because the response wasn't getting passed.
I get the JSONOject from my bean in my helper class.
Inside helper
public JSONObject init() throws Exception{
// initializations codes are here
JSONObject json = JSONObject.fromObject(bean);
return json;
}
Then I need to access above JSONObject inside a jsp calling through ajax request when loading the jsp(to assign javascript variable like bellow)
inside jsp
$(document).ready(function(){
var VAR_JSON = // need to get the JSON through AJAX
});
previously I had a code like this.
<script type="text/javascript">
var VAR_JSON = <%=helper.init()%>
</script>
how can I achive this by AJAX ?
thanks in advance..!!
First of all, stop thinking JSP. The JSP is (part of) what executes on your server when a request is being handled. That in turn returns a response to the browser (usually a webpage); your JavaScript (and therefore your AJAX request) run in the user's browser on that webpage, not in your JSP.
jQuery provides a function specifically designed for getting JSON through an AJAX request; it's called jQuery.getJSON(). You'd use it something like this:
<script type="text/javascript">
$(document).ready(function() {
var VAR_JSON;
function yourFunction() {
// do something with VAR_JSON here
}
$.getJSON('yoururl.do', function(response) {
VAR_JSON = response;
yourFunction();
});
});
</script>
It's important to note that you can't do var VAR_JSON = $.getJSON() because the function is asynchronous, and therefore doesn't return the JSON (it returns something else - see the documentation linked above). You instead need to provide a callback function that will execute when the asynchronous request returns a successful response, which will then set your variable and call another function that uses it.
Also note that you won't need to call something like JSON.parse() because jQuery does that for you; you've told it you're expecting JSON back so it parses that string to get the resulting object or array, which is then in turn passed as an argument to the callback function.
I am newbie to external javascript files (*.js). Basically I have my JSP ready but my manager wants me to add graphics in it.
So I found some *.js files. But I don't know how to communicate between them and my JSP page.
I want to pass data from jsp to external .js file.
Is there any mechanism to do that?
For e.g:-
Demo.jsp
out.print(request.getAttribute("Name"));
Now I want use/pass/set above value to main.js file how to do that?
<script type="text/javascript">
var myJavascriptVariable = <%= request.getParameter("Name")%>;
//or .getAttribute("Name")
</script>
This could do the trick, it will make a global Variable which could be accessed in main.js. When you have GET Parameters you could also use only JS:
var paramarr = window.location.search.substr(1).split("&");
var params = {};
for (var i = 0; i < paramarr.length; i++) {
var tmparr = paramarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
or a bit shorter:
var params = {};
// parse URL's GET parameters and iterate over them
window.location.search.substr(1).split("&"),forEach(function(el) {
var kv = el.split('"'); // split into [ key, value ] array
params[kv[0]] = kv[1];
});
Now you can access the parameter in JS via:
params['name']
Personally I would use AJAX (e.g. with the help of JQuery) to get Data for my JavaScript files, you can look at that at http://api.jquery.com/category/ajax/shorthand-methods/ (2018 edit: kust use native ajax calls or whatever JS framework is hyped this week ;-) )
If you are using .js file you can't write jsp sriptlet in it.
If you need to call value in .js file there is one simple way.
Assign values to input elements in .jsp page.(If you are not using values in .jsp page assign values to hidden input elements)
Then include.js file in your .jsp page
get values as javasript or jquery methods.
Ex:-
value= document.getElementById("element_id").value
OR If you are using jquery you can get as
value = $("#element_id").val();
You can declare a global js variable and assign the value.
<% String myValue = (String)request.getAttribute("Name"); %>
var global1 ='<%= myValue %>';
I have tried different things but i am not able to do this.
I am very new to jquery json and ajax. I wrote a servlet which connects to my databse and retrive user ids from the table. I wrote a jsp and which has a text box that takes input text and refines the results on each key press I want to do it in a html page using jquery ajax by sending json object from my servlet. can someone give me an example for this scenario.
Thanks in advance.
http://jsfiddle.net/tAjNz/
<input type="text" />
<select id="autoPop" multiselect="true"></select>
<script>
// define a data source (ajax or on page load);
myJson = [{value:1,text:'Item One'},{value:1,text:'Item Two'},{value:1,text:'Item Three'},{value:1,text:'Item Four'}];
$('input[type="text"]').keyup(function(){
//Optionally update the data source when a user starts typing or use the predefined source.
//Populate the select list
$sel = $('select');
$sel.html('');
var $this = $(this);
$.each(myJson,function(k,v){
if(v.text.toLowerCase().indexOf($this.val().toLowerCase()) > -1) {
$sel.append('<option value="' + v.value+ '">'+ v.text+'</option>');
}
});
});
</script>
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 1 year ago.
I am trying to create a web application using the MVC design pattern. For the GUI part I would like to use JavaScript. And for the controller Java Servlets.
Now I have never really worked with JavaScript, so I'm having a hard time figuring out how to call a Java Servlet from JavaScript and how to get the response from the Servlet.
Can anybody help me out?
So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('${pageContext.request.contextPath}/myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World! in the JavaScript alert.
You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?
The code here will use AJAX to print text to an HTML5 document dynamically
(Ajax code is similar to book Internet & WWW (Deitel)):
Javascript code:
var asyncRequest;
function start(){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open('GET', '/Test', true); // /Test is url to Servlet!
asyncRequest.send(null);
}
catch(exception)
{
alert("Request failed");
}
}
function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
{
var text = document.getElementById("text"); // text is an id of a
text.innerHTML = asyncRequest.responseText; // div in HTML document
}
}
window.addEventListener("load", start(), false);
Servlet java code:
public class Test extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException{
resp.setContentType("text/plain");
resp.getWriter().println("Servlet wrote this! (Test.java)");
}
}
HTML document
<div id = "text"></div>
EDIT
I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):
document.location = 'path/to/servlet';
Where your servlet-mapping in web.xml looks something like this:
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});