AJAX responseText not getting anything - javascript

I wrote this simple AJAX script:
var request;
function createRequest(){
request = null;
try{
request = new XMLHttpRequest();
}catch(failed){
request = null;
}
if(request==null){
alert("Incompatible Browser");
}
}
function getProd(form){
createRequest();
var w = form.list.selectedIndex;
var cat = form.list.options[w].text;
var url = "showProd.do?prodCat=" + cat;
request.open("GET",url,false);
//Send request to server
request.onreadyStateChange = updatePage();
request.send(null);
}
function updatePage(){
//if(request.readyState == 4){
//add your code here
var options = "Bloody Server";
options = request.responseText;
//docWrite(options);
alert(options);
//}
}
I used firebug to check the response i was getting from server. Its absolutely fine and is of type "text/html".
Problem is it doesn't show up in alert box!

By writing request.onreadyStateChange = updatePage(), you are calling the updatePage function and assigning its return value to onreadyStateChange (which, by the way, must be lowercase)
You need to assign the function itself to onreadystatechange without calling it by removing the ().
For example:
request.onreadystatechange = updatePage;
Note that using a global request variable is a horrible idea; your code cannot send two requests at once.
I highly recommend that you use an existing AJAX framework, such as jQuery's, instead.

umm, you are calling your update function on every state change and all but the last will be before there is any data available, resulting in undesirable results.
You need to update your page when readystate==4
createRequest();
....
request.open("GET",url,false);
//Send request to server
request.onreadyStateChange = function(){
if(request.readyState == 4){
//add your code here
var options = "Bloody Server";
options = request.responseText;
//docWrite(options);
alert(options);
}
};
request.send(null);
....

Related

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);
}
};
}

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
}

javascript: wait for a return

I have this problem.
I have a function for example called functionA() that needs the results from another function called functionB().
var globalVar="";
function functionA(){
//...
functionB();
//here i have to use the global variable (that is empty because functionB isn't finished)
}
function functionB(){
//ajax request
globalVar=ajaxRequest.responseText;
}
How can I do to let the functionB finish befor continue with the execution of functionA?
Thanks!
This is the code:
var ingredientiEsistenti="";
function ShowInserisciCommerciale() {
getElementiEsistenti();
JSON.parse(ingredientiEsistenti);
}
function getElementiEsistenti(){
// prendo gli ingredienti esistenti.
var url = "http://127.0.0.1:8080/Tesi/Ingredienti";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", url, false);
xmlHttp.send(null);
xmlHttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) // COMPLETED
{
if (xmlHttp.status == 200) // SUCCESSFUL
{
ingredientiEsistenti = xmlHttp.responseText;
} else {
alert("An error occurred while communicating with login server.");
}
}
};
}
You've got one of many options, that don't require an evil global variable:
Move the code you want to see executed to the onreadystatechange callback of the ajax request, that way, it won't get executed until you received a response
Redefine functionA, so that it takes a parameter that allows you to skip the first bit:
Make the request synchronous, not recommended, though
use a timeout/interval to check the readystate of the request manually (brute-force, not recommended either)
Perhaps there is some worker trickery that could do the trick, too, in your particular case
function functionA(skipDown)
{
skipDown = skipDown || false;
if (skipDown === false)
{
//doStuff
return functionB();//<-- call functionA(true); from the readystatechange callback
}
//this code will only be called if skipDown was passed
}
It is impossible to have a sleep/wait in JavaScript when the call is asynchronous. You need to use a callback pattern to make this action occur.
It is possible to make an XMLHttpRequest synchronous, but that can lead to other problems. It can hang the browser as it blocks all other actions from happening. So if you want to show a loading animation, it most likely will not execute.
You can make your AJAX request synchronous. https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
var request = new XMLHttpRequest();
// Last parameter makes it not asnychronous
request.open('GET', 'http://www.mozilla.org/', false);
request.send(null);
// Won't get here until the network call finishes
if (request.status === 200) {
console.log(request.responseText);
}
However, that will block the UI while waiting for the server to respond, which is almost never what you want. In that case, you should use a callback to process results.
Here's an example using a callback without relying on a global variable. You should always run away from those
function ShowInserisciCommerciale( ) {
getElementiEsistenti(function(responseText) {
JSON.parse(responseText);
});
}
function getElementiEsistenti(successCallback){
var url = "http://127.0.0.1:8080/Tesi/Ingredienti";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", url, false);
xmlHttp.send(null);
xmlHttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) // COMPLETED
{
if (xmlHttp.status == 200) // SUCCESSFUL
{
successCallback(xmlHttp.responseText);
} else {
alert("An error occurred while communicating with login server.");
}
}
};
}

To pass parameters to Result handler function in javascript

I am making XMLHttpRequest to call Google search API URL. And on getting the response I want to call another result Handling function. But I also want to pass the parameter to it.
request = new XMLHttpRequest();
if(request) {
var url = "http://localhost:8080/final_project/SearchService";
url += "?user_query=" + getQueryString();
request.onreadystatechange = handleSearchResult;
request.open("GET", url, true);
request.send(null);
}
Here handleSearchResult is resultHandler and I want to pass parameter to this function. But if I do so the function gets called directly.
What can be done to solve this problem?
Surround it using a closure:
request.onreadystatechange = function() {
handleSearchResult(yourParameter);
}

javascript XMLHttpRequest requestXML is null

I'm trying to grab an xml document from a url and then parse it. I am able to open it fine on a browser, but it doesnt seem to work through my javascript. Can anyone help me?
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = function(){};
callback(request, request.status);
}
};
request.open('GET', "url", true);
request.send(null);
}
downloadUrl("http://jojo.theone.net/survey.xml", function(data) {
alert("Inside downloadURL"); // shows up
var xml = request.responseXML;
alert(xml); // Doesn't even show up.
alert(request.responseText); // Doesnt show up.
});
You are using data as the parameter name in your callback method, but calling the callback method as callback(request, request.status). The result is that the request object is now in the var called "data", and the request.status is not referenced at all.
Try
downloadUrl("http://jojo.theone.net/survey.xml", function(request, status) {
alert("Inside downloadURL");
var xml = request.responseXML;
alert(xml);
alert(request.responseText);
});
Try to use data value not the request object. Also it is better to use some framework like Mootools or jQuery to perform AJAX requests -- you'll get a more compatible and predictable interface.
Also note that request will fail if the url you're requesting has different server, port and protocol than the script that is making request.

Categories

Resources