IE not activating Ajax - javascript

I have the following script on my page, in Chrome, it works perfectly, but IE is not getting into the success{} function of Ajax. It goes into the Complete{} function perfectly fine. When I tried to send the data variable through the Complete{} function, it just displays an [object Object] as the contents. What can I do to get this to function in IE?
$(document).ready(function () {
var totalstrings = "";
var totaltimes = "";
var trendstop = "false";
var firstrun = "true";
var url = "newtrend.aspx";
$('#fm1').attr('src', "http://somepage/page1/collecttrend.aspx");
(function worker() {
var rand;
$.ajax({
url: 'http://somepage/page1/gettrendvars.aspx',
success: function (data) {
if (totalstrings.length < data.length || data === "") {
alert("test1");
if (trendstop === "false") {
alert("test2");
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
},
complete: function (data) {
setTimeout(worker, 10000);
$.ajax({
url: 'http://somepage/page1/gettimevars.aspx',
success: function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
},
complete: function (data) {
}
})();
}
});
})();
});

Try adding a timestamp to your ajax requests, for some reason, IE caches it sometimes.
$.ajax({
url: 'http://somepage/page1/gettrendvars.aspx?timestamp='+ new Date().getTime(),
success: function (data) {
if (totalstrings.length < data.length || data === "") {
alert("test1");
if (trendstop === "false") {
alert("test2");
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
},
complete: function (data) {
setTimeout(worker, 10000);
$.ajax({
url: 'http://somepage/page1/gettimevars.aspx?timestamp=' + new Date().getTime(),
success: function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
},
complete: function (data) {
}
})();
}
});

Finally got it to work, in conjunction with Vinicius Souza's answer. Utilizing the $.get() command rather than the ajax(), and activating the timestamp to break the caching of IE.
Thanks Everyone!
(function worker() {
var rand;
$.get("http://somepage/page1/gettrendvars.aspx?timestamp=" + new Date().getTime(), {})
.done(function (data) {
if (totalstrings.length < data.length || data === "") {
if (trendstop === "false") {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
$.get("http://somepage/page1/gettimevars.aspx?timestamp=" + new Date().getTime(), {})
.done(function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
});
})
.fail(function () {
});
setTimeout(worker, 1500);
})();

Related

i want next ajax request wait until the previous request is done

i send ajax request every 5 second and i want wait for next requset until the previous one is done ...
Because it sends a lot of requests even if the status of the previous request is pending, and this causes me a problem with the server.
this is my Java Script code :
this is my Java Script code :
$(document).ready(function(e){
$("#getUsersId").on('submit', function(e){
e.preventDefault();
$('.loading_spinner').css('display','flex');
$('.form-fieldset.api-mode').attr('disabled','disabled');
let id = 1;
let zeroNum = "0";
var keyword = $('#keyword').val();
var region = $('#region').val();
// you can use a "fat-arrow" function or a function reference, look at the docs
let timer = 5000;
// console.log(timer);
const interval = setInterval(() => {
if (id>=9) {
let zeroNum = "";
}
$.ajax({
type: "post",
url: "dataExtractorRequset.php",
data: {keyword: keyword,region: region,id:id},
dataType: 'json',
success: function (response) {
// var parsedJson= JSON.parse(response);
// console.log(response);
function countTextArea() {
var text = $("#FbUsersId").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length-1;
return count;
}
var output2 = "";
if(response.status == 1){
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'success',
title: response.message,
showConfirmButton: true,
timer: 3000,
timerProgressBar: true
})
);
$('.loading_spinner').css('display','none');
$('.form-fieldset.api-mode').removeAttr('disabled');
$('#sendForm').css('display','block');
var arr = $("#FbUsersId").val().split("\n");
var arrDistinct = new Array();
$(arr).each(function(index, item) {
if ($.inArray(item, arrDistinct) == -1)
arrDistinct.push(item);
});
var newUniquData = arrDistinct;
$.each(newUniquData, function(key, value) {
output2 += value+'\r\n';
});
$("#FbUsersId").val(output2);
$('#usersCount').html(countTextArea);
var text = $('#FbUsersId').val();
text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
$(FbUsersId).val(text);
console.log("success");
console.log(arrDistinct);
alert("Done !!!");
}else{
var output = "";
for (i =0; i< response.length; i++) {
console.log(response[i].data.user_url);
output += response[i].data.user_url+ '\r\n';
}
// var appendData = $("#FbUsersId").val();
// var newData = appendData + output;
$("#FbUsersId").append(output);
$('#usersCount').html("Loading...");
if(response.status == 0) {
$('.loading_spinner').css('display','none');
$('.form-fieldset.api-mode').removeAttr('disabled');
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'error',
title: response.message,
text: response.errMSG,
showConfirmButton: true,
timer: 10000,
timerProgressBarColor: '#435ebe',
timerProgressBar: true
}).then(function(isConfirm) {
if (isConfirm) {
// location.reload();
} else {
//if no clicked => do something else
}
})
);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
// console.log(textStatus, errorThrown);
}
});
id++;
// stop the interval when id is greater 9
// if (id > 9) {
// }
}, timer); // 3000 is the time in milliseconds
});
});
How can I solve this problem.
Not so elegant (I would set setTimeout) but as Barmar suggested a global variable is quick solution:
$(document).ready(function (e) {
$("#getUsersId").on('submit', function (e) {
e.preventDefault();
$('.loading_spinner').css('display', 'flex');
$('.form-fieldset.api-mode').attr('disabled', 'disabled');
let id = 1;
let zeroNum = "0";
var keyword = $('#keyword').val();
var region = $('#region').val();
// you can use a "fat-arrow" function or a function reference, look at the docs
let timer = 10000;
// console.log(timer);
var in_progress
const interval = setInterval(() => {
if (in_progress) {
return;
}
in_progress = true;
if (id >= 9) {
let zeroNum = "";
}
$.ajax({
type: "post",
url: "dataExtractorRequset.php",
data: { keyword: keyword, region: region, id: id },
dataType: 'json',
success: function (response) {
in_progress = false;
// var parsedJson= JSON.parse(response);
// console.log(response);
function countTextArea() {
var text = $("#FbUsersId").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length - 1;
return count;
}
var output2 = "";
if (response.status == 1) {
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'success',
title: response.message,
showConfirmButton: true,
timer: 3000,
timerProgressBar: true
})
);
$('.loading_spinner').css('display', 'none');
$('.form-fieldset.api-mode').removeAttr('disabled');
$('#sendForm').css('display', 'block');
var arr = $("#FbUsersId").val().split("\n");
var arrDistinct = new Array();
$(arr).each(function (index, item) {
if ($.inArray(item, arrDistinct) == -1)
arrDistinct.push(item);
});
var newUniquData = arrDistinct;
$.each(newUniquData, function (key, value) {
output2 += value + '\r\n';
});
$("#FbUsersId").val(output2);
$('#usersCount').html(countTextArea);
var text = $('#FbUsersId').val();
text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
$(FbUsersId).val(text);
console.log("success");
console.log(arrDistinct);
alert("Done !!!");
} else {
var output = "";
for (i = 0; i < response.length; i++) {
console.log(response[i].data.user_url);
output += response[i].data.user_url + '\r\n';
}
// var appendData = $("#FbUsersId").val();
// var newData = appendData + output;
$("#FbUsersId").append(output);
$('#usersCount').html("Loading...");
if (response.status == 0) {
$('.loading_spinner').css('display', 'none');
$('.form-fieldset.api-mode').removeAttr('disabled');
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'error',
title: response.message,
text: response.errMSG,
showConfirmButton: true,
timer: 10000,
timerProgressBarColor: '#435ebe',
timerProgressBar: true
}).then(function (isConfirm) {
if (isConfirm) {
// location.reload();
} else {
//if no clicked => do something else
}
})
);
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
// console.log(textStatus, errorThrown);
in_progress = false;
}
});
id++;
// stop the interval when id is greater 9
// if (id > 9) {
// }
}, timer); // 3000 is the time in milliseconds
});
});

