So I don't have a whole lot of experience with Javascript but I've done pretty well in the past. I have this website where I'm trying to run 'geoip' to pull two iso's to take to a certain page, this I've gotten to function perfectly. However, if said ISO completes a purchase a Thank You page is presented to them, but goes away because the 'geoip' is still in place. I've tried running a 'return' but can't seem to get the hang of it. In Sublime Text 3 it looks fine, any help would be GREATLY appreciated. Here's my code:
$.ajax({
url: 'https://freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// If the visitor is browsing from Australia or New Zealand.
if (location.country_code == 'AU' || location.country_code == 'NZ') {
// Redirect visitor to the purchasing store.
window.location.href = 'http://example.com/order-international/';
else {
location.country_code == 'AU' || location.country_code == 'NZ' === window.location.href = 'http://example.com/thanks-international/') {
return; //stop the execution of function
} else {
//keep on going
}
}
}
});
Two things:
First, when I cleaned up your code formatting, it became fairly clear that there are some misplaced {} (at least). I've tried to guess from the comments what you were really trying to do below.
Second, you've said you want to stop execution of "the function," so I'm guessing this ajax call is in some function somewhere.
What you do is make the rest of the function a function, and then call that from the ajax success handler if you want it to run, or don't if you don't. E.g.:
function yourOuterFunction() {
$.ajax({
url: 'https://freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// If the visitor is browsing from Australia or New Zealand.
if (location.country_code == 'AU' || location.country_code == 'NZ') {
// Redirect visitor to the purchasing store.
window.location.href = 'http://example.com/order-international/';
} else {
// keep going
keepGoing();
}
}
});
function keepGoing() {
// The part you want to do after you have the ajax result
}
}
I didn't quite know what you were trying to do with your thanks-international link, but hopefully that gets you headed the right way.
Related
I am running into a situation in Chrome where a single Ajax call is being performed multiple times (20 times to be exact).
I have an input field that gets triggered when you enter in 5 digits into the zip field.
I am trying to perform a zip code / state validation in my ajax call.
I am crossing domains.
The code performs correctly in Firefox. It makes the single call, and performs the proper maintenance.(see code). The maintenance is nothing significant. It's assigns a title value or changes a class. Nothing that should cause my ajax call to perform multiple times.
I have checked my code. It is not being called 20 times.
I have put counters in my code to see if the function is being called multiple times and it's only being done once.
The reason for the onKeyUp and onInput was to handle if someone typed into the field, or double-clicked on it and used a cached value.
So in Chrome Version 60.0.3112.113, the Ajax call is performed 20 times, and on the 21st, it cancels itself.
I am also using jQuery instead of $ because there is other code being used that I don't have any control over.
Any and all help would be appreciated. If I am missing something, please let me know.
Here's the input field code:
<input id="zipPostal" name="zipPostal" type="text" placeholder="Postal Code" onkeyup="zipValid1()" oninput="zipValid1()" />
Here's the jquery code:
function zipValid1(){
var x = jQuery("#zipPostal").val();
if (x != '00000' && x.length == 5){
jQuery.ajax({
url: 'https://myurl/getzip.cfm',
type:'POST',
crossDomain:true,
data: {zipcode: x},
success: function(data){
if (data.trim() == 'Invalid'){
(perform CSS and JS maintenance)
}
else{
(perform CSS and JS maintenance)
}
} // closes Success
}); // ajax
}
else{
(perform CSS and JS maintenance)
}
};
Your function zipValid1 gets called on every keyup and input, which when typing it is called twice for each character you type into the input.
A standard approach to fix this issue is to "debounce" the function called until after the user has stopped typing.
This is a popular jQuery library to help with this issue. http://benalman.com/projects/jquery-throttle-debounce-plugin/
Here is a simple example of debouncing the function and waiting until 500ms after the user has stopped typing.
var timeout;
function zipValid1() {
clearTimeout(timeout);
timeout = setTimeout(function() {
var x = jQuery("#zipPostal").val();
if (x != '00000' && x.length == 5) {
jQuery.ajax({
url: 'https://myurl/getzip.cfm',
type: 'POST',
crossDomain: true,
data: {
zipcode: x
},
success: function(data) {
if (data.trim() == 'Invalid') {
// (perform CSS and JS maintenance)
} else {
// (perform CSS and JS maintenance)
}
} // closes Success
}); // ajax
} else {
// (perform CSS and JS maintenance)
}
}, 500);
}
I am currently developing a chat using your typical everyday web programming languages (JavaScript, PHP etc..). The chat is currently fully functional. However, there are several issues that I have yet to solve successfully. One of which being a cross-browser issue.
I am trying to run an AJAX request when a user closes the tab. The PHP for this request looks something like this:
date_default_timezone_set("America/New_York");
session_start();
unset($_SESSION["onpage"]);
if ($_POST['logout'] == "false") {
sleep(5);
if (isset($_SESSION["onpage"]) || !empty($_SESSION["onpage"])) die();
}
...
...
And the AJAX being:
$.ajax({ // this is jQuery
type: "POST",
url: "offline.php",
data: {
logout: out ? 'true' : 'false'
},
success: function (data) {
document.location.reload();
}
});
Basically, when a user closes the tab (in that case $_POST['logout'] will equal false), the request should not finish until the 5 seconds (sleep(5)) have finished. This is because I do not want this request to be fired when a user simply refreshes the page, only when it is confirmed that he left the page.
This is where the cross-browser issue comes in. The functionality I want to achieve works perfectly fine in Safari. This being that on refresh, the request doesn't finish, but if I close the tab, after 5 seconds it does what it is suppose to do and completes. However, on chrome when I hit refresh, refresh itself does not complete until the 5 seconds are over already over which means the request completes regardless. Chrome is waiting for the AJAX to be completed while Safari does not.
Is there any simply fix to this issue?
Edit:
I have tried the following code from a suggestion in the comments:
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (isChrome) {
var formData = new FormData();
formData.append("logout", "false");
navigator.sendBeacon("offline.php", formData);
} else {
$.ajax({ // this is jQuery
type: "POST",
url: "offline.php",
data: {
logout: 'false'
},
success: function (data) {
document.location.reload();
}
});
}
It however did not successfully work.
Currently I've been stuck on this code for almost two days now looking up everything I can on it but nothing I've tried has quite panned out, this could partly be due to me implementing it incorrectly or something else, but I figured I would finally ask. I should start by saying that I'm inside of a fancybox. The value of true that I want bIsError to be, shows up in console.log, however window.alert shows me that it's set to false. I did notice that the value changes once I run through my code. For example - If the username is incorrect it returns false then sets bIsError to true and displays an error message. However I just need it to return true and then give the error so that my code works. Anyways, here's my code, thanks for any feedback anyone will have as well, I really appreciate it.
if (typeof bFirstLoginPrep == 'undefined') {
var bFirstLoginPrep = true;
}
if (typeof $ != 'undefined') $(function () {
$(".ajaxformsubmit").unbind("click");
$(".ajaxformsubmit").click(function (event) {
setTimeout("lfSubmitForm()", 100);
return false;
});
});
function lfSubmitForm()
{
$form = $(".ajaxformsubmit").parents("form");
response = $.ajax({
url: $form.attr("action"),
type: "POST",
async: false,
data: $form.serialize()
}).responseText;
var responseList = false;
if (responseList == <%=LCase(bisError)%>) {
lfLoginSuccess();
} else {
$("#fancybox-inner").html(response);
$.fancybox.resize();
}
}
DinoMyte
<%=bIsError%> gives you the value of an instance server-side variable. If you are updating it via Ajax, it wouldn't work because you are probably making an ajax call to a pagemethod which is declared as static and static methods cannot manipulate the instance members of the page. In order to make it work with ajax, you need to return bIsError as part of the ajax response.
Amos
Yes, as DinoMyte says. Also you could set blsError as a session variable in this script before it is sent to the browser and then the script that the ajax calls can read it server-side.
I have a java servlet which responds with a number in text/plain format. What I want to do is have another page run a script which polls this URL and triggers an alert window when the number there has changed from the first time it was loaded. I have little to no experience with javascript and so far have been unable to follow any of the long-polling tutorials I have found.
Basically, I need to start the poll on page load, remember what the first value retrieved was, and then trigger an alert window once the value changes.
This is what I have so far, however I believe I need to parse the data somehow. The URL returns a text/plain page with a number on it. That's it.
var initial = null;
function checkForMsg() {
$.ajax({
type: "GET",
url: URL_GOES_HERE,
dataType : "text",
async: true,
cache: false,
success: function(data) {
if (initial == null) {
initial = data
}
else if (initial != data) {
alert(data);
}
setTimeout('checkForMsg()', 12000);
},
error: function() {
setTimeout('checkForMsg()', 12000);
}
})
}
$(document).ready(function(){
checkForMsg();
});
My users keep complaining that a link does not show up for them. For me, I have tested this on several browsers and it works for me.
What should happen is that a process is started via AJAX using JQuery and once that is done I keep checking with the server via AJAX how much of the process has been done and once the process is complete I show them a link. But a lot of users tell me that it shows them the link and it quickly disappears back to showing 100.0%!
I can't see how I can fix this and I was hoping you guys could help me write something fool proof so that the link is always shown!
Here is the code concerned (its been shortened).
var startTime;
var continueTime;
var done = false;
function convertNow(validURL){
startTime = setTimeout('getStatus();', 6000);
$.ajax({
type: "GET",
url: "main.php",
data: 'url=' + validURL + '&filename=' + fileNameTxt,
success: function(msg){
done = true;
$("#loading").hide("slow");
$("#done").html("LINK SHOWN HERE");
}//function
});//ajax
}//function convertNow
function getStatus()
{
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
}
});//ajax
continueTime = setTimeout('getStatus();', 3000);
}
}
Thanks all
P.S. I have this question before and was given an idea of using a conditional in the function but that didn't work when it should have!!
UPDATE
I have some of my users what OS and browsers they are using and they usually say a Mac Os and firefox or safari. Not sure if that help with the solution.
The behaviour described by the users suggests that the success callback of your getStatus function is called after the one in convertNow. You should test done variable in this callback
function getStatus(){
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
// FIX : Already done, just ignore this callback
if (done) return;
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
// BONUS : call getStatus only when previous ajax call is finished
continueTime = setTimeout('getStatus();', 3000);
}
});//ajax
}
}
EDIT : This solution should prevent the bug from appearing most of the time, but there is still a chance. The only way to be sure is to remove the callback from convertNow and let the one in getStatus set the link when the processing is done (don't forget to allow only one call to getStatus at a time, see "BONUS" modification above).
If done is never set back to false then the reported behavior would be expected upon the second call to convertNow.
Since the ajax call in convertNow uses GET instead of POST, it is possible that a browser is returning a cached result whenever parameters are identical to a previous call.