Sending XMLHttpRequest via Javascript under iNotes client - javascript

I want to post data using XMLHttpRequest in a form and provide the same functionality under various environments. The following well-known code creates the request for me.
function createRequest() {
var result = null;
if (window.ActiveXObject) {
// MSIE
result = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
// FireFox, Safari, etc.
result = new XMLHttpRequest();
if (typeof xmlhttp.overrideMimeType != 'undefined') {
result.overrideMimeType('text/xml'); // Or anything else
}
}
else {
alert("What a bad browser!")
// No known mechanism -- consider aborting the application
}
return result;
}
This works fine in the system web-browser and in the default web/browser of iNotes client. But when run in a normal form in iNotes client, no suitable object is found to send the request.
My question is whether iNotes client provides some alternative for sending such requests.
A negative answer would also be appreciated since it would help me make decisions!

Related

Is there any way to convert svg url to <svg> tag in javascript? [duplicate]

I'm currently building a site that should be able to function as a ftp sort of browser. Basically what I have is a ftp server with some images on it.
What I can't figure out is: if I browse to this ftp site I can view the source of the ftp site (as seen in some browser), what I need is to save that source in a way to a string (using javascript).
The reason is, that I will make som kind of 'image' browser. I plan on accomplishing that by reading the source into a string, then copy all the image sources and use innerHTML to create a new layout.
In short: I want to read information from a url and display it in a different way.
Well, can't seem to get it working. The problem might be that I cannot use serverside scripting. Would it be possible however to put a file on the ftp server that I can load that can dynamically load the data in the same folder? (when I say FTP I actually mean a NAS server with FTP access).
Your answer is Ajax. It can POST and GET data from an URL, just like browsing a website, and it will return the HTML as a string.
If you plan on using jQuery (real handy), it is easy to use Ajax. Like this example (does not work without the library):
$.ajax({
url : "/mysite/file.html",
success : function(result){
alert(result);
}
});
If you want to use default Javascript, take a look at http://www.w3schools.com/ajax/default.asp
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
IN Javascript to get data without using alert() :
$.ajax({
url : "/mysite/file.html",
async:false, //this is the trick
success : function(result){
//does any action
}
});
Modern Promise-based Fetch API solution (no more XMLHttpRequest or jQuery.ajax()):
fetch('data.txt')
.then(response => response.text())
.then(data => console.log(data));
Example using async/await:
async function myFetch() {
let response = await fetch('data.txt');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
let text = await response.text(); // await ensures variable has fulfilled Promise
console.log(text);
}
There's not much to add to what Niels and rich.okelly have said. AJAX is your way to go.
Keep in mind though, that cross-domain restrictions will prohibit you to access data that is not in the same domain. You'll find a possible workaround here.

why do we use setTimout function if AJAX is asynchronous?

I have been using jquery libraries for implementing AJAX. it was ok and I am comfortable with that. However, I started reading some ajax book and found the following code.
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}// if running Mozilla or other browsers
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
//executed automatically when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else
{
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
Here my question is why do we use setTimeout('process()', 1000); in handleServerResponse() function? Can't we do this without setTimeout('process()', 1000);?
For me, it looks like some kind of constant polling. It's reusing the AJAX request over and over every second, and when the previous request is still active, it waits another second to send it again. So it's not just create an AJAX request and deal with the response.
Using that code, the page would be updating constantly with the information retrieved from the server. Whenever server response has changed, page will as well but not in real time (only when next request finishes). It's similar to Periodic Refresh.
As an evolution, you can have Long Polling in which you spawn an AJAX request and then wait until server responds. If any info is there in the server for you, you'll receive the response immediately. If, while you are waiting for response, anything comes to the server for you, you will receive it. If your request times out, server will respond with an empty body. Then, your client will spawn another AJAX request. You can get some more info from the Wikipedia. Extra link: Comet.
In the given example , the book has call the process() function on the body onload event.
When I change the code to onload-> to onkeyup <input type="text" id="myName" onkeyup="process()"/> I could remove the code //setTimeout('process()', 1000);

How to suppress SSL error when AJAX request to the server with invalid certificate

I have this code:
function newXMLHttpRequest() {
var xmlHttp;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (f) {
xmlHttp = new XMLHttpRequest();
}
}
return xmlHttp;
}
var xmlHttp = newXMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
// this I have xmlHttp.status = 12019
alert("readyState = " + xmlHttp.readyState + "\nstatus = " + xmlHttp.status);
}
xmlHttp.send('same data');
When I send request to the server with invalid certificate I have error with status code 12019.
Solution should be cross-browser (IE, FF, Chrome)
First, to answer the question in the title, this cannot be done. The client xmlHttp libraries do not allow the client to ignore ssl errors. The MsXml2.ServerXMLHTTP object does allow one to ignore SSL errors with the setOption(2, 13056) method. However, this object cannot be used within a browser, nor is it cross-platform.
That said, there seems to be another issue. The 12019 status does not indicate an invalid certification. Some variant of an HTTP 403 status code, or one of the many 'invalid certification' codes would be expected in that case.
Your 12019 status code indicates:
ERROR_INTERNET_INCORRECT_HANDLE_STATE
12019
The requested operation cannot be carried out because the handle supplied is not in the correct state.
Unfortunately this status code doesn't really communicate much, and without knowing what versions of IE, and details about the server there's not much more to go on. I've checked a number of forum posts. One stated switching to IIS fixed the issue, another stated that temporary files that could not be overwritten lead to the problem. Most posts however, do not have a satisfactory, or decisive conclusion.

