Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest' - html

I need to display hello world using servlet program in browser by Ajax call but on clicking button I am not to display it what could be reason of this error:
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/workspace/Poc_Ajax/WebContent/WEB-INF/HelloWorld'.
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "HelloWorld", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send();
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
</script>
</head>
<body>
<div>Getting Started with AJAX using JAVA: Hello World!</div>
<div id="hello"><button type="button" onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>

To run a servlet program you need to make an HTTP request to a web server that is configured to execute the servlet.
Your Ajax URL (as displayed in the error message) starts with file:// so you are trying to deal with a local file instead of a webserver.
Install a webserver (such as Tomcat). Load your HTML document from it. Make sure that "HelloWorld" is a relative URI from that HTML document to the servlet URL.

Related

Need Help Reading JSON object from a URL in a HTML

I am trying to create a website in where I can get a particular json object from a url and then display it on the website. The field that I am trying to display is UV_INDEX out of three fields. Nothing is being printed out. I don't even know if it is getting the json object.
<!DOCTYPE html>
<html>
<body>
<h2>EPA </h2>
<p id="demo"></p>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON').then(function(data) {
document.getElementById('UV_INDEX').innerHtml=json.result;
alert('Your Json result is: ' + json.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
</script>
</body>
</html>
I added a third-party chrome extenstion for CORS issue. But I get this error
Uncaught (in promise) ReferenceError: json is not definedmessage: "json is not defined"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
You can try using a Ajax plugin to make CORS request where the CORS headers are not being served from service.
Add Jquery library and add your installed CORS ajax scripts after that:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>
Now you can make cross origin request by just adding crossOrigin: true in your Ajax:
E.g.
$.ajax({
crossOrigin: true,
url: "http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON/",
success: function(data) {
console.log(data);
}
});
You can try putting the same URL in the below demo page to receive the Json data.
See live demo.

Cordova android plugin unable to update JSON object

i have developed a cordova plugin for optical character recognition. I send image to android and the image processing part is done by the plugin and after processing the plugin returns the JSON object back to Cordova. The plugin is working fine for the first time only the data is received correctly but when i tried to process an image for second time the data returned by the plugin is correct but on cordova side the Json object is not updated it shows previous data.
try {
if (ACTION.equals(action))
{
Log.d("action name", action);
Log.d("json object", args.getString(0));
//JSONObject arg_object = args.getJSONObject(0);
this.callbackContext = callbackContext;
if(ACTION_CAMERA.equals(args.getString(0))){
Log.d("action name", "camera");
cordova.getThreadPool().execute(new Runnable() {
public void run() {
camera();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json)); // Thread-safe.
}
});
}
/*
* sending the JSON object containing OCR results and BASE64 encoded string to javaScript
*/
//callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
result = true;
Log.d("after results", "after results");
}
else{
callbackContext.error("Invalid action");
result = false;
}
return result;
}
catch(Exception e)
{
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
and my cordova code is
function onPhotoURISuccess(obj) {
alert(obj['all']);
// clear image div contents
$("#base64Image").empty();
$("#base64Image").attr('src', '');
var image = new Image();
image.src = 'data:image/png;base64,' + obj['imageBase64'];
$("#base64Image").append(image);
$('#base64Image').width();
}
// A button will call this function
function capturePhoto() {
var success = function(message) {
onPhotoURISuccess(message);
}
var failure = function() {
alert("Error calling OCR 1 Plugin");
}
OCRPlugin.greet("camera", success, failure);
}

Telerik Html5 Report Viewer "The requested resource does not support http method 'GET' "

I am getting this while using html5 report viewer in my MVC project
Unable to get report parameters:
Report 'Application.Reports.Report1, WebAppUsingTelerikReport' cannot be resolved.
After clicking the error in console it says The requested resource does not support http method 'GET'
My ReportsController
public class ReportsController : ReportsControllerBase
{
protected override IReportResolver CreateReportResolver()
{
var appPath = HttpContext.Current.Server.MapPath("~/Reports");
//var reportsPath = Path.Combine(appPath, #"..\..\..\Report Designer\Examples");
return new ReportFileResolver(appPath)
.AddFallbackResolver(new ReportTypeResolver());
}
[System.Web.Http.HttpPost]
protected override ICache CreateCache()
{
return Telerik.Reporting.Services.Engine.CacheFactory.CreateFileCache();
}
}
View
#{
Layout = null;
var typeReportSource = new TypeReportSource() { TypeName = "Application.Reports.Report1, WebAppUsingTelerikReport"
};
}
<script type="text/javascript">
$(document).ready(function () {
debugger;
$("#reportViewer1")
.telerik_ReportViewer({
serviceUrl: "/api/reports/",
templateUrl: '../ReportViewer/templates/telerikReportViewerTemplate-8.2.14.1027.html',
reportSource: {
report: "#typeReportSource",
},
viewMode: telerikReportViewer.ViewModes.INTERACTIVE,
scaleMode: telerikReportViewer.ScaleModes.FIT_PAGE_WIDTH,
scale: 1.0,
ready: function () {
}
});
});
</script>
It sounds like a resource is being requested which you have specified not to accept HTTP GET requests. I would expect based on your code that the HTML5 Report Viewer is attempting to call CreateCache() but you have specified it should only accept HTTP POST requests with [System.Web.Http.HttpPost]. If this isn't the issue check if there is another Controller method which is restricted from processing GET requests.
Using a debugger on the server side or in-browser network profiler on the client side it should be easy to identify which requested resource is causing the issue.