jQuery run js function on page load

I have this below function to filter search
function GetFilters()
{
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
var categoryid = loc.pathname.split('/').pop();
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
// get all keys.
var keys = Object.keys(data);
var fdata = "";
// iterate over them and create the fdata
keys.forEach(function(key,i){
if (i>0) fdata += '&'; // if its not the first key add &
fdata += key+"="+data[key].join(',');
});
$.ajax({
type: "get",
url: "<?php echo $appURL; ?>/productByCategory",
data: {
"fdata": fdata,
"categoryID": categoryid
},
success: function (response) {
$('.productCategory').html(response);
}
});
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
}
window.onload = GetFilters;
and now I want to run the function every page loaded, but it seems there is no effect and display is empty.
PHP
if(isset( $_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'))
{
}
If I remove this: if(isset( $_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'))
{
}
I can see the data display.
I need to do this because prevent user directly open productByCategory.php
How to do that?

Why don't work my function xmlParser(). Help me please

Hello everybody. I have a problem with my code. I use the jquery framework. When I want to call $.ajax(requestOptions), function xmlParser(xml) don't working.
I try to find a resolve this problem, but I can't nothing find.
$(document).ready(function () {
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser //Calling function
};
function xmlParser(xml) {
$("#load").fadeOut();
$(xml).find("Valute").each(function() {
$("#outputListValutes").append(
"<option value=" + $(this).find("CharCode").text() + ">" + $(this).find("CharCode").text() + "</option>");
});
};
$.ajax(requestOptions);
$("#clear").click(function() {
var sumValue = document.getElementById("sum").value = "";
var resValue = document.getElementById("result").value = "";
});
$("#convert").click(function(xml) {
//var selectCurrency = $("#inputListCurrency").val();
//findData(xml);
}(requestOptions));
function findData(xml) {
var decimalOnly = /^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/;
try{
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if(value == "") throw new Error("Empty value");
else if(!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if(value < 0) throw new Error("Value isn't to be below zero");
else if(isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function() {
if(shortName == $(this).find("CharCode").text()) {
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch(e) {
alert(e);
}
}
});
change the success parameter of the request to use the xmlParser function (forgot () ):
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser(data) //Calling function
};
I found the solution this promlem. I am happy.
var courseFilePath = "xml/Course_Currency_02-07-2014.xml";
var listCurrency = [];
function insertOptions(){
for (var i = 0; i < listCurrency.length; ++i){
$("#outputListCurrency").append(
"<option value=" + listCurrency[i] + ">" + listCurrency[i] + "</option>");
}
}
function xmlParser(xml){
$("#load").fadeOut();
$(xml).find("Valute").each(function(){
var value = $(this).find("CharCode").text();
listCurrency.push(value);
});
listCurrency.sort();
};
function findData(xml){
var decimalOnly = /^\s*-?[0-9]\d*(\.\d{1,2})?\s*$/;
try {
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if (value == "") throw new Error("Empty value");
else if (!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if (value < 0) throw new Error("Value isn't to be below zero");
else if (isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function(){
if (shortName == $(this).find("CharCode").text()){
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch (e){
alert(e);
}
}
$(document).ready(function(){
$.ajax({
type: "GET", //The method of sending for data
url: courseFilePath, //It is reference on xml file
dataType: "xml", //The type of data
success: function(xml){
xmlParser(xml);
insertOptions();
}
});
//insertOptions();
$("#clear").click(function() {
document.getElementById("sum").value = "";
document.getElementById("result").value = "";
});
$("#convert").click(function() {
var selectCurrency = $("#inputListCurrency").val();
$.get(courseFilePath, findData, "xml");
});
});

How to stop interval function

I'm trying to stop with return syntax:
<script>
$(document).ready(function() {
setInterval(function() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
f(data.exists == 0){
alert("0");
} else {
alert("1");
return;
}
});
}, 5000);
});
</script>
The function verifies every 5 seconds if there exists data in my table.
I need to stop the function when data.exists == 1 ( the alert("1") ).
<script>
$(document).ready(function() {
var id;
id = setInterval(function() {
var idRefCopy = id; // You need this otherwise you'll get a reference exception
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
if(data.exists == 0){
alert("0");
} else {
alert("1");
clearInterval(idRefCopy);
return;
}
});
}, 5000);
});
</script>
You have to define the interval inside a variable, and then clear it. Try this:
<script>
$(document).ready(function() {
var interval = setInterval(function() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
if(data.exists == 0){
alert("0");
} else {
clearInterval(interval);
}
});
}, 5000);
});
</script>
You have a typo in the code (i have fixed it here, its a "f" instead of "if" ;) Hope this helps.
You need to clear your interval, this will prevent your function from being fired again. See this for interval reference.
This should be your code:
$(document).ready(function() {
var i = setInterval(function() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
f(data.exists == 0) {
alert("0");
} else {
alert("1");
clearInterval(i);
}
});
}, 5000);
});
How about clearInterval?
var myVar = setInterval(function(){myTimer()},1000);
function myTimer()
{
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction()
{
clearInterval(myVar);
}
source: W3Schools
I strongly suggest you do not hit your server unless you know your ajax was done
This example will check, but only after the server returned
var counter = 0;
function checkData() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
if (data.exists == 0) {
$("#someContainer").html("Not yet on attempt #"+(counter++));
setTimeout(checkData,5000);
} else {
$("#someContainer").html("found on attempt #"+(counter++));
}
});
}
$(function() {
checkData();
});

Javascript does user exists, returning value from ajax to late?

I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
    var data = 'user='+ fullname;
    if(fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
async: false,
            beforeSend: function(html) {
                $("#msg_lastname").html('');
            },
            success: function(html){
                $("#msg_lastname").show();
                 $("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
            }
        });
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}

Categories