I currently have a problem,
I have a client who wants his site in Argentina to be seen only in Argentina and that users entering from another country are redirected to the official website in France, and that when the API query is made if you are inside Argentina, the geolocation script is not executed It should be noted that the only way,the api that I am using is ip api, I have to create it in js. Because the system we are using does not give us access to server. and additionally a cookie must be saved. So I did the following.
var site = {
init: function() {
this.setDisplayClass();
this.global();
this.search();
this.newsletter();
menu.init();
minicart.amount(".cart-link .qty-items");
minicart.create();
minicart.hover();
if ($('body').hasClass('home')) {
banner.background('.main-banner-section .box-banner');
banner.slide('.run-slick');
shelf.slide('.featured-products-slider .shelf ul');
}
if ($('body').hasClass('grid-products')) {
grid.init();
}
if ($('body').hasClass('producto')) {
product.init();
shelf.slide('#related-products .shelf ul');
}
},
}
AND
var geo ={
init: function(){
var isAr = localStorage.getItem("country");
if((isAr == null) || (isAr == undefined)){
$.ajax({
url: 'http://ip-api.com/json/?callback=?',
async: false,
dataType: 'jsonp',
success: function (response) {
var country = response.countryCode;
if(country !== "AR"){
window.location.replace("https://www.google.com.ar");
}else{
localStorage.setItem('country', country);
if($(".loading-hidden").length > 0){
$(".loading-hidden").each(function(){
if ($(this).attr('style') == 'visibility: hidden;') {
console.log(1);
site.init();
$(this).removeAttr('style');
if ($("#loading").length > 0) {
$("#loading").remove();
}
}
});
}
}
}
});
}else{
if ($(".loading-hidden").attr('style') == 'visibility: hidden;') {
site.init();
$('.loading-hidden').removeAttr('style');
if ($("#loading").length > 0) {
$("#loading").remove();
}
}
}
}
}
AND
$(document).on('ready', function() {
});
site.init();
$(window).bind("load", function() {
});
The error I get is that site.init is undefined.
Related
I need help with an advanced search I implemented into a new existing page system.
It seems there is a problem with the existing jquery ui on the page:
<script src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="js/jquery.lazy.min.js"></script>
When I enter my code the page isn't working properly anymore.
My code:
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#warenkorb_suche_feld').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#warenkorb_suche_feld').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#warenkorb_suche_feld").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
The search script works fine but I need to add
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
And after this page stops working. What can I do to get this stuff working?
Consider the following. I was not able to test it.
$(function() {
function search(term, callback) {
$('b#search-string').text(term);
$.ajax({
type: "POST",
url: "search.php",
data: {
query: term
},
cache: false,
success: function(html) {
$("ul#results").html(html);
if(callback && (typeof callback == "function")){
callback();
}
}
});
return false;
}
$('div.icon').click(function() {
$('input#warenkorb_suche_feld').focus();
});
$("input#warenkorb_suche_feld").on("keyup", function(e) {
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string.length > 0) {
$("ul#results, h4#results-text").fadeOut(400, function() {
search(search_string, function() {
$("ul#results, h4#results-text").fadeIn();
});
});
}
});
});
This makes use of the complete callback for .fadeOut(). So once it has faded, it will then run the search. I added a Callback in the search so that once the AJAX has completed, it will reveal the results with .fadeIn().
You may want to consider adjusting the length condition. This ensures
I'm trying to validate Google Captcha and my form, which currently does work. I'm using JQuery Forms and Validate Unobstructive. The problem is after submission, you can still submit the form as many times as you click.
Is there a way to ensure this only happens once?
I have tried using the following (commented in the code), but then you can't submit the form again to recheck the captcha:
if ($form.data('submitted') === true) { } else { }
JS:
$(document).ready(function () {
//Intercept Submit button in order to make ajax call instead of a postback
$('#contactForm').preventDoubleSubmission();
});
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
$("button").click('submit', function (e) {
e.preventDefault();
var $form = $("#contactForm");
$($form).bind("invalid-form.validate", function() {
if( $("invalid-form.validate") ) {
formErrors();
}
})
// if ($form.data('submitted') === true) {
// // Previously submitted - don't submit again
// } else {
if ($form.valid()) {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
if ( captchaCheck() == false) {
captchaCheck();
} else {
// Make ajax call form submission
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
}
});
}
}
// }
});
// keep chainability
return this;
};
function hover() {
$(".contour-button").on("mouseenter", function() {
return $(this).addClass("hover");
});
}
function hoverOff() {
$(".contour-button").on("mouseleave", function() {
return $(this).removeClass("hover");
});
}
function success() {
$(".contour-button").addClass("success");
var formFields = $(".contactForm input, .contactForm textarea, .contactForm button");
$(formFields).attr('disabled', 'disabled');
$(formFields).animate({'opacity':'0.5'});
$(".contour-btn-arrow").addClass("contour-btn-success");
$(".contour-button .submit").html("Thank you for your enquiry");
}
function formErrors() {
$(".contour-button").addClass("form-errors").delay(3500).queue(function(){
$(this).removeClass("form-errors").dequeue();
});
$(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
$(this).removeClass("contour-btn-error").dequeue();
});
$(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
$(this).html("Submit").dequeue();
});
}
function captchaCheck() {
var captchaResponse = grecaptcha.getResponse();
if(captchaResponse.length == 0) {
// html for the captcha error message
var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';
$("#captchaMsg").html(captchaMsgHtml).slideDown(500);
$(".g-recaptcha div div").addClass("recaptchaHighlight");
return false;
} else {
$(".g-recaptcha div div").removeClass("recaptchaHighlight")
$("#captchaMsg").hide();
return true;
}
}
hover();
hoverOff();
You might disable clicked button just putting
var that = this;
$(that).attr("disabled", true);
after
e.preventDefault();
then, if you need, enable it when the operation is completed with
//probably after success()
$(that).attr("disabled", false);
I hope that's what you need!
I managed to solve this in a similar way to MonkeyZeus's suggestion by wrapping the AJAX call in a condition, using a bool (true/false).
var ajaxRunning = false;
$("button").click('submit', function (e) {
e.preventDefault();
var $form = $("#contactForm");
$($form).bind("invalid-form.validate", function() {
if( $("invalid-form.validate") ) {
formErrors();
}
})
if ($form.valid()) {
if ( captchaCheck() === false) {
captchaCheck();
formErrors();
} else {
if(!ajaxRunning){
ajaxRunning = true;
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
},
error: function (result) {
captchaCheck();
formErrors();
}
});
}
}
}
});
function hover() {
$(".contour-button").on("mouseenter", function() {
return $(this).addClass("hover");
});
}
function hoverOff() {
$(".contour-button").on("mouseleave", function() {
return $(this).removeClass("hover");
});
}
function success() {
var disabledElements = "#formFooter button, .contourField input, .contourField textarea";
var opacityElements = ".contourField input, .contourField textarea";
// disable button & inputs once submitted
$(disabledElements).attr('disabled', 'disabled');
// change opacity of elements
$(opacityElements).animate({ 'opacity' : '0.5' });
$(".contour-button").addClass("success");
$(".contour-btn-arrow").addClass("contour-btn-success");
$(".contour-button .submit").html("Thank you for your enquiry");
}
function formErrors() {
$(".contour-button").addClass("form-errors").delay(3500).queue(function(){
$(this).removeClass("form-errors").dequeue();
});
$(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
$(this).removeClass("contour-btn-error").dequeue();
});
$(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
$(this).html("Submit").dequeue();
});
}
function captchaCheck() {
var captchaResponse = grecaptcha.getResponse();
if(captchaResponse.length == 0) {
// html for the captcha error message
var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';
$("#captchaMsg").html(captchaMsgHtml).slideDown(500);
$(".g-recaptcha div div").addClass("recaptchaHighlight");
return false;
} else {
$(".g-recaptcha div div").removeClass("recaptchaHighlight")
$("#captchaMsg").hide();
return true;
}
}
hover();
hoverOff();
For starters, if you are actually using a <form> with a dedicated <submit> or <button type="submit">Submit</button> then you should be listening for on.('submit'):
var allowSubmit = TRUE;
$('form').on('submit', function(e)
{
if(allowSubmit === TRUE)
{
allowSubmit = FALSE;
// Perform your validations + AJAX calls and make sure to set
// allowSubmit = TRUE; wherever appropriate
if(validationFails)
{
allowSubmit = TRUE;
}
else
{
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
allowSubmit = TRUE;
},
error: function() {
// Do some error handling
allowSubmit = TRUE;
}
});
}
}
else
{
e.preventDefault();
}
});
So I've been stuck at this problem for quite a long time. Basically I have a button (#action) located in index.html. I have a second page : number.html. I'm trying to get in the .receiver span from index.html either .success content or .failure content from number.html, depending if #action was clicked in less than 2 seconds.
Here is the code :
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
});
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
});
Problem : on click, I never get the .success content, and I have no error message. But after 2 seconds, the .failure actually shows up. I tried several ways to make it work but it doesnt. I also checked if the flag value was changed on click with an alert box, and it was
You need to include the ajax calls within the on click function, otherwise the if logic will only be called when the page is loaded and never again.
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
flagCheck();
});
var flagCheck = function() {
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
}
});
function getFriends(url) {
return FB.api(url, function(response) {
if (response && !response.error) {
if (response.paging && response.paging.next) {
$.each(response.data, function() {
friends.push(this);
});
return getFriends(response.paging.next);
} else {
console.error(friends);
}
} else {
console.error("facebook friends couldn't been retrieved ");
}
});
}
$.when(getFriends("/me/friends")).then(
function() {
console.log('getFriends finished');
});
i want to make sure that fb calls finished when the then() block executed but had no chance. is there a way to implement this ?
thanks
The Facebook JS SDK does not implement jQuery style promise objects / $.Deferreds but you can easily create an instance on your own like:
function getFriends(url) {
var dfd = $.Deferred();
FB.api(url, function(response) {
if (response && !response.error) {
if (response.paging && response.paging.next) {
$.each(response.data, function() {
friends.push(this);
});
return getFriends(response.paging.next);
} else {
console.log(friends);
}
dfd.resolve();
} else {
console.error("facebook friends couldn't been retrieved ");
dfd.reject();
}
});
return dfd;
}
getFriends("/me/friends").done(
function() {
console.log('getFriends finished');
}
);
Not really an answer, but a working example that demo's how to go about it:
Demo JSFiddle
function doStuff() {
var dfd = new jQuery.Deferred();
alert ("loaded");
setTimeout(function(){
dfd.resolve("response - success");
}, 5000);
return dfd.promise();
}
$.when(doStuff()).then(function(status) {
alert(status);
});
I have the following code to ping a list of computers with Jquery and asp.net.
function ping() {
$('#progress').css("display", "");
$('.comp').each(function () {
var $computer = $(this);
$.getJSON('pingcomputer.aspx', { computer: $(this).attr("rel") }, function (data) {
if (data.Status == '1') {
$($computer).attr("src", "ok.png");
}
else {
$($computer).attr("src", "nok.png");
}
})
})
$('#progress').css("display", "none");
}
The pinging works fine.
Before the ping start I want to make #progress visible (an image)
After all computers are pinged I want to hide it again.
The problem is that the #progress image is immediately hidden when the function is called.
How can I detect when all "pingcomputer.aspx" pages have finished loading?
Add a counter which checks that as many requests have been completed as there was started:
function ping() {
$('#progress').css("display", "");
var count = 0,
total = $(".comp").length;
$('.comp').each(function () {
var $computer = $(this);
$.getJSON('pingcomputer.aspx', { computer: $(this).attr("rel") }, function (data) {
count++;
if (data.Status == '1') {
$($computer).attr("src", "ok.png");
}
else {
$($computer).attr("src", "nok.png");
}
if (count==total) $('#progress').css("display", "none");
})
})
}
Count the number of things that should happen, decrement the count each time one thing does. When there are none left, stop the progress bar. BTW, any reason you're not using show()/hide()?
function ping() {
$('#progress').show();
var $comp = $('.comp'),
waitCount = $(comp).length;
$comp.each(function () {
var $computer = $(this);
$.getJSON('pingcomputer.aspx', { computer: $(this).attr("rel") }, function (data) {
if (data.Status == '1') {
$($computer).attr("src", "ok.png");
}
else {
$($computer).attr("src", "nok.png");
}
if (--waitCount == 0) {
$('#progress').hide();
}
})
})
}