Passing two URLS to AJAX and getting response in two divs

I am using AJAX and i have four URLS of HTML. I want to fetch this four urls using AJAX and want to load them in four different divs dynamically. Although i have written code to access one url. Code is here...
function load(url)
{
if (window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch (e) {req = false;}
} else if (window.ActiveXObject) {
// For Internet Explorer on Windows
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
req = false;
}
}
}
if(req) {
req.open('GET', url, false);
req.send(null);
}
}
load('<%=request.getScheme()%>://${domain}/car-rental/html/global/${siteLanguage}/terms/PrefMbrGlobalTermsMiddle-text.html');
function display(id)
{
var element = document.getElementById(id);
if (element && req)
{
// Synchronous request, wait till we have it all
element.innerHTML = req.responseText;
}
}
I want to do same type of logic to load four urls .. Please help me out...
What I understood from your code is load function you are using to make an ajax call. So what can do call load function as:
load("url1","target-div1");
load("url2","target-div2");
load("url3","target-div3");
load("url4","target-div4");
inside load on successful of AJAX set the content target-div with AJAX response.

Geolocation in Flash

I'm building a small web app in Flash. Is there a solution to get the geo-location of a user?
The easiest way is to interface with a JavaScript function.
In your HTML:
<script>
function getGEO()
{
// First check if your browser supports the geolocation API
if (navigator.geolocation)
{
//alert("HTML 5 is getting your location");
// Get the current position
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude
long = position.coords.longitude;
// Pass the coordinates to Flash
passGEOToSWF(lat, long);
});
} else {
//alert("Sorry... your browser does not support the HTML5 GeoLocation API");
}
}
function passGEOToSWF(lat,long)
{
//alert("HTML 5 is sending your location to Flash");
// Pass the coordinates to mySWF using ExternalInterface
document.getElementById("index").passGEOToSWF(lat,long);
}
</script>
Then, in your Application, once your map is ready, put this in a function:
//for getting a user's location
if (ExternalInterface.available)
{
//check if external interface is available
try
{
// add Callback for the passGEOToSWF Javascript function
ExternalInterface.addCallback("passGEOToSWF", onPassGEOToSWF);
}
catch (error:SecurityError)
{
// Alert the user of a SecurityError
}
catch (error:Error)
{
// Alert the user of an Error
}
}
Finally, have a private function ready to catch the callback.
private function onPassGEOToSWF(lat:*,long:*):void
{
userLoc = new LatLng(lat,long);
map.setCenter(userLoc);
}