call generic handler in aspx without jquery - javascript

Can i call Generic handler in aspx without using jQuery?

yes, jQuery itself is a javascript, so you can call by writing your own script. The benefit of using jQuery is you don't need to worry about browser compatability, have to write less code, can get advantage of using jquery plugins etc, only the cost of adding jQuery.js.
Example:
<script type="text/javascript">
// Intialize XMLHTTP object
function GetXmlHttpObject() {
var A;
if (window.XMLHttpRequest) {
A = new XMLHttpRequest();
} else {
var msxmlhttp = new Array(
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < msxmlhttp.length; i++) {
try {
A = new ActiveXObject(msxmlhttp[i]);
break;
} catch (e) {
A = null;
}
}
}
return A;
}
function sendAjaxRequest(url, postVars, callbackFunc) {
var isPost = (postVars && postVars.length > 0);
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
if (!isPost) {
if (url.indexOf('?') == -1) {
url += '?' + uncache();
} else {
url += '&' + uncache();
}
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { //This function will execute on receive
var callback;
var extra_data = false;
var data = xmlHttp.responseText;
callback = callbackFunc;
callbackFunc(data, extra_data);
}
};
//Send data to the url through ajax
if (isPost) {
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-Length", postVars.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postVars);
} else {
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
function uncache() {
var d = new Date();
var time = d.getTime();
return 'time=' + time;
}
function comp(result) {
alert(result);
}
sendAjaxRequest('test.html', '', comp);
</script>

Related

How can i display as ajax-response in a reloaded page

I have the following situation in an AJAX-Request:
function getFileContens(OBJ) {
var file = OBJ.id;
PARAMS = "Action=getFileContens";
PARAMS = PARAMS + "&File=" + OBJ.id;
var probenZahl = file.split("__")[4];
document.getElementById("inpProbenAnzahl").value = probenZahl;
//setSessionValue(document.getElementById("inpProbenAnzahl"));
try {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Ihr Webbrowser unterstuetzt leider kein Ajax!");
}
//alert(PARAMS);
req.open("POST", "./php/ajax/Eingabe.php", true);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onreadystatechange = function() {
cbGetFileContens();
};
req.send(PARAMS);
} catch (e) {
alert("Fehler: " + e);
}
}
function cbGetFileContens() {
if (4 == req.readyState) {
if (200 != req.status) {
alert("Fehler " + req.status + ": " + req.statusText);
} else {
//alert(req.responseText);
var ar_resp = req.responseText.split(";;;");
for (let i = 0; i < ar_resp.length; i++) {
ar_inp = ar_resp[i].split("##");
if (ar_inp[0].trim().length > 2) {
if (document.getElementById(ar_inp[0].trim())) {
document.getElementById(ar_inp[0].trim()).value = ar_inp[1];
}
}
}
location.reload();
//console.log("Hallo");
console.log(req.responseText);
}
}
}
This code shoud display the splitted response-text in a textfield with certain IDs in a HTML-File...
I want to use the Ajax-response-text after reloading the page..
Everything works fine whe i do not reload the page..
Using reloading the text is not displayed..
You can store the response into a session storage.
sessionStorage.setItem('ajax_response', req.responseText)
location.reload();
After, when the page is loaded, you can put the item into your element.
var el = document.getElementById('elemId')
el.innerText = sessionStorage.getItem('ajax_response')

set time out in ajax call while using core javascript

I have a JavaScript function to call ajax. Now I need to add time out in this function like while calling service took more than defile time ajax call should time out and display a default message. I don't want to use Jquery in it.
here is my code:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here's an example of how you can handle a timeout:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(xmlHttpTimeout);
alert(xmlHttp.responseText);
}
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
xmlHttp.abort();
alert("Request timed out");
}
In IE8, You can add a timeout event handler to the XMLHttpRequest object.
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
Use a javascript framework to do this though, i don't know why you're not using one, do you like uneccesary work? :)
If you want to simply add timeout, You can add it in the first function in three places:
setTimeout(function() {callback(this.responseText, params)}, 1000)
And your callback will execute around 1s later. The second palce is second call of callback.
Third place that i would suggest is to wrap this function like above:
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
Usually when i get in to testing internet connection i rather add throttling in the chrome developer tools like this:
Here is your code with first approach:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
console.log(new Date());
setTimeout(function() {callback(this.responseText, params)}, 2000);
} else {
console.error((new Date()).getSeconds());
setTimeout(function() {callback(this.responseText)}, 2000);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
AJAX('http://ip.jsontest.com/', function() {console.error((new Date()).getSeconds()); });
Maybe the answer to this question will help.
Timeout XMLHttpRequest
since from what i understand you need to set timeout for xmlhttprequest,
you can use xmlhttp.timeout = /*some number*/

How to know how many asynchronous calls are pending

I'm using the following code to make multiple async. calls and I need to know how many of those calls are pending for validating purposes.
function llenarComboMetodos(cell) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Las llamandas asincronas no son soportadas por este navegador.");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
var combo = '<select name="metodos[]">';
var opciones=xhr.responseText;
combo+= opciones+"</select>";
cell.innerHTML = combo;
}
}
}
xhr.open('POST', 'includes/get_metodos.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("completar=1");
}
Is there a way to know that?
Thank you (:
You can intercept the XMLHttpRequest.send and do your counting of active calls:
var activeXhr = (function(){
var count = 0;
XMLHttpRequest.prototype.nativeSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
this.onreadystatechange = function(){
switch(this.readyState){
case 2: count++; break
case 4: count--; break
}
};
this.nativeSend(body);
};
return count;
})();
console.log(activeXhr);

