Ajax request not passed to controller - javascript

I send an AJAX request to my controller. This development done in JSP and Spring environment. SimpleFormController is overridden by the controller I'm using.
Using JavaScript I create the object and send the request. this request is not getting passed to controller.
JavaScript code which send the request.
function getStates(){
var httpRequest;
var country = document.getElementById('countryName');
alert(country);
var url = '/developer/register.htm';
url = url + (url.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true');
if (window.ActiveXObject)
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
httpRequest = new XMLHttpRequest();
}
httpRequest.open("GET", url, true);
httpRequest.onreadystatechange = function() {processRequest(); };
httpRequest.send(null);
}
function processRequest() {
if(httpRequest.readyState == 4){
alert("inside ready state");
var response = http.responseText;
document.getElementById('states').innerHTML = response;
}
}
Variable url is given in the way how I have mentioned in dispatcher servlet.
The browser shows an error in processRequest() function telling that httpRequest is not defined. but, I don't get this error in the previous lines. I use this object in getStates() function.

It is because variable httpRequest should be defined outside getStates() function. Otherwise processRequest() cannot see it.

Either declare httpRequest outside getStates() (as a global variable) or pass it to processRequest():
httpRequest.onreadystatechange = function() { processRequest(httpRequest); };
function processRequest(httpRequest) {

Related

Why the "Uncaught ReferenceError:" when making my HTTP request?

"use strict";
(function() {
var url = "http://api.openweathermap.org/data/2.5/weather?q=London,England";
var apiKey = "OMMITTED FOR PRIVACY REASONS"; // Replace "APIKEY" with your own API key; otherwise, your HTTP request will not work
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url + '&appid=' + apiKey);
httpRequest.send();
}
// handle XHR response
function responseMethod() {
if (httpRequest.readyState === 4) {
console.log(httpRequest.responseText);
}
}
})();
See link below for a screenshot of the errors, but here's what I'm getting:
An Uncaught ReferenceError on line 12 where my onreadystatechange is.
I also get an error saying 'responseMethod' isn't defined at
makeRequest nor when I call it.
Also getting an error on the very last line for some reason.
Your code looks good. I just replaced your code with my api key and everything worked (see below).
Can you be more specific about the browser where you get an error?
I tried in the latest chrome and firefox and there is no problem.
"use strict";
(function() {
var url = "http://api.openweathermap.org/data/2.5/weather?q=London,England";
var apiKey = "4ff5002c91520701ec111b6082de9387"; // This key might expire soon.
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url + '&appid=' + apiKey);
httpRequest.send();
}
// handle XHR response
function responseMethod() {
if (httpRequest.readyState === 4) {
console.log(httpRequest.responseText);
}
}
})();

Call MVC Controller Method from TypeScript/JavaScript without jquery

Is it possible to call MVC Controller Method with Ajax call in Type Script/JavaScript without Jquery? if not How I can Call Controller Method from JavaScript/Type Script file?
Consider a method that is calling Controller method to sort and send a sort column to it:
This is function in ts file:
function SortData()
{
.... call Controller method and send sortCriteria (FullName) to it
}
and this is Controller method:
[Route("sortbycolumn")]
public ActionResult SortByColumn(string sortCriteria)
{
.... Do the sort retun back json result
}
Of course you can. In fact, jQuery is library based on javascript and it is not an independent language. Here is what you have to do:
function SortData(){
// Every ajax call is an XMLHttpRequest
var xhttp = new XMLHttpRequest();
// It means that your request is processed asynchronously.
// So we need to define the method that has to be run once the response is received,
xhttp.onreadystatechange = function() {
// status 200 means that your request has been processed successfully.
if (this.readyState == 4 && this.status == 200) {
// Change your html here
}
};
// Setting your request
xhttp.open("POST", "mycontroller/myaction", true);
// Send your request when everything is set.
xhttp.send();
}
If you need more to know, check out this link: https://www.w3schools.com/xml/ajax_intro.asp
I've included an example of a GET and a POST + submitting/receiving data using vanilla JS & AJAX below.
For further info, give this a read.
Good luck.
function SortData() {
var data;
//Post Example
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/Controller/Action", true);
xhttp.setRequestHeader("Content-Type", "application/json");
//There are two options for using xhttp.send(): Only keep the ONE that applies to you
//Option 1: Submit data to the server
xhttp.send(JSON.stringify(params));
//OR
//Option 2: Nothing to submit to the server
xhttp.send();
xhttp.onload = function(response) {
if(response.target.status == 200) {
data = JSON.parse(response.target.response);
}
};
//Get Example
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/Controller/Action", true);
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
//There are two options for using xhttp.send(): Only keep the ONE that applies to you
//Option 1: Submit data to the server
xhttp.send(JSON.stringify(params));
//OR
//Option 2: Nothing to submit to the server
xhttp.send();
xhttp.onload = function(response) {
if(response.target.status == 200) {
data = JSON.parse(response.target.response);
}
};
}

How do I manage multiple, overlapping XMLHttpRequests?

