Couldn't make ASPJAX working - html

I want to make a demo on how to combine ASP and AJAX. I have found snippets from http://www.aspjax.com and implemented it in my project. However, the text that should be displayed cannot be output properly.
Here's the code. Basically the same as the one in the original:
In index.asp
<script language="javascript" type="text/javascript">
/** XHConn - Simple XMLHTTP Interface - bfults#gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
// doAJAXCall : Generic AJAX Handler, used with XHConn
// Author : Bryce Christensen (www.esonica.com)
// PageURL : the server side page we are calling
// ReqType : either POST or GET, typically POST
// PostStr : parameter passed in a query string format 'param1=foo&param2=bar'
// FunctionName : the JS function that will handle the response
var doAJAXCall = function (PageURL, ReqType, PostStr, FunctionName) {
// create the new object for doing the XMLHTTP Request
var myConn = new XHConn();
// check if the browser supports it
if (myConn) {
// XMLHTTPRequest is supported by the browser, continue with the request
myConn.connect('' + PageURL + '', '' + ReqType + '', '' + PostStr + '', FunctionName);
}
else {
// Not support by this browser, alert the user
alert("XMLHTTP not available. Try a newer/better browser, this application will not work!");
}
}
// launched from button click
var getMessage = function () {
// build up the post string when passing variables to the server side page
var PostStr = "";
// use the generic function to make the request
doAJAXCall('ajaxtest.asp', 'POST', '', showMessageResponse);
}
// The function for handling the response from the server
var showMessageResponse = function (oXML) {
// get the response text, into a variable
var response = oXML.responseText;
// update the Div to show the result from the server
document.getElementById("responseDiv").innerHTML = response;
};
</script>
<body>
<button onclick="javascript:getMessage();">Get Message From Server</button>
<div id="responseDiv">Original Text</div>
</body>
So, the code tells it to replace the Original Text in the div with the one in ajaxtest.asp
In ajaxtest.asp
<%# Language=VBScript %>
Response.Write "The Server time is " & Now()
The problem is when I click the button Get Message From Server, the stuff in ajaxtest.asp is rendered as plain text, but not in ASP. How to fix this? Is it because of the extension used is wrong?
EDIT: by plain text I mean exactly as Response.Write "The Server time is " & Now()

You probably want the contents of your ASP page to be:
<%# Language=VBScript %>
The Server time is <%=Now()%>

Related

XMLHttpRequest ERROR in QML Blackberry 10

I'm trying to get movie data for BlackBerry 10 apps.
I don't know where I'm making a mistake.
Please, can you help me?
Thank you all.
import bb.cascades 1.4
Page {
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send(data);
}
}
You need to use the onreadystatechange EventHandler.
Also, you don't need to pass data when making a GET request.
I have removed the withCredentials line as it isn't needed in this example.
You can learn more on XMLHttpRequest here :
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
var json = JSON.parse(xhr.responseText);
var results = json.results;
var count = results.length;
console.log("There are " + count + " results :");
json.results.forEach((value, index) =>
{
console.log(index + " - " + value.title);
});
}
};
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send();
}
Here's an example of using XMLHttpRequest I've made a long time ago :
https://github.com/RodgerLeblanc/Markup/blob/master/assets/main.qml

html <script> tag headers

I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.

Parallel form submit and ajax call

I have a web page that invokes long request on the server. The request generates an excel file and stream it back to the client when it is ready.
The request is invoked by creating form element using jQuery and invoking the submit method.
I would like during the request is being processed to display the user with progress of the task.
I thought to do it using jQuery ajax call to service I have on the server that returns status messages.
My problem is that when I am calling this service (using $.ajax) The callback is being called only when the request intiated by the form submit ended.
Any suggestions ?
The code:
<script>
function dummyFunction(){
var notificationContextId = "someid";
var url = $fdbUI.config.baseUrl() + "/Promis/GenerateExcel.aspx";
var $form = $('<form action="' + url + '" method="POST" target="_blank"></form>');
var $hidden = $("<input type='hidden' name='viewModel'/>");
$hidden.val(self.toJSON());
$hidden.appendTo($form);
var $contextId = new $("<input type='hidden' name='notifyContextId'/>").val(notificationContextId);
$contextId.appendTo($form);
$('body').append($form);
self.progressMessages([]);
$fdbUI.notificationHelper.getNotifications(notificationContextId, function (message) {
var messageText = '';
if (message.IsEnded) {
messageText = "Excel is ready to download";
} else if (message.IsError) {
messageText = "An error occured while preparing excel file. Please try again...";
} else {
messageText = message.NotifyData;
}
self.progressMessages.push(messageText);
});
$form.submit();
}
<script>
The code is using utility library that invokes the $.ajax. Its code is:
(function () {
if (!window.flowdbUI) {
throw ("missing reference to flowdb.ui.core.");
}
function NotificationHelper() {
var self = this;
this.intervalId = null;
this.getNotifications = function (contextId, fnCallback) {
if ($.isFunction(fnCallback) == false)
return;
self.intervalId = setInterval(function() {
self._startNotificationPolling(contextId, fnCallback);
}, 500);
};
this._startNotificationPolling = function (contextId, fnCallback) {
if (self._processing)
return;
self._processing = true;
self._notificationPolling(contextId, function (result) {
if (result.success) {
var message = result.retVal;
if (message == null)
return;
if (message.IsEnded || message.IsError) {
clearInterval(self.intervalId);
}
fnCallback(message);
} else {
clearInterval(self.intervalId);
fnCallback({NotifyData:null, IsEnded:false, IsError:true});
}
self._processing = false;
});
};
this._notificationPolling = function (contextId, fnCallback) {
$fdbUI.core.executeAjax("NotificationProvider", { id: contextId }, function(result) {
fnCallback(result);
});
};
return this;
}
window.flowdbUI.notificationHelper = new NotificationHelper();
})();
By default, ASP.NET will only allow a single concurrent request per session, to avoid race conditions. So the server is not responding to your status requests until after the long-polling request is complete.
One possible approach would be to make your form post return immediately, and when the status request shows completion, start up a new request to get the data that it knows is waiting for it on the server.
Or you could try changing the EnableSessionState settings to allow multiple concurrent requests, as described here.

How can I hide the parameters of this URL?

I have a ajax call in my javascript and its returning some response as json and redirecting the json values to another jsp page.. in the redirected jsp page, am getting the whole json in the url tab.. how to avoid that...
here is my ajax call in js file...
var cols="PRIORITY,USER_ID,PARTICIPANT_TYPE,CREATION_DATE,ASSIGN_TO_USER_DATE,START_WORK_DATE,DUE_DATE,OPERATION,ORDER_VK,SENDER_TYPE,SENDER_ID,ORDER_ID,FLAGS";
var ioArgs = {
url: "./DynamicDBServlet",
content: { TABLE_NAME:'CWPWORKLIST',WHERE_CONDN:cond,COLUMNS:cols},
handleAs: "json",
load: function(response) {
alert("new "+new String(response));
window.location.href = "worklist.jsp?PRIORITY="+response;
},
error: function(error) {
alert("An unexpected error occurred: " + error);
}
};
Replace this line:
window.location.href = "worklist.jsp?PRIORITY="+response;
with:
openWindowWithPost("worklist.jsp",'height=300px,width=300px,top=200px,left=500px,scrollbars=no,sizable=yes,toolbar=no,statusbar=no','title',param);
and then have the below function:
function openWindowWithPost(url, windowoption, name, params)
{
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", url);
form.setAttribute("target", name);
var input = document.createElement('input');
input.type = 'hidden';
input.name = "PARAM";
input.value = params;
form.appendChild(input);
/*for (var i in params) {
if (params.hasOwnProperty(i)) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = i;
input.value = params[i];
form.appendChild(input);
}
}*/
document.body.appendChild(form);
window.open(url, name, windowoption);
//alert("inside openpost");
form.submit();
document.body.removeChild(form);
}
and read the values to worklist.jsp using the name PARAM......
You are now using GET to send your PRIORITY variable. Use POST!
You will have to create a form consisting of a single hidden input, put response in the value attribute of said input and submit the form having it's action point to your worklist.jsp.