XMLHttpRequest only works in IE

I am using the XMLHttpRequest object for my AJAX calls which has been working fine across browsers with a callback handler I have created to return JSON based on the request type and arguments etc.
But I am now integrating an external RESTful API to return a JSON string and for some reason it only works for me in IE (tested in IE 8). Using fiddler 2 I have determined that the API is returning the correct data.
I get the XMLHttpRequest.readyState of 4 but XMLHttpRequest.status only returns 0 for Chrome, Safari and FF. I read that sometimes when using a local server (test server) you always get a status of zero so I bypassed my check for status but still got a blank string for XMLHttpRequest.responseText.
function ajaxRequest(requestType,url) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
switch (requestType)
{
case 5:
//Home postcode search
showAddresses("home", xmlhttp.responseText);
break;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
You should upgrade to jQuery as it will handle this request for nearly all browsers. But if you really want to know how to use XMLHttpRequest across all browsers, here's some code that seems to do the trick: https://github.com/ilinsky/xmlhttprequest/blob/master/XMLHttpRequest.js
Or, just pick apart jQuery's implementation.
http://api.jquery.com/category/ajax/
Hope this helps.
My issue was that I was using an external API and xmlHttpRequest only allows you to makes calls on the same server. I moved my data call into my server code and got the response from my callback handling page instead of going straight out to the API.

Having trouble reading Javascript code

I'm new in JS, and having quite hard time reading the following JS code.
The first parameter of the function is a url to a PHP script, the second is a string.
What confuses me is how to read code after the line:
self.xmlHttpReq.open('POST', strURL, true);
What happens after this? Which code should i look after this line? The script?
What happens after open?
function check_detail(strURL, pids)
{
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function()
{
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids);
}
self.xmlHttpReq.send(getquery(pids));
}
The key is the call to "send()", which actually launches the HTTP request. That happens, but the code then proceeds immediately without waiting for the result.
When the server responds, the browser will invoke the anonymous function set up as the "readystatechange" handler. Exactly when that happens is unpredictable; it's asynchronous, in other words.
Thus, the "updatepage()" call will happen long after the "check_detail()" function has returned.
When you make an Ajax request (which is what you are doing here) it is asynchronous, which means that you don't know exactly when it will return so you can't just wait for the return.
Instead, you set up your function so that, when the request returns, a function is kicked off to handle the response. This is the onreadystatechange piece.
So the chronology will be: first the send() will occur, which will send the result of the getquery() method up to the PHP page. When that returns, the function defined within onreadystatechange will fire, which will call updatepage() and pass it both the text that was sent back from the Ajax call, and also the pids parameter.
If you're new to JavaScript, then I'd say it's a waste of time trying to figure out what's going on here - you're learning how to use the XHR object, how to make that cross-browser, and you're learning JavaScript at the same time.
I'd recommend doing the Ajax with a JavaScript library such as jQuery - don't try to learn it all now while you're learning JavaScript as well.
Most of that could be replaced with something along the lines of:
$.post(strURL, function (data) {
updatePage(data);
});
this is simple Ajax function
function check_detail(strURL, pids)
{
// definning new variable
var xmlHttpReq = false;
// creating variable self which will function as this
var self = this;
// creating HTTP request maker for Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// creating HTTP request maker in IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
// so this is the confusing part right ?
// xmlHttpReq.open opens connection tu the strURL and infomation sending method
// will be POST method ( other passible values can be GET method or even else )
self.xmlHttpReq.open('POST', strURL, true);
// this defines HTTP request header (small information about what we are sending)
// in fact this is sending Content-type of information
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// when HTTP request maker state will be changed for example:
// the data will be sent or data will be received this function will be fired
self.xmlHttpReq.onreadystatechange = function()
{
// readyState 4 means data has been received
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids); // updatepage is user defined function
}
// this actually sends the HTTP request which is made above
// but don't be confused because of this code ordering
// I mean the function defining what to do when content will be received is implemented
// before sending HTTP request right ?
// thats because if the data is too small and internet is really fast HTTP query can be
// executed faster then defining new function which will cause javascript error
self.xmlHttpReq.send(getquery(pids));
}
hope this helps
if not
more about ajax: http://en.wikipedia.org/wiki/Ajax_(programming)

Categories