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);
Related
I have angular code
app.controller('add', function ($scope, $http) {
$scope.add = function() {
$scope.msg = "no connect";
var data = {name:'soso',description:'buba',method:'POST'};
$http.post(host + "/add-component",data)
.then(function (response) {
$scope.msg = response.data;
});
}
});
in my servlet, I want to catch it
resp.setContentType("application/json; charset = utf8");
String name = req.getParameter("name");
String description = req.getParameter("description");
but my name and description both = null;
You are sending data as POST request body, not request parameters. This is documented in the angular docs for post method:
url string
Relative or absolute URL specifying the destination of the request
data *
Request content
Take a look at this answer to see how to read request body.
These days it's easier to use Spring Boot or other frameworks to handle your server side endpoints. There is nothing wrong with using Servlets but you will have to write more code yourself.
On the click of a button I am sending a JSON to the Java Server side via an API POST call.On validating the JSON, the server side function return a String.
How do I access that string on my JavaScript client side?
That String will tell me whether the JSON is valid or not.
You can use parseJSON(json) function in jQuery, for example:
function getValue(actionName) {
$j.ajax({
url: actionName + ".do",
data: {
"action" : "getJsonValue"
},
dataType: "json",
success: function(response) {
if (response.errorCode) {
showErrorMessage(response.errorMessage);
return;
}
response = $j.parseJSON(response);
return response;
},
});
}
FrontEnd: jsp with AngularJS
BackEnd: Spring MVC/Java
I am uploading a file using ng-flow, angularJS. Source: https://github.com/flowjs/ng-flow
File upload is successful. I need to return a json from my Spring Controller. Any clues how to go about it?
P.S. can't find where to put in .success() function, if at all that is applicable.
Spring Controller:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
}
app.js code:
(function() {
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'upload',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
app.controller('PageController', function() {
//this.products = gems;
});
app.controller("TabController", function() {
this.tab = 1;
this.showOutput = false;
this.viewEvents = false;
this.isSet = function(checkTab) {
return this.tab === checkTab;
};
this.changeVal = function() {
this.viewEvents = true;
};
this.setTab = function(setTab) {
this.tab = setTab;
};
});
})();
What exactly should be returned from the spring controller? (String/#ResponseBody String etc)
How to collect that json in angular?
On your controller #ResponseBody should be added and the jo returned as String:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
return jo.toString();
}
In AngularJS, you should do this for being able to post files and then retrieve the data back:
$http({url: '/url',
method: 'POST',
data: $scope.myFile,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(data){
$scope.myData = data;
});
In your Spring controller you should just return an Object containing the properties you want to transfer to your angular service. This will be automatically (or by default) be converted to JSON. #RequestBody is not needed.
This return value will be available in the success callback, something like:
$http({
method: 'POST',
url: '...',
}).success(function (data) {
//data is your JSON response
})},
If you are using Spring 3 you can do this
#RequestMapping(value = "/getDealers", value = "/upload", method = RequestMethod.POST)
#ResponseBody
public String uploadFileHandler() {
}
#ResponseBody annotation directly writes the response to the response stream. You would not need a JSP. Just send the request for the controller from the browser & the controller method will write the response to the response stream.
You can parse the response using Jquery or any json library & display in the JSP
Check this out
An alternate way, which I just found out. Will be useful to extract from existing code, without any modification. It does introduce an extra global variable, outside your main angular app, and might not be highly recommended, but still, posting this.
var json = {};
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'processxls',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
this.jsonResponse = arguments[2]; //Note this change
//json = this.jsonResponse;
console.log(this.jsonResponse);
json = angular.fromJson(this.jsonResponse);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
'json' variable now has the json response received. You can use it for further use now.
P.S. in order to check for which value of 'i' arguments[i] gives you the json, see console.
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.
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);
}
}
}