jquery doesn't get loaded, if i don't reload page

This code works only if I reload/refresh page, otherwise it doesn't work, I susspect issue is, because I use Jquery + normal javascript.
I have form and there is input which uses autocomplete, but while you go trough form next, it doesn't work.
The point is that input with #SchoolName isn't on first page is on 2nd page (after showcart(); function is trigered)...
Anyone have any ideas why my jquery code doesn't load properly?
I have this code:
<script type="text/javascript" language="javascript">
function autocomplete() {
$("#SchoolName").autocomplete("ajaxFuncs.php", {
cacheLength:1,
mustMatch:1,
extraParams: {getSchoolName:1}
});
};
$(document).ready(function(){
setTimeout("autocomplete()", 500);
});
function showVal(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "* Please type in School Name.";
return;
}
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) {
if (xmlhttp.status == 200) { // break this into 2 statements so you can handle HTTP errors
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
} else {
document.getElementById("txtHint").innerHTML = "AJAX Error (HTTP "+xmlhttp.status+")";
}
}
}; // functions declared in this way should be followed by a semi colon, since the function declaration is actually a statement.
// encodeURIComponent() does all the escaping work for you - it is roughly analogous to PHP's urlencode()
// xmlhttp.open("GET","ajaxFuncs2.php?q="+encodeURIComponent(str),true);
xmlhttp.open("GET","ajaxFuncs2.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
<script>
function ajax(doc)
{
doc = null;
if (window.XMLHttpRequest) {
try {
doc = new XMLHttpRequest();
}
catch(e) {
if(SBDebug)
alert("Ajax interface creation failure 1");
}
}
else if (window.ActiveXObject) {
try {
doc = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
doc = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
if(SBDebug)
alert("Ajax interface creation failure 2");
}
}
}
return doc;
}
function postIt(params) {
var doc;
// alert("postIt: " + params);
if(params == "")
params = "nada=0";
doc = ajax(doc);
if (doc) {
var url = window.location.href;
url = url.substr(0, url.lastIndexOf("/") + 1) + "clientCartPost.php";
// alert(url);
doc.open("POST", url, false);
//Send the proper header information along with the request
doc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
doc.setRequestHeader("Content-length", params.length);
doc.setRequestHeader("Connection", "close");
document.body.style.cursor = "wait";
doc.send(params);
document.body.style.cursor = "default";
if(doc.responseText == "timeout") {
alert("Timed out");
document.location = "index.php";
}
return doc.responseText;
}
return "Connection Failed";
}
function saveCC() {
var doc;
doc = ajax(doc);
if(params == "")
params = "nada=0";
if (doc) {
var params = "";
var eVisi = document.getElementById("visiCard");
var eCard = document.getElementById("x_card_num");
if(eVisi.value.indexOf("*") < 0)
eCard.value = eVisi.value;
for(i=0; i<document.CC.elements.length; i++) {
if(document.CC.elements[i].name == "visiCard")
continue;
params += getElemValue(document.CC.elements[i]) + "&";
}
doc.open("POST", "https://dot.precisehire.com/clientCartStoreCard.php", false);
//Send the proper header information along with the request
doc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
doc.setRequestHeader("Content-length", params.length);
doc.setRequestHeader("Connection", "close");
document.body.style.cursor = "wait";
doc.send(params);
document.body.style.cursor = "default";
// alert(doc.responseText);
return true;
}
return false;
}
function getElemValue(item)
{
// alert("Getting: " + itemBase + itemID);
// alert(itemBase + "" + itemID);
if(item.type == "radio" || item.type == "checkbox")
{
if(!item.checked)
return "";
}
if(item.type == "select-one")
{
value = item.options[item.selectedIndex].value;
}
else
value = item.value;
return item.name + "=" + escape(value) + "&";
}
function makePie()
{
var contents = postIt("command=getProgress");
document.getElementById("step2").className = "bx2";
document.getElementById("step3").className = "bx2";
document.getElementById("step4").className = "bx2";
if(contents > 0)
document.getElementById("step2").className = "bx1";
if(contents > 1)
document.getElementById("step3").className = "bx1";
if(contents > 2)
document.getElementById("step4").className = "bx1";
}
var gbColor;
function RedIn(start)
{
var id;
if(start)
gbColor = 0;
gbColor += 32;
if(gbColor > 255)
gbColor = 255;
id = 0;
var obj = document.getElementById("red" + id);
while(obj != undefined)
{
obj.style.backgroundColor = 'rgb(255,' + gbColor + ',' + gbColor + ')';
id++;
obj = document.getElementById("red" + id);
}
if(gbColor < 255 && id > 0)
setTimeout("RedIn(0)", 100);
}
function showCart(next)
{
var ca = document.getElementById("cartArea");
var params = "";
for(i=0; i<document.clientCart.elements.length; i++)
{
param = getElemValue(document.clientCart.elements[i]);
if(param != "")
params += param + "&";
}
if(next)
params += "Next=1";
// alert(params);
ca.innerHTML = postIt(params);
makePie();
// RedIn(1);
}
function tabIfComplete(formField, maxSize, nextField, e)
{
if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
if(keynum < 48)
return;
if(formField.value.length >= maxSize)
{
var nf = document.getElementById(nextField);
if(nf)
nf.focus();
}
}
function sendCommand(command)
{
var ca = document.getElementById("cartArea");
var params = "command=" + command;
var submitOrder = command.indexOf('submitOrder') >= 0;
// alert(command);
if(submitOrder)
{
if(document.getElementById("RESULT").checked)
{
params += "&postSettlement=result";
/*
n = postIt(params);
alert(nOID);
if(nOID > 0)
document.location="orderreview.php?id=" + nOID;
return;
*/
}
else if(document.getElementById("REPORT").checked)
{
params += "&postSettlement=report";
}
else if(document.getElementById("DUPEORDER").checked)
{
params += "&postSettlement=dupeorder";
}
postIt(params);
document.location="cart.php";
return;
}
else if(command.indexOf('priorSearches') >= 0)
{
document.location="orderreview.php?ssnlist=1";
}
else if(command.indexOf('addState') >= 0)
{
for(i=0; i<document.clientCart.elements.length; i++)
{
if(document.clientCart.elements[i].name != "Next")
params += "&" + getElemValue(document.clientCart.elements[i]);
}
}
ca.innerHTML = postIt(params);
makePie();
}
function doReset()
{
var ca = document.getElementById("cartArea");
ca.innerHTML = "";
ca.innerHTML = postIt("reset=1");
makePie();
}
function dupeOrder()
{
var ca = document.getElementById("cartArea");
ca.innerHTML = "";
ca.innerHTML = postIt("dupeOrder=1");
makePie();
}
function resetCart()
{
if(confirm("Empty current cart and start over? Are you Sure?"))
doReset();
}
function saveCart()
{
var ca = document.getElementById("cartArea");
var params = "";
for(i=0; i<document.clientCart.elements.length; i++)
{
params += getElemValue(document.clientCart.elements[i]) + "&";
}
params += "saveExit=1";
ca.innerHTML = postIt(params);
makePie();
RedIn(1);
}
function deleteOrderItem(command)
{
if(!confirm("Delete this search? Are you Sure?"))
return;
var ca = document.getElementById("cartArea");
var params = "command=" + command;
ca.innerHTML = postIt(params);
makePie();
}
// alert("Reloaded");
setTimeout("showCart();", 100);
</script>
Try to move the last line:
setTimeout("showCart();", 100);
...into the $.ready-function:
$(document).ready(function(){
setTimeout("autocomplete()", 500);
});
Otherwise it may happen that showCart() gets called before the elements you access in showCart() are known.
First: Combining jQuery + regular javascript is not a problem -- jquery is made of regular javascript.
Secondly, when you're passing a method into your callback param anything, you can usually just write the name of the method:
$(document).ready(function(){
setTimeout(autocomplete, 500);
});
Third, the issue of using XMLHttpRequest while also using jquery. Jquery has a version of the XHR that is even more cross browser compliant than that is, you should use it:
$.ajax()
Finally, please add an include to the actual jquery file at the beginning of your code..
<script type="text/javascript" src="jquery.js"></script>
Sorry to say, while formatting your code its really pain to do.
I have seen some of issue right now:-
function autocomplete() { first this function has improver closing }; with semi-colon
Below is the repeatitive code:-
//Send the proper header information along with the request
doc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
doc.setRequestHeader("Content-length", params.length);
doc.setRequestHeader("Connection", "close");
document.body.style.cursor = "wait";
doc.send(params);
document.body.style.cursor = "default";</li>
This you can make into a single function call by passing proper parameters.
3.If you are using JQuery then XMLHttpRequest is not required
4.Yet to update...
Open up a javascript console (Ctrl-Shift-J) in Firefox/Chrome and look in the menu bar for other browsers and see what errors show up