I'm working on my first AJAX project, and I've started by setting up the following functions:
function sendHTTPRequest(callback,filename,data) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = callback;
httpRequest.open('POST',rootAddress+filename, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(data);
}
function exampleCallback() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// successful, parse the XML data
} else {
// error
}
} else {
// not ready
}
}
This has worked well but I've now gotten to the point where I have more than one simultaneous HTTP request, and my single global httpRequest variable isn't cutting it. It seems to me I could use an array, and .push a new XMLHttpRequest onto the stack each time sendHTTPRequest() is called, but how can I tell my various callback functions which item in the stack to parse? Or is the a better way to handle this process? (I'm using these to handle requests to different pages, with results that need to be parsed differently.)
Thanks!
Use a local variable and a per-request callback, which in turn calls the given callback. The changes required are surprisingly small; see ** lines:
function sendHTTPRequest(callback,filename,data) {
var httpRequest; // ** Local variable
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// ** Callback specific to *this* request
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// successful, call the callback
callback(httpRequest);
} else {
// error, call the callback -- here we use null to indicate the error
callback(null);
}
} else {
// not ready
}
};
httpRequest.open('POST',rootAddress+filename, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(data);
}
function exampleCallback(xhr) {
if (xhr) {
// successful, parse the XML data, for instance
var x = xhr.responseXML;
} else {
// not ready
}
}
You could have it give the callback more information (for instance, the filename and data arguments).
If you use promises, you could have sendHTTPRequest return a promise instead of accepting a direct callback.
httpRequest = new XMLHttpRequest();
Don't use a global. Use a local variable.
if (httpRequest.readyState === XMLHttpRequest.DONE) {
Don't use a global. Event handlers are called in the context of the object on which they fire. Use this.

Multiple http requests by same js file

i have a problem with my file js that call multiple http requests.
I have a button that call the function VisualizzaReport that is in my file visualizzaReport.js
Here is the function VisualizzaReport(select is the ID of the user)
function visualizzaReport(select){
reportUtente(select)
loadPianificazione(select)
}
Here the function reportUtente(select)
function reportUtente(select) {
var url = "../loadReportUtenteServlet?";
url += "type=perso_atti&value=" + select.value;
xmlhttp.onreadystatechange = handlerForReportUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
Here the function loadPianificazione(select)
function loadPianificazione(select) {
var url = "../loadPianificazione2Servlet?";
url += "type=pianificazioni&value=" + select.value;
xmlhttp.onreadystatechange = handlerForPianificazioneUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
my problem is that the function reportUtente is launched but has not effect because it seems that it is substitute by loadPianificazione function.
How can i call loadPianificazione only when reportUtente has finished his execution?
In your case I suggest you use either jQuery or AngularJs for this purposes.
jQuery example:
$.get('url1.com', function(){
$.get('url2.com');
})
You will request url2.com only when first request has finished.
You appear to be using a single, global xmlhttp variable.
Then you call two functions which do things with it. The second one will overwrite xmlhttp.onreadystatechange before the first request has finished so the second function you put there will be called for each request.
Don't do that. Create a new instance of XMLHttpRequest for each request, and keep it in a local scope so that it doesn't interfere with other instances.
function reportUtente(select) {
var url = "../loadReportUtenteServlet?";
url += "type=perso_atti&value=" + select.value;
var xmlhttp = new XMLHttpRequest(); // New instance here
xmlhttp.onreadystatechange = handlerForReportUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
You haven't shared handlerForReportUtente but it should look something like:
function handlerForReportUtente() {
alert(this.responseText); // Use `this` to get the right XHR object
}

XMLHttpRequest object not being instantiated?

I'm new to Ajax and this has me stumped. It's relatively simple but trips up on the onclick handler with the first xhr.open(). Firebug says it's not a function, my guess is the XMLHttpRequest object isn't being created, but I'm not sure. Anyone have any ideas?
Thanks in advance.
function init(){
function getXMLHTTP(){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function updatePage(theData){
$('results').innerHTML = theData; //TODO: pretty this up with mootools
}
var xhr = getXMLHTTP();
if (xhr) {
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var theData = xhr.responseText;
updatePage(theData);
}
else{
alert("Error communicating to web service!");
}
}
}
$('submit_btn').onclick = function(xhr){
if ($('state').value != "") {
var theValue = $('state').value;
xhr.open("GET", "/inc/calc.php?state="+theValue, true); //Ajax 101: 3rd argument marks object as asynchronous
xhr.send(NULL);
}
else if ($('city').value != "") {
xhr.open("GET", "/inc/calc.php?city="+$('city').value, true);
xhr.send(NULL);
}
else if ($('county').value != "") {
xhr.open("GET", "/inc/calc.php?county="+$('county').value, true);
xhr.send(NULL);
}
else {
//the form is empty, or just down payment is filled. returns whole freakin' table.
xhr.open("GET", "/inc/calc.php", true);
xhr.send(NULL);
}
}
}
}
The problem with your code is the onclick function. You have put the xhr in the argument list to the function. Remember that when a function is called, the value of this variable is set by the caller. In this case it would be the event dispatcher, and it would probably set the xhr variable to an event object, which does not have an open function.
If you remove the xhr variable from the argument list of the onclick function, then it will look for the xhr variable in the parent scope, the global scope, and it will find it there, and it should work. I haven't tested it though.
I'm assuming you are using some kind of framework as well (judging by the frequent use of $, and the reference to mootools). This framework probably has an ajax function built in, as well as a cross browser event model. Try using it instead, you will run into a lot less problems.
When assigning the onclick handler you create a new function that takes a parameter called xhr:
$('submit_btn').onclick = function(xhr){
...
xhr.open("GET", "/inc/calc.php?state="+theValue, true);
...
}
The click on the button won't pass a XMLHttpRequest object the the handler, so xhr will not have an open() method. The global definition of xhr doesn't matter because it's shadowed by the local parameter definition.
Generally you should just generate a new local XMLHttpRequest object when you need it, not try to use a global one. For example use an onclick function that creates a new local XMLHttpRequest:
$('submit_btn').onclick = function(){
var xhr = getXMLHTTP();
xhr.open("GET", "/inc/calc.php?state="+theValue, true);
...
}

Categories

Resources