Javascript - Playing sound on variable change - javascript

I'll try to explain this as much as possible, but basically what I'm trying to do is create an Instant Messaging Service for my website to be used by privately by a group of people. I've got the sending and receiving down pat, but I can't seem to find a work around for the notification sounds.
What I would like is for a notification sound to play when a new message is received. I've been fiddling with it for about 45 minutes, and I've tried looking around for a solution, but I can't seem to find any avail.
Here is my Javascript:
function update() {
var xmlhttp=new XMLHttpRequest();
var username = "<?php echo $ugt ?>";
var output = "";
var number = 0;
var messages = msgarea.childElementCount / 2;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var response = xmlhttp.responseText.split("\n")
var rl = response.length
var item = "";
for (var i = 0; i < rl; i++) {
item = response[i].split("\\")
if (item[1] != undefined) {
if (item[0] == username) {
output += "<div class=\"msgsentby ext\"><div class='imgprop'></div></div><div class=\"msgc\"> <div class=\"msg msgfrom\">" + item[1] + "</div> <div class=\"msgarr msgarrfrom\"></div> </div>";
} else {
output += "<div class=\"msgsentby\"><img src='https://api.lspd-fibo.com/avatar/?gt=" + item[0] + "'></div> <div class=\"msgc\"> <div class=\"msg\">" + item[1] + "</div> <div class=\"msgarr\"></div></div>";
number = msgarea.childElementCount / 2;
}
}
}
msgarea.innerHTML = output;
if (messages < number ) {
audio.play();
setTimeout(function() {
messages = msgarea.childElementCount / 2;
}, 500);
}
msgarea.innerHTML += "number: " + number;
msgarea.innerHTML += " messages: " + messages;
}
}
xmlhttp.open("GET","get-messages.php?username=" + username,true);
xmlhttp.send();
}
function sendmsg() {
var message = msginput.value;
var delay = 1500;
if (message != "") {
var username = "<?php echo $ugt ?>";
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {}
}
message = escapehtml(message)
msgarea.innerHTML += "<div class=\"msgc\" style=\"margin-bottom: 30px;\"> <div class=\"msg msgfrom sending\">" + message + "</div> <div class=\"msgarr msgarrfrom\"></div> <div class=\"msgsentby msgsentbyfrom\">Sending...</div> </div>";
msginput.value = "";
var objDiv = document.getElementById("msg-area");
objDiv.scrollTop = objDiv.scrollHeight;
xmlhttp.open("GET","update-messages.php?username=" + username + "&message=" + message,true);
xmlhttp.send();
setTimeout(function() {
var objDiv = document.getElementById("msg-area");
objDiv.scrollTop = objDiv.scrollHeight;
}, delay);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var objDiv = document.getElementById("msg-area");
objDiv.scrollTop = objDiv.scrollHeight;
}
}
}
}
I apologize if it's a little messy, but this is what I have to work with. I appreciate any assistance that anyone can offer in advance :)
//EDIT 1
Personally, what I was thinking may work, was to count all of the messages when the page had loaded, and every time the script refreshed and a new number was detected, make a sound.. I've tried getting this particular method to work, also with no avail but that is likely due to my lack of knowledge in the process.
//EDIT 2
I've edited my JavaScript with what I've been trying to work with in the meantime.

I have taken your code, moved a few variable declarations up and switched to using Array.prototype.forEach() so we don't have to handle incrementing the index manually... This works for me...
function update() {
var xmlhttp=new XMLHttpRequest();
var username = "Fred";
var output = "";
var number = 0;
var oldVar; //initialize here instead of after forEach
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var response = xmlhttp.responseText.split("\n")
var rl = response.length
var item; //just declare array here but don't need to set value
response.forEach(function(responseLine,index) {
item = responseLine.split("\\")
if (item[1] != undefined) {
number++;
if (item[0] == username) {
output += "<div class=\"msgsentby\"><div class='imgprop'></div></div><div class=\"msgc\"> <div class=\"msg msgfrom\">" + item[1] + "</div> <div class=\"msgarr msgarrfrom\"></div> </div>";
} else {
output += "<div class=\"msgsentby\"><img src='https://api.lspd-fibo.com/avatar/?gt=" + item[0] + "'></div> <div class=\"msgc\"> <div class=\"msg\">" + item[1] + "</div> <div class=\"msgarr\"></div></div>";
}
}
});
if (oldVar != number) {
var audio = new Audio('notification.mp3');
audio.play();
}
msgarea.innerHTML = output;
//removed var keyword here so we don't re-declare it each time
oldVar = number;
}
}
xmlhttp.open("GET","get-messages.php?username=" + username,true);
xmlhttp.send();
}

Related

how to fix javascript refresh error on google chrome

