javascript XMLHttpRequest requestXML is null - javascript

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.

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

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

Explanation of downloadUrl() in Javascript?

I have looked far and wide for an explanation so that i am able to understand the above function. The situation which i have encountered it is in Google Maps API documentation:
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
If someone could shed some light it would be appreciated.
function downloadUrl(url, callback) { // pass a URL and a function to call on success
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest; // create an xmlhttprequest, native if possible, activeX for older IE - the construct is a ternary conditional statement
// set up handling of the state change, we only want the 4th
request.onreadystatechange = function() { // when the request changes state
// i.e from sending to having received
if (request.readyState == 4) { // request done
request.onreadystatechange = doNothing; // removed this anonymous function on 4th state (done)
callback(request.responseText, request.status); // call the supplied function with result
}
};
request.open('GET', url, true); // now initialize
request.send(null); // now execute
}
Update: it is these days (July 2018) more likely to find the XMLHttpRequest than the activeX, so any of the following are recommended:
switch the test around,
remove the test for activeX,
add a try/catch or
use Fetch
this code uses AJAX functionality in the browser to fetch the contents of the URL.

Passing variable to PHP file

So I'm not too sure if I'm going to be able to explain this in a way that someone will be able to help me but here it goes:
When I call the function getFishing() I want it to get the "username" Element and put it in a var called get_name, then I want it to send that variable over to the XML_Fishing.php file where is is then used in a mysql query which is then parsed to XML data which is then re-read by the fishingUrl() function. The issue right now is that it's not passing the get_name variable to the XML_Fishing.php file. Can anyone see why from the code below? I didn't give the entire fishingUrl function because it is not relevant to the passing of the variable. It's just the rest of the function, after the data is returned from the XML data.
function getFishing(){
var get_name = escape(document.getElementById("username").innerHTML);
var name = "XML_Fishing.php?username=" + get_name;
fishingUrl(name, "XML_Fishing.php", function(data) {
............
............
............
}
function fishingUrl(name, url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
name is not being passed to the AJAX request - try changing
fishingUrl(name, "XML_Fishing.php", function(data)
to
fishingUrl(name, name , function(data)
that will make first parameter redundant - unless it was being used in the callback function.
This will set $_GET['username'] in the PHP script to the value of get_name from the Javascript

AJAX responseText not getting anything

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

Categories

Resources