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

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

Related

How to modify anchor tags in botframework Web chat

We've just started using the bot-framework. For client side we are using the cdn and not react. We have certain links that bot responds with. And we would like to append a url parameter to each link and open the link in the same window. So far this is what my code looks like. Is there a better way to achieve this using the botframework. I know there is cardActionMiddleware which has openUrl cardAction, but we don't have any cards and I am not sure on how to implement that.
var webchatMount = document.getElementById('webchatMount');
function loadChatbot() {
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://webchat.botframework.com/api/tokens", true);
xhr.setRequestHeader('Authorization', 'BotConnector ' + '<secret>');
xhr.send();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var store = window.WebChat.createStore({}, function ({ dispatch }) {
return function (next) {
return function (action) {
if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
var event = new Event('webchatincomingactivity');
event.data = action.payload.activity;
window.dispatchEvent(event);
}
return next(action);
}
}
});
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token: response }),
store: store,
},
webchatMount
);
document.querySelector('.webchat__send-box-text-box__input').focus();
window.addEventListener('webchatincomingactivity', ({ data }) => {
setTimeout(function () {
var links = document.querySelectorAll('#webchatMount a');
if (links.length >= 1) {
for (var i = 0; i <= links.length; i++) {
if (links[i] == undefined)
break;
var compare = new RegExp('maindomain');
var href = links[i].getAttribute('href');
var st = getParameterByName('st', href);
if (links[i].hasAttribute('target')) {
links[i].removeAttribute('target');
}
if (compare.test(href)) {
// internal link
// check if it has st=INTRA
if (st) {
console.log(' it has a value');
} else {
links[i].setAttribute('href', insertParam('st', 'INTRA', href));
}
} else {
// external link, do nothing
}
}
}
}, 1000);
});
}
}
}
and here are getParameterByName and insertParam functions.
function getParameterByName(name, url) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function insertParam(key, value, url) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = url.split('&');
var i=0;
for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
var pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}
return kvp.join('&');
}
I am new to botframework webchat so I don't know it very well. I know that the secret should not be used like that, but for know we are testing and would like to get it to work. Any help would be appericiated
Thanks.

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')

JavaScript extracting data from XML (if else statement not working)

So my problem in the code below is in the following if else if statement at the bottom:
1. the code in both of the if statements work perfect.
2. the issue is that when i run the code on one can be use.
if i do 2 separate if statements only the second one works.
if i do 1 if and one else if only the if statement works and the else if does nothing.
a little more info: what I'm trying to do is every time the function times out and loops through again it will check the if statements and if something changed to run the appropriate if clause.
PLEASE LET ME KNOW IF MORE INFO IS NEEDED.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
alert("cant create object");
else
return xmlHttp;
}
function process_search()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
search_parameter = encodeURIComponent(document.getElementById("userInput").value);
search_type = encodeURIComponent(document.getElementById("userOptions").value);
xmlHttp.open("GET", "../pages/search_xml.php?search_parameter=" + search_parameter + "&search_type=" + search_type, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process_search()',5000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
if(document.getElementsByTagName('find_users')) // FIND USERS
{
first_name = root.getElementsByTagName('first');
last_name = root.getElementsByTagName('last');
users = document.createElement('ul');
users.setAttribute("id", "usersFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< first_name.length; i++)
{
usersList = document.createElement('li');
t = document.createTextNode(first_name.item(i).firstChild.data + " - " + last_name.item(i).firstChild.data + "<br/>");
usersList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(usersList);
}
}else if(document.getElementsByTagName('find_config_item')) //FIND CONFIG ITEMS
{
item = root.getElementsByTagName('item');
desc = root.getElementsByTagName('description');
itemsList = document.createElement('ul');
itemsList.setAttribute("id", "itemsFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< item.length; i++)
{
itemList = document.createElement('li'); // CREATE LIST ITEM ELEMENT
t = document.createTextNode(item.item(i).firstChild.data + " - " + desc.item(i).firstChild.data + "<br/>");
itemList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(itemList);
}
}
setTimeout('process_search()', 5000);
}
else
{
alert("something is wrong");
}
}
}
You shouldn't really rely on try/catch for this use case. You can be fairly certain the XMLHttpRequest or a Mircrosoft.XMLHTTP object will exist so you could simplify your code to the following:
function createXmlHttpRequestObject () {
return window.XMLHttpRequest ? new XMLHttpRequest() : new XDomainRequest();
}
var xmlHttp = createXmlHttpRequestObject();
Let me know if you would like to see a non ternary version

Something is preventing my submit button from functioning

I posted earlier regarding a different topic and want to thank all who helped me out. I've cleaned up my code pretty well (I think) but now when I click 'submit' nothing happens. I suspect the issue is regarding sending data with ajax but there is a problem with the way I've written things to send both text and radio data. Before posting this, I did do a thorough search to see if the question may have been answered in another's post but didn't find it - probably because I'm not astute enough with javascript to relate it to my own code. Anyway, here is a sample http://jsfiddle.net/J2yWQ/78/ If someone could find my issue I would really appreciate it.
function emailWarning() {
var check = document.getElementById("check");
check.className = 'show';
}
function validateEmail(xem) {
var re = /\S+#\S+\.\S+/;
return re.test(xem);
}
function postData() {
email = 'email'+document.getElementById('email').value;
var tt = validateEmail(email);
if (tt == true) {
xmlhttp.open('POST', 'payment.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(myProps.join("&"));
} else {
emailWarning();
}
}
var myProps = [];
function insert() {
try {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
myProps = [];
function addProp(id) {
var input = document.getElementById(id);
if(!input) {
input = document.forms[0][id];
}
var value = encodeURIComponent(input.value);
myProps.push(id + "=" + value);
}
addProp('child_name');
addProp('age');
addProp('hometown');
addProp('boy_girl');
addProp('first_name');
addProp('last_name');
addProp('email');
addProp('address1');
addProp('address2');
addProp('city');
addProp('state');
addProp('zip');
addProp('country');
var flagInvalid = false;
var tempArray = document.getElementsByClassName("required");
for (var i = 0; i < tempArray.length; i++) {
if (tempArray[i].value == "") {
flagInvalid = true;
break;
}
}
if (flagInvalid == false) {
postData();
} else {
var showValidationError = function(id) {
var el = document.getElementById(id);
if (el) {
el.className = 'show';
}
else {
alert('Missing element #' + id);
}
}
showValidationError('log');
for (var i = 1; i < 12; i++) {
showValidationError('log' + i);
}
}
} catch (e) {
alert('An error occured in inert: ' + e);
}
}

call generic handler in aspx without jquery

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>

Categories

Resources