JavaScript XMLHttpRequest.onreadystatechange - javascript

I'm attempting to do some AJAX and need to know why this code isn't firing a completed or error alert. I'm in Mozilla Firefox 20.0.1
PLEASE NOTE
This code IS updating the database (I have a select statement reading the exact record verifying it's updating) I'm just unsure as to why I can't get an alert when the response has completed.
I have these GLOBAL (at the top of the javascript page) declared variables.
var AjaxEnginePage;
var ClientInfoPage;
var XMLHTTP;
AjaxEnginePage = "AjaxEngine.aspx";
ClientInfoPage="getClientInfo.aspx";
Creating the connection.
//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable
function CreateXMLHTTP()
{
try
{
XMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
XMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
XMLHTTP = null;
}
}
//Creating object in Mozilla and Safari
if(!XMLHTTP && typeof XMLHttpRequest != "undefined")
{
XMLHTTP = new XMLHttpRequest();
}
}
Tying the connection:
function btnUpdateMe_OnClick() {
var me = encodeURIComponent(document.getElementById("MeTextBox").value);
// construct the URL
var requestUrl = AjaxEnginePage + "?Action=UpdateMe&Me=" + me;
CreateXMLHTTP();
// If browser supports XMLHTTPRequest object
if(XMLHTTP)
{
//Setting the event handler for the response
XMLHTTP.onreadystatechange = handleStateChange(me);
//Initializes the request object with GET (METHOD of posting),
//Request URL and sets the request as asynchronous.
XMLHTTP.open("get", requestUrl, true);
//Sends the request to server
XMLHTTP.send(null);
}
Handle State Change
function handleStateChange(me) {
switch (XMLHTTP.readyState) {
case 0: // UNINITIALIZED
case 1: // LOADING
case 2: // LOADED
case 3: // INTERACTIVE
break;
case 4: // COMPLETED
alert("Success");
break;
default: alert("error");
}
I can provide more code if needed. :( thanks.

Change:
XMLHTTP.onreadystatechange = handleStateChange(me);
to:
XMLHTTP.onreadystatechange = function() {handleStateChange(me);};
You're setting onreadystatechange to the result of calling the function, not to the function.

Related

Jena Fuseki not working when making an insert query from javascript. No Update parameter error

I have this JavaScript function which aims to insert a keyword in a named graph which belongs to the project Dataset.
function insert(keyword) {
var query = "INSERT DATA {GRAPH <http://test1> {<subj> <pred>'" + keyword + "'. }}";
var endpoint = "http://localhost:3030/project/update";
sparqlQueryJson(query, endpoint, showResults, true);
}
I have executed Jena Fuseki with the --update option. The sparqlQueryJson function is as follows:
function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
var querypart = "query=" + escape(queryStr);
// Get our HTTP request object.
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Code for older versions of IE, like IE6 and before.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Perhaps your browser does not support XMLHttpRequests?');
}
// Set up a POST with JSON result format.
xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
// Set up callback to get the response asynchronously.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// Process the results
callback(xmlhttp.responseText);
} else {
// Some kind of error occurred.
alert("Sparql query error: " + xmlhttp.status + " " + xmlhttp.responseText);
}
}
};
xmlhttp.send(querypart);
};
The showResults function is, in my opinion, not very important here, since it takes the results of the query and show them in HTML.
I followed what is discussed here and here, executing the query using the http://localhost:3030/project/update. The thing is that if I execute the same query on top of the local Fuseki server with the same endpoint url by using the web, it works, but from the JavaScript code, it raises the error:
"SPARQL query error: 400 Error 400: SPARQL Update: No 'update=' parameter".
I'm using Ubuntu 16.04 and Jena Fuseki - version 2.4.1.
To solve this problem the =query parameter has to be changed to =update. In addition, a parameter with the type of the query has to be handled, i.e., update or query.
if(type==="update"){
var querypart = "update=" + escape(queryStr);
}else if(type === "query"){
var querypart = "query=" + escape(queryStr);
}
...
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if(type==="query"){
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
}

return value = undefined when i try to call a Ajax-function inside another Ajax-function