I have an error which is giving me a hard time to fix. I have written a program in JavaScript but when I refresh it doesn't affect the page. I even closed and opened the browser more than once but it didn't work, please does anyone have a solution to it?
This is some part of the code
var person = document.getElementById('formant');
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var num = document.getElementById('num').value;
var pass = document.getElementById('pass').value;
var conpass = document.getElementById('conpass').value;
var gen ='';
function setgen(f)
{
gen = document.getElementById(f).value;
}
person.addEventListener('submit', red);
function red(m)
{
m.preventDefault();
var xhr = new XMLHttpRequest();
// var response = document.getElementById().innerHTML;
xhr.open('POST','php/signupajax.php',true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function()
{
if(this.status == 200)
{
if(document.getElementById('pass').value.lenght < 0)
{
alert('less man');
}
console.log(this.responseText);
}
}
xhr.send('fname=' + document.getElementById('fname').value + '&lname=' + document.getElementById('lname').value + '&email=' + document.getElementById('email').value + '&num=' +document.getElementById('num').value+ '&pass=' + document.getElementById('pass').value + '&conpass=' +document.getElementById('conpass').value + '&gen=' + gen);
}
if(document.getElementById('pass').value <6)
{
alert('password not strong');
}
else{
alert('password good');
}

JSON response returning null array

Please help i have been trying from 1 hours and not able to get whats wrong
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out = arr[i].ID + arr[i].Title + arr[i].Description;
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
I am trying to fetch details from http://it-ebooks-api.info/v1/book/2279690981 but it show only empty array being returned. What changes are required ?
Modification
I added [ ] on JSON object and it worked .. Please can someone explain me.
Thank in advance :)
The response does not contain an array, so the for loop is not needed and this should get you the result you are looking for:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var out = "";
var i;
out = "<p>" + response.ID + response.Title + response.Description + "<p>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
If you use the full listing available from http://it-ebooks-api.info/v1/search/php, then you need the for loop to go through the array like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse.Books);
}
}
function myFunction(Books) {
var out = "";
for (var i = 0; i < Books.length; i++) {
out += "<p>ID: " + Books[i].ID + "</p>" + "<p>Title: " + Books[i].Title + "</p>" + "<p>Description: " + Books[i].Description + "</p>"
}
document.getElementById("id01").innerHTML = out;
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
And to make it slightly more elegant, you could have a function that adds the book and if you get only one book you can call it directly from the onreadystatechange, and if you have the full listing, then you can loop it through, but still use the same function. So something like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttpo.responseText);
if (response.Books) { // If the response object has Books array, we pass it to the parseBooks functoin to add them all one by one.
parseBooks(response.Books)
} else {
addBook(response); // If there is no Books array, we assume that there is only one book and add it to the list with addBook function.
}
}
}
function addBook (Book) {
var text = document.getElementById("id01").innerHTML;
var body = "<p>ID: " + Book.ID + "</p><p>Title: " + Book.Title + "</p><p>Description: " + Book.Description + "</p>";
document.getElementById("id01").innerHTML = text + body; // Append the innerHTML with the new Book.
}
function parseBooks(Books) {
for (var i = 0; i < Books.length; i++) {
addBook(Books[i]) // Add all books in the array one by one
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
You JSON feed is just a simple object and not an Array of objects. Note the opening curly braces in the returned feed: {}
You should then change your myFunction function so it goes through an object and not an array just by removing the for loop:
function myFunction(obj) {
var out = "",
id01 = document.getElementById("id01");
out = obj.ID + obj.Title + obj.Description;
id01.innerHTML = id01.innerHTML + out;
}
Edit:
You can use the same function then inside a for loop when you have to parse an Array of Objects.
Taking as a feed the JSON returned from http://it-ebooks-api.info/v1/search/php, you can retrieve the Books value and then loop through it:
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
var url2 = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var rslt = JSON.parse(xmlhttp.responseText);
console.log(rslt);
var books = rslt.Books;
for (var i = 0; i < books.length; i++)
{
myFunction(books[i]);
}
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();

javascript function doesn't seem to be calling

I am creating an AJAX dynamic search bar which returns results from a database. I find that when i open the debugger, the code isn't entering the function handleSuggest() which sets the inner html of the div where the results are shown. Here is my code.
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
var search = getXmlHttpRequestObject();
function ajaxSearch(){
if (search.readyState == 4 || search.readyState == 0){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", 'searchSuggest.php?search=' + str, true);
search.onreadystatechange.handleSearchSuggest();
search.send(null);
}
}
function handleSearchSuggest(){
if(search.readyState == 4){
var ss = document.getElementById('ajaxSearch');
ss.innerHTML = '';
var str = search.responseText.split("\n");
for(i=0; i<str.length-1; i++){
var suggestion = '<div onmouseover="javascript:suggestOver(this);"';
suggestion += 'onmouseout="javascript.suggestOut(this);"';
suggestion += 'onclick="javascript:setSearch(this.innerHTML);"';
suggestion += 'class="suggestLink">' + str[i] + '<div>';
ss.innerHTML += suggestion;
}
}
}
function suggestOver(divValue){
divValue.className = "suggestLink";
}
function suggestOut(divValue){
divValue.className = "suggestLink";
}
function setSearch(x){
document.getElementById('searchBox').value = x;
document.getElementById('ajaxSearch').innerHTML = '';
}
The problem is in this line:
search.onreadystatechange.handleSearchSuggest();
search.onreadystatechange needs a callback function assigned to it.
Change it to the following:
search.onreadystatechange = handleSearchSuggest;
Note that this does not invoke the handleSearchSuggest function here as onreadystatechange needs a callback function not the result of the function.

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

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

Categories

Resources