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

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.

Related

Javascript checking country code keeps refreshing constantly

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;
});

Terminating or halting based on value from ajax

I have a php script with a an image that when you click on it you are redirected to another page.
I also have an ajax / jquery check to see if you are logged in or not.
So, when someone clicks on the link, ajax finds out if they are logged in, and if not they get an alert box.
My link has the id='newlisting'
$("#newlisting").click( function() {
$.post("ajaxqueries.php", {"checkloggedin": ''}, function(data) {
var loggedin = data;
if ( loggedin == 0 ) {
alert('Please login or register to use this feature');
}
});
});
The problem is that when they click on on the alert box, it continues to the screen as if you were logged in.
I need the php script to exit if they get the alert box and hit ok.
Any help would be appreciated.
You need to prevent the redirect.
$("#newlisting").click( function( event ) {
event.preventDefault();
$.post("ajaxqueries.php", {"checkloggedin": ''}, function(data) {
var loggedin = data;
if ( loggedin == 0 ) {
alert('Please login or register to use this feature');
}else{
// Redirect code goes here.
}
});
});

Showing error message using jQuery and making it disappear

Below is a simple jQuery code for showing error messages on submission of form, if the given conditions are not fulfilled. This works fine and shows error messages on form submission but I want to change it to keyup function which seems easy, changing $('#submit').click(function() { to $("input").keyup(function(){ works. Now problem is error messages appears on keyup if condition is not fulfilled but does not disappear if condition is fulfilled until I go to next input leaving some error so that inputs error message appears. So what changes I need to make in my code so that error message appearing on keyup disappera as soon as that condition is fulfilled.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var title = document.getElementById('title').value;
var category = document.getElementById('category').value;
if (category == "") {
$('#er').html('Oops! Please select a category from the options.');
return false;
}
else if (title == "") {
$('#er').html('Oops! Title cannot be empty.');
return false;
}
else if (title.length > 100 || title.length < 5) {
$('#er').html('Oops! Make sure title is 5 to 100 characters long.');
return false;
}
});
});
</script>
Try to .empty() the error message initially in the event handler,
$('input').keyup(function() {
var title = document.getElementById('title').value;
var category = document.getElementById('category').value;
var error = $('#er').empty();
if (category == "") {
error.html('Oops! Please select a category from the options.');
return false;
}
else if (title == "") {
error.html('Oops! Title cannot be empty.');
return false;
}
else if (title.length > 100 || title.length < 5) {
error.html('Oops! Make sure title is 5 to 100 characters long.');
return false;
}
});
});

Faking a login w/Javascript

I'm creating a fake login experience in a pre-existing prototype. I think my problem is that there's already a click event on the button that advances it to the next div (it's a single page setup with divs that slide in) and I need to add the below validation functionality to the same button. Here's what I have so far:
$('#login_button').click(function(e){
var username_input = $('input[placeholder*="Hint"]'),
password_input = $('input[placeholder*="Password"]'),
username = $(username_input).val(),
password = $(password_input).val(),
login_errors = 0;
if ((username == '') || (password == '')) {
console.log("Please enter your username and password.");
login_errors = 1;
} else if ((username == 'my_username') && (password == 'my_password')) {
console.log("Username and password are correct.");
} else {
console.log("Your username or password are incorrect. Retry.");
login_errors = 1;
}
if (login_errors != 0){
e.preventDefault();
}
});
I'm getting a little lost there at the end. I can get the button to validate the input and to advance to the next page, but I don't know how to get it to do both of these things at the same time.
Here's my solution:
In my project, I had to refactor to sort out some logic. I made a fiddle that worked right away and helped clarify things for me:
jsfiddle.net/kapunahele/0c9htr4o

Parsley.js Submit form not working when using addAsyncValidator and remote

I have a registration form split into blocks that was working perfectly using this code based on one of the examples from the website:
$('.register-next').on('click', function () {
var current = $(this).data('currentBlock'),
next = $(this).data('nextBlock');
console.log('current block = ' + current);
console.log('next block = ' + next);
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if (next > current)
if (false === $('#form-register').parsley().validate('block' + current))
return;
// validation was ok. We can go on next step.
$('.block' + current)
.removeClass('show')
.addClass('hidden');
$('.block' + next)
.removeClass('hidden')
.addClass('show');
});
I then wanted to add an additional ajax validation to the last block of the code to make sure that the username was not already taken. I have the check working but the problems is that the form will now not submit when the validation checks are passed. Clicking on the submit button just calls the remote function again.
I am assuming that I have to reassign the function of the submit button once all validation checks have been made?
The ID username relates to the input field in the last block of my form.
Thanks
$('#username').parsley().addAsyncValidator(
'validateUsername', function (xhr) {
var UserLogin = $('#username').parsley();
window.ParsleyUI.removeError(UserLogin,'errorUsername');
if(xhr.status == '200'){
console.log("in 200");
return;
}
if(xhr.status == '404'){
response = $.parseJSON(xhr.responseText);
console.log("username exists");
window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
}
}, 'inc/check_username.php'
);
I finally got this working. There is probably a far easier way to do it but this works.
firstly, I made one mistake with my code, I needed to return true if the status was 200
$('#username').parsley().addAsyncValidator(
'validateUsername', function (xhr) {
var UserLogin = $('#username').parsley();
window.ParsleyUI.removeError(UserLogin,'errorUsername');
if(xhr.status == '200'){
return true;
}
if(xhr.status == '404'){
response = $.parseJSON(xhr.responseText);
console.log("username exists");
window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
}
}, 'inc/check_username.php'
);
I then added an additional piece of code to listen for the submit button to be clicked and remove parsley validation from the form before using javascript to submit
$('#new-user-submit').click(function(){
$('#form-register').parsley().asyncValidate()
.done(function(){
$('#form-register').parsley().destroy();
$('#form-register').submit(); });
});
I'm not a big user of javascript so it normally takes me a while to work my way through these things but I thought with parsley being so popular there would be far better support and documentation for it.

Categories

Resources