i have a function with a XML-HTTP-Request. Unfortunately i don't get back my DB-result when i call this function getUserdataByToken() <-- working, via a second Function sendPost(wall).
I just want to have the return value (array) inside my second function but the value is always "undefined". Can someone help me?
function getUserdataByToken() {
var token = localStorage.getItem("token");
var userDataRequest;
//-AJAX-REQUEST
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url= window.location.protocol+"//"+window.location.host+"/getuserdatabytoken";
var param = "token=" + token;
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
userDataRequest = JSON.parse(xhttp.responseText);
if (userDataRequest.success === "false") {
warningMessage('homeMessage', false, userDataRequest.message);
} else {
return userDataRequest;
}
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(param);
}
Function call via second Function (AJAX) leads too "undefined" Value for "userDataRequest" (return of function 1).
function sendPost(wall) {
var content;
var token = localStorage.getItem("token");
var userData = getUserdataByToken(); // PROBLEM
console.log(userData); // "leads to undefined"
alert(userData); // "leads to undefined"
… Ajax Call etc…
P.S. it's my first post here in stackoverflow, I'm always grateful for tips.
Thanks!
The userdata value only exists within the anonymous Ajax callback function, and you only return it from there. That is pointless because there is nowhere for it to be returned to; certainly the value does not get returned from getUserdataByToken. Don't forget that Ajax calls are asynchronous; when sendPost calls getUserdataByToken the request won't even have been made.
Generally you'd be much better off using a library like jQuery for this whole thing. Apart from making your code much simpler, it will allow you to use things like Promises which are explicitly intended to solve this kind of problem.
(And, do you really need to support IE5? Are you sure?)

Get Date Header Asyncronously

As the title says, I want to get the Response Header Date value, but I keep getting the following warning :
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
My code :
function getxmlhttp () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
return new XMLHttpRequest();
}else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
return null;
};
function srvTime(){
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.open('GET',"blank.php",false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
console.log("raw " + xmlHttp.getResponseHeader("Date"));
return xmlHttp.getResponseHeader("Date");
};
When I switch this line:
xmlHttp.open('GET',"blank.php",true);
To be true, the value returns NULL.
So can this be done, or do I have to just live with the warning in the console?
Thank you
As your title states, you must make the request asynchronously. That means you have to issue the request and wait for it to complete to get the information. Something like this should work:
function srvTime(callback) {
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { // The operation is complete
console.log("raw " + xmlHttp.getResponseHeader("Date"));
callback(xmlHttp.getResponseHeader("Date"));
xmlHttp = null;
}
};
xmlHttp.open('GET', "blank.php", true);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
};
Note that you must change the signature of your srvTime method. You can't return the data from it, the caller must supply a callback function that receives the date once the request completes.
An example of how you would use this function with the new signature is as follows:
srvTime(function (serverDate) {
document.getElementById("clock").innerHTML = "Game Time: " + serverDate;
});

Ajax request to load .php file not working

Trying to load contents from postcode.php file into a #postcodeList div, but it is not working (nothing happens). I checked postcode.php file it echoes al correct information.
var loadicecream = document.getElementById("iceCreams");
loadicecream.addEventListener("click", iceAjax, false);
function iceAjax() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","ice-cream-list.php",true);
xmlhttp.send();
document.getElementById("ice-cream-list").innerHTML = xmlhttp.responseText;
}
You want the query to execute asynchronously (the third parameter to open function) and then you synchronously try to read the value. This happens before the query has been sent, so it will always be empty.
Either run the load synchronously, or set the xmlhttp.onreadystatechange to point into a function where you handle the loaded state. The best way is to do it asynchronously since you don't want to block the user from using the page while loading data.
Quick example, only handles the success case:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("postcodeList").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","postcode.php",true);
xmlhttp.send();
Read up on the documentation for the onreadystatechange, at least you want to handle the case where there is a timeout or some error, otherwise the user won't know something went wrong.

How to send data from outside site to my server via AJAX?

I am written the bookmarklet, which takes pictures and videos from a site and must send it to my server via AJAX. The problem is in crossdomain AJAX request - I have got an error:
XMLHttpRequest cannot load http://mysite.com/community/bookmarklet/. Origin http://www.some-nice-site.com is not allowed by Access-Control-Allow-Origin.
How to solve data sending to my server from third-part sites?
Note: I use only plane javascript, this is the stipulation of development.
my code:
function getXmlHttp(){
var xmlhttp;
if (typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
};
return xmlhttp;
};
function vote(data) {
var req = getXmlHttp();
req.onready = function() {
if (req.readyState == 4 & req.status == 200) {
alert('OK');
}
}
req.open('GET', 'http://mydomain.com/community/bookmarklet/');
req.send(JSON.stringify(data()));
};
function dataProcessing(){
//some processing
return data;
};
// I tried it, but not deeply understand.
function JSONPresponse(){
document.getElementById('popup_body').innerHTML = 'done!';
};
(function(){
function pasteIt(){
// this function is builds the form, which get data for dispatch to my server.
};
pasteIt();
document.getElementById('my_button').addEventListener('click', function() {vote(dataProcessing)}, false);
}());
It is quite clear... the site you are attempting is prohibiting connection from outside world. You can try by modifying your http headers in request. See:
Access-Control-Allow-Origin Multiple Origin Domains?
Cannot properly set the Accept HTTP header with jQuery
As #jakeclarkson told - JSON-P is the solution, not the only, but useful for me.
XMLHttpRequest is not needed anymore. Instead it vote(data) function creates the script to build URL with params:
function vote(data) {
var script = document.createElement('script'),
data = JSON.stringify(data());
script.type = 'text/javascript';
script.src = 'http://mysite.com/api/bookmarklet/?vids='+encodeURIComponent(data);
document.getElementsByTagName('head')[0].appendChild(script);
};
The script is fulfilled, so URL is called and params already in the server.

Categories