my ajax some how looks like this :
function getXMLHttpRequest() {
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "http://abc.com:8080/someservletServlet/", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
}
function getReadyStateHandler(xmlHttpRequest) {
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("xml").value = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
} but somehow the servlet is not bringing the response it should bring. can you help. what could be the possible error.
Ajax is the way to go.Because if you submit the request, page will refresh whether its same page or different.
If you still want to achieve it using without using ajax and refresh of page is fine with you then see if you have this kind of code in your servlet which is causing to forward it to some other page
String nextJSP = "nextPage.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
If you need to load some data from some other URL you'll need to send an AJAX request (explain where to get data from) and handle the AJAX response (explain what to do with the fetched data). To provide for a browser-compatible solution you'd better use some well-known JS library. For example, you could use jQuery in which case your script could look like:
$.ajax({
url: "servletURL",//servlet URL to post data to
type: "POST",//request type, can be GET
cache: false,//do not cache returned data
data: {id : idOfData},//data to be sent to the server
dataType: "xml"//type of data returned
}).done(function(data) {
//do something with XML data returned from server
});
With this approach you need to call the above JS code, probably wrapped in a JS function, on some JS event, i.e. click, and handle response data, for example, by appending its contents to your text area.
Related
I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.
Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?
You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.
Here's an example (not compatible with IE6/7).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
Use fetch!
It is much more readable and easily customizable. All modern browsers and Node support it. Here is a more in depth tutorial
const url = "https://stackoverflow.com";
fetch(url)
.then(
response => response.text() // .json(), .blob(), etc.
).then(
text => console.log(text) // Handle here
);
You can optionally pass a second param, depending on the needs/type of request.
// Example request options
fetch(url, {
method: 'post', // Default is 'get'
body: JSON.stringify(dataToPost),
mode: 'cors',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(response => response.json())
.then(json => console.log('Response', json))
In Node.js, you'll need to import fetch using:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
const json = await fetch(url)
.then(response => response.json())
.catch((e) => {});
More Info:
Matt Walsh Tutorial
Mozilla Documentation
Can I Use
The simple way to use XMLHttpRequest with pure JavaScript. You can set custom header but it's optional used based on requirement.
1. Using POST Method:
window.onload = function(){
var request = new XMLHttpRequest();
var params = "UID=CORS&name=CORS";
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('POST', 'https://www.example.com/api/createUser', true);
request.setRequestHeader('api-key', 'your-api-key');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
}
You can send params using POST method.
2. Using GET Method:
Please run below example and will get an JSON response.
window.onload = function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
request.send();
}
In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below
Failed to read the \'responseText\' property from \'XMLHttpRequest\':
The value is only accessible if the object\'s \'responseType\' is \'\'
or \'text\' (was \'arraybuffer\')
Best way to access the response from XHR as follows
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(readBody(xhr));
}
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);
I currently have a webpage that uses a javascript that does the following:
function callSomething(parm) {
req = false;
if (window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch (e) {
req = false;
}
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
req = false;
}
}
}
if (req) {
var url_str = "/Servlet?parm=" + parm;
req.open("GET", url_str, false);
req.onreadystatechange = processReqChange;
req.send(null);
// process the response
}
return something;
}
My concern is that if someone enters the full URL manually (e.g. "http://somesampleserver.com/Servlet?parm=something") in an browser window, the response is also displayed. How do I prevent that from happening? I only want the code to be able to get the response.
It sounds like you want to check if this was an XHR request. You can check the X-Requested-With header
Boolean isXHR = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
More on that here
Seems session framework can help. Like Shiro & Spring security.
With those frameworks, only valid session connection can visit resources(URL). Otherwise, it will redirect to login page(customized) automatically.
I am doing a toy program that asks user to input "username" and "fullname" on an html form, the form will be submitted by AJAX to the following method in Spark framework (see here for Spark:
post("/admin/user/signup", "application/json", (request, response) -> {
String username = request.queryParams("username");
String fullname = request.queryParams("fullname");
System.out.println("username is: " + username +", full name is: " + fullname);
Map<String, Object> registerResults = new HashMap<String, Object>();
registerResults.put("success", "successfully registered " + username);
return new MyMessage("successful registration!");
}, new JsonTransformer());
And the following is my AJAX code that supposedly submits and receives the response from the above post() method:
<script>
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>
However, the AJAX code cannot receive the JSON object, instead the JSON object is simply printed on the web page /admin/user/signup:
{"message":"successful registration!"}
So I am asking for help how to return the JSON object to AJAX request in Spark? thanks
You do realize that you are submitting the form. So instead of the supposed AJAX call the form is being submitted and hence the resulting page ...
So you should stop the form submit propagation by simply adding
event.preventDefault();
OR return false; at the end of the submit handler.
in the form submit handler.
<script>
$(document).ready(function() {
$('#registerForm').submit(function(event) {
event.preventDefault();
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>
Instead of return new MyMessage("successful registration!");
Just pass like this return new MyMessage(registerResults);
now,you are not returning this registerResults map value.
I hope you are using play framework.then it should work
And one more thing,you should deny the form from submitting. so, use
$('#registerForm').submit(function(e) {
e.preventDefault();
// do your stuff here
});
You can not treat json as HTML by using html() function, you need to parse it by parseJson() function from jQuery: http://api.jquery.com/jquery.parsejson/
var obj = jQuery.parseJSON(data);
$('.starter-template').html(obj.message);
I'm trying to implement asynchronous login to JEE6 webapp using javascript and XMLHttpRequest. I should be able to make an asynchronous call with XMLHttpRequest to /app/j_security_check and parse the response somehow so that I can show the user a dialog with "Login Failed" or "Login success". I am using Glassfish 3.1.1.
Something I tried, but response is always null. I have a login.jsp that holds the login form and the following script:
function submitLogin(formName) {
var urlAction = "/app/j_security_check";
var client;
var dataString;
if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari
client = new XMLHttpRequest();
} else { // IE6, IE5
client = new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange = function() {
var response = client.responseText; // this is always null
/* ALERT THE DIALOG HERE ACCORDING TO RESPONSE? */
};
var form = document.forms[formName];
var username = form.elements["j_username"].value;
var password = form.elements["j_password"].value;
dataString = "j_username=" + username + "&j_password=" + password;
client.open("POST", urlAction, true);
client.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
client.send(dataString);
}
So my question is, is this possible and how should implement it?
Edit:
The problem here seems to arise from the redirect Java Security is enforcing after succesful/failed login. It seems to always redirect the page, no matter what I do with javascript. I also tried jQuery's ajax methods with no avail.
I do something similar maybe this will help you :
//Get a XMLHttpRequest object.
//The XMLHttpRequest specification defines an API that provides
//scripted client functionality for transferring data between a client and a server.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax obj
/*
* Use this method to send data to server using ajax.
* Sent attribute name is : attribute
* Sent attribute value is : attribute:val
*/
function ajaxFunction(attribute,val, url) {
if(xmlhttp) {
var param = attribute+"="+attribute+":"+val;
param +="&tiers_payant="+document.getElementsByName("tiers_payant")[0].value; //Add the value to send here
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(param);
}
}
/**
* When client received response from server,
* set the inner HTML of the page with the one returned by server.
*/
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
// DO what you want with : xmlhttp.responseText;
}
else {
document.getElementById("erreur").innerHTML="Le serveur le répond pas.";
//alert("Error during AJAX call. Please try again"+xmlhttp.status);
}
}
}
This question is related to the previous one, when I click over an anchor
send email
it calls servlet using json
$("#Email").click(function() {
var option={
"action":"sendEmail"
};
$.getJSON('StudentManagementServlet',option, function(hasEmail) {
if(hasEmail == false){
// //view form to let user enter his email
$("#CommViaEmail").fadeIn("normal");
}
});
});
in servlet I handle the request
if (action != null && action.equals("sendEmail")) {
//open connection to db
con.setAutoCommit(false);
String email = ParentManagement.getParentEmail(con, stdNo);
if (email != null) {
String commResult = createAccountAndSendEmail(con, parentNo, email);
request.setAttribute("result", commResult);
request.setAttribute("incp", "ResultPage");
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response); //doesn't make forward!!!!!
System.out.println(">>send email DONE!!");
con.commit();
return;
} else {
boolean hasEmail = false;
String json = new Gson().toJson(hasEmail);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
The problem here is if user has an email, then I send an email but request dosn't forward to result page, even the print statement is printed " System.out.println(">>send email DONE!!");" ??
You need to let JS/jQuery do that job. Let the servlet write true as JSON result and in JS do
if (hasEmail) {
window.location = 'index.jsp';
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
Or when you want to control the URL yourself, add the new location to the JSON
Map<String, Object> data = new HashMap<String, Object>();
data.put("hasEmail", true);
data.put("location", "index.jsp");
// ...
with
..., function(data) {
if (data.hasEmail) {
window.location = data.location;
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
}
You are making an AJAX request from the client and are trying to 'forward' that request in the server side.
AJAX requests DONT refresh the page. The hasEmail variable in javascript function will be a string containing the HTML of the index.jsp.