ajax form issue IE

I have the following code that works in every browser but IE. When click on the submit button of the form I get no response at all from IE.
form has this value: onsubmit="sendform(this);return false;"
<script type="text/javascript">
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.status);
//alert(http_request.responseText);
toggleDiv('stylized');
showtoggleDiv('success');
} else {
alert('There was a problem with the request.');
}
}
};
http_request.open('GET', url, true);
http_request.send(null);
}
function sendform(el) {
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
query = '?' + query.join('&');
makeRequest("http://markburnettinternational.com/sitelokpw/members/test.php" + query);
}
</script>
<script language="javascript">
function toggleDiv(divid) {
if (document.getElementById(divid).style.display == 'none') {
document.getElementById(divid).style.display = 'block';
} else {
document.getElementById(divid).style.display = 'none';
}
}
</script>
<script>
function showtoggleDiv(divid) {
document.getElementById(divid).style.display = 'block';
}
</script>
Turn on the browser's debugger and put a breakpoint in sendform() and walk through it and see what happens. Alternately turning on the javascript console can give you vital feedback about what's going on.
There are at least three problems with this piece of code:
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
First, always declare your variables within the local scope using var, so use
var query = new Array();
for (var i in sub) {
Second, getElementsByTagName returns a NodeList, which is an array-like object. Never iterate over array(-like object)s using a for … in loop, always use an ordinary for loop.
Third, always use encodeURIComponent to properly encode query parameters:
for (var i = 0, len = sub.length; i < len; i++) {
if (sub[i].name) {
query.push(sub[i].name + '=' + encodeURIComponent(sub[i].value));
}
}
This might solve your IE issue.

Categories

Resources