In html5 server sent event, why do I see polling log on fiddler

I am not able to figure out that why do I see polling log in fiddler for the server sent event I am trying to implement using HTML 5. Please find the image of my fiddler log below
If its server sent event, the message should be sent from server without system calling the method again and again to look for updates. Or i have not implemented it properly. Here my code:
<script type="text/javascript">
$(function () {
var userStatusChangeEvent = new EventSource("/events");
userStatusChangeEvent.onmessage = function (event) {
data = $.parseJSON(event.data);
for (index = 0; index < data.length; index++) {
$elem = $('#' + data[index].Id);
isOnline = data[index].IsOnline;
if (isOnline) {
$elem.addClass('is_online');
$('.loginTimestamp', $elem).html(data[index].Time);
}
else {
$elem.removeClass('is_online');
$('.loginTimestamp', $elem).html('');
}
}
};
});
</script>
public virtual ActionResult Events()
{
var userStream = new UserServerSentStatusResult();
userStream.ChangeUserStatus = new LoggedUsersViewModel().Users.Where(x => x.HasChanged).ToList();
userStream.Content = () =>
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(userStream.ChangeUserStatus);
};
userStream.ChangeUserStatus.ForEach(x =>
{
x.HasChanged = false;
x.Time = DateTime.Now.ToShortTimeString();
});
return userStream;
}
Turn on the Streaming mode in Fiddler