Javascript checking country code keeps refreshing constantly - javascript

My current code checks the country code and then changes the drop down value before submitting it for the things to refresh in right currency pricing, but I've tried things like, putting return; to stop it after running it once and moving return; on different line with no luck. I even combined the .val line with .change() thinking maybe having it on separate lines was running it multiple times and refreshing it multiple times.
Here is my code;
$.ajax({
url: "https://ipinfo.io/json",
type: "GET",
success: function(location) {
if (location.country === 'AU') {
$(".shopify-currency-form select").val("AUD").change();
} else if (location.country === 'AR') {
$(".shopify-currency-form select").val("ARS");
} else if (location.country === 'CA') {
$(".shopify-currency-form select").val("CAD");
} else if (location.country === 'US') {
$(".shopify-currency-form select").val("USD").change();
}
return;
}
} );
$('.shopify-currency-form select').on('change', function() {
$(this)
.parents('form')
.submit();
return;
});

Related

Javascript, Socket.io - alert shows up more than one time

When I click the follow button, socket.io sends some data to the server, and then the server sends back a response number. According to what the number is, js alerts a message. But if I click the button a second time, js will alert the same message twice, and if I click it again, three times and so on. If I refresh the page, it starts all over again (click it once, alert shows up once, click it twice, alert shows up twice...)
Here's the code:
$('.followUser').click(function(e){
e.stopImmediatePropagation();
e.preventDefault();
var user= $(this).parent().parent().parent().parent().next().children().children('.userName').children().first().children().attr('id');
var thisUserId = $.cookie('thisUserID');
if(user != thisUserId){ //if he tries to follow himself
var object = {
user: user,
userId: thisUserId
}
socket.emit('followUser', object); //server just adds that user to the following list of the first user
socket.on('followUserResults', function(data){
if(data == 1){
alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
} else if(data == 0){
alert('User was added to your following list!');
} else if(data == 2){
alert('This user is already on your following list!');
}
});
} else {
return false;
}
Can you please help me with that? Thank you!
I am slightly unclear as to what is trying to be achieved but I've noticed an error in your code straight away.
This code should be outside of the $('.followuser').click function:
socket.on('followUserResults', function(data){
if(data == 1){
alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
} else if(data == 0){
alert('User was added to your following list!');
} else if(data == 2){
alert('This user is already on your following list!');
}
});
So your code should read like:
$('.followUser').click(function(e){
e.stopImmediatePropagation();
e.preventDefault();
var user= $(this).parent().parent().parent().parent().next().children().children('.userName').children().first().children().attr('id');
var thisUserId = $.cookie('thisUserID');
if(user != thisUserId){ //if he tries to follow himself
var object = {
user: user,
userId: thisUserId
}
socket.emit('followUser', object); //server just adds that user to the following list of the first user
} else {
return false;
}
socket.on('followUserResults', function(data){
if(data == 1){
alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
} else if(data == 0){
alert('User was added to your following list!');
} else if(data == 2){
alert('This user is already on your following list!');
}
});
Try put the socket.on(...) outside the click callback function, if still not working properly, I would need watch the server code.

Trying to remember the updated ajax html when user hitting back button?

I am trying to make the browser to remeber the ajax updated html. So when user hit the back button, it will go back to the ajax update html. I had found the following code from stackoverflow, but I had no idea how to use it. I had tried to replace the #Mytable with my class .post-content. But it doesn't work, do I miss something. Help, appreciate.
$('#pagination').click(function(e){
var data = {
action: 'post_pagination_ajax',
AjaxFrontNonce : Child_ajax.ajaxLoadUserNonce,
};
$.ajax({
url: ajax_front_gallery.ajaxurl,
type:'POST',
data: data,
success: function(data){
$('.post-content').fadeOut().html(data).fadeIn();
$fa_spen.fadeOut();
}
});
return false;
});
// the following code found on stackoverflow, but I don't know how to replace it with my code.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}/*remember the previous div position*/
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}

Jquery submit form then redirect not working

I have found so many posts about this but I can't get this to work for the life of me. On submit of the form, I need the code to 1) submit the form and 2) redirect to one of the locations inside the case statements. I can get the form to submit without the cases and I can get the form to redirect, but I can't get it to do both. Please tell me I am on the right track but just have code in the wrong spot, I have been staring at this way too long and have hit a roadblock.
$("#submitBtn").click(function (event) {
event.preventDefault();
var validator = $(this).closest("form").kendoValidator({
messages: {
required: function (input) { return getRequiredValidationMessage(input) },
custom: function (input) { return getInvalidValidationMessage(input) },
},
rules: {
custom: function (input) {
var minlength = $(input).attr('data-minlength');
var required = $(input).attr('required');
if (typeof minlength !== typeof undefined && minlength !== false && ((typeof required !== typeof undefined && required !== false) || $(input).val().length > 0)) {
var minlength = $(input).data('minlength');
return $(input).val().length >= minlength;
} else {
return true;
}
}
}
}).data("kendoValidator");
if (validator !== undefined) {
if (validator.validate()) {
$("aspnetForm").submit();
if ($("aspnetForm").submit()){
switch(document.getElementById('interests').value){
case "stair-lifts":
window.location.href="/Catalog/Online-Catalog-Category/15522/Stair-Lifts";
break;
case "wheelchair-ramps":
window.location.href="/Catalog/Online-Catalog-Category/15521/Ramps";
break;
case "roll-in-barrier-free-showers":
window.location.href="/Catalog/Online-Catalog-Category/15529/Bathroom-Safety";
break;
case "walk-in-tubs":
window.location.href="/Catalog/Online-Catalog-Category/15529/Bathroom-Safety";
break;
case "patient-lifts-ceiling-lifts":
window.location.href="/Catalog/Online-Catalog-Category/15523/Patient-Lift";
break;
case "wheelchair-lifts":
window.location.href="/Catalog/Online-Catalog-Category/15525/Wheelchair--Scooter-Lifts";
break;
default:
window.location.href="/"; // if no selection matches then redirected to home page
break;
}// end of switch
}
} else {
$('.k-invalid:first').focus();
$('.k-invalid').blur(function () { if (this.checkValidity()) { $('.k-invalid:first').focus(); } });
}
} else {
$(this).closest("form").submit();
}
});
});
You shouldn't be using .submit() for this. Since you're using JQuery, you should use an AJAX request, formatted something like this:
$("#submitBtn").click(function (event) {
$.ajax({
url : "/your/url", // Whatever URL you're submitting to goes here
type : "post",
data : yourData, // Whatever data you're sending goes here
success : function(data) {
// Whatever you want to do on success goes here
}
});
});
You make the switch in URL part of the function the AJAX query executes on success.
The form submission and the page redirect are clashing because in a basic web page, only one of these can occur. When the form submits, it will send the form data via the desired method to the server - typically a GET or a POST.
Conversely, when that redirect switch statement runs, it will tell the browser to change the page url.
Both of these events will trigger a page change within the browser, but only one can truly happen.
What would help you the most is to submit the form data via an AJAX request and then on completion call the redirect code.
As it looks like you are already using jQuery, check out the post method here.

is:empty not working for dynamically created content

I have a div listOfTodos that is empty by default. No white space inside the html. I also have a textbox that when enter is pressed it appends text to listOfTodos. For some reason is:empty doesn't work and it always says it's empty.
My code for checking is:
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
Then above this code I also have:
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>'); }
});
The label above is saved and is retrieved on every reload. What's going on?
Doesn't JS run code from top to bottom? I have the keypress above the if statement inside my js file.
Yes, but the event handler is not executed until the event is triggered, which is not possible until after the whole script executed.
I.e.
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
}
});
if (....) { }
will execute the if statement only once after the event handler was bound.
You have to put the if statement inside the handler if you want to run it after the event fired:
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
}
});
Or put it in a function if you want to run that logic in multiple places:
function isEmpty() {
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
}
// run on load
isEmpty();
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
// run on change
isEmpty();
}
});
Use
if ($.trim($('#listOfTodos').text()) == '') {
alert("empty");
} else {
alert("not empty");
}
Fiddle

Jquery comparing strings not working in POST

I have a jquery post code that can have two different reactions based on the response. if the response is a then i would like to alert() if it is not a then i would like to update a div (ratebox). However, one of the lines (below) isn't working. It appends the letter a onto the ratebox when it should bring up the alert. I checked that answerrating.php does produce the letter a.
JQUERY:
$.post('../answerrating.php' , {answer_id: answer_id , direction: 2} , function(response){
if (response == 'a'){ //this line doenst work
alert("error");
}
else {
ratebox.text(response);
}
});
Perhaps you get some whitespaces in the response, try using jQuery.trim():
if ($.trim(response) == 'a'){ //this line doenst work
alert("error");
}
You could also use firebug to check so that your response don't include any html.
If you are getting something other than plain text from the server try setting the dataType in your call:
$.post('../answerrating.php',
{
answer_id: answer_id,
direction: 2
},
function (response) {
//this line doenst work
if (response == 'a') {
alert("error");
} else {
ratebox.text(response);
}
},
dataType: 'text'
);

Categories

Resources