I am building a chat app and I want to ask users to input their username. JQuery front-end code slides a form into view (on ready), stores the data into variables and then loads the chat (when enter key or button is pressed). How do I stop that animation until I validate user input on server-side? I am using node.js for backend. Any ideas?
Thanks in advance!
Front-end jQuery:
var nameChoice, roomChoice; //to store user input
var initName = function() {
nameChoice = $("#init-name input").val(); //save chosen name in nameChoice
$("#current-name").text("Username: " + nameChoice); //put chosen name in chat header
$("#init-name").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#init-room").removeClass("hidden");
$("#init-room").animate({"left" : "35%"}, 300);
}); //remove name form and slide in room form in callback
} //end initName
var initRoom = function() {
roomChoice = $("#init-room select").val(); //save chosen room in roomChoice
$("#current-room").text("Room: " + roomChoice); //put chosen room in chat header
$("#init-room").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#chat-main").removeClass("hidden");
}); //remove room form and show page in callback
} //end initRoom
var btnHover = function() {
$(".btn-form").hover(
function() {
$(this).stop().animate(
{
backgroundColor : "#FFBD7A"
}, 300);
},
function() {
$(this).stop().animate(
{
backgroundColor : "white"
}, 300);
});
}
var init = function() {
$("#init-name").removeClass("hidden").animate({"left" : "35%"}, 300); //slide in name form
$(document).keydown(function(event) { //submit choice on enter key
if (event.which === 13) {
if (!$("#init-name").hasClass("hidden")) { //if user is choosing name
event.preventDefault();
initName(); //call initName function
}
if (!$("#init-room").hasClass("hidden")) { //if user is choosing room
event.preventDefault();
initRoom(); //call initRoom function
}
}
}); //end enter key submission
$("#init-name .btn-form").click(initName);
$("#init-room .btn-form").click(initRoom);
btnHover();
} //end init
$(document).ready(init);
I'm still learning node, so no back-end code yet...
rough code for this ...
$http.post("/login", {"username":username, "password": password}).then(function(response) {
console.log("success - do animation here");
}.catch(function(response) {
console.log("failure a non 2xx HTTP response - handle error here");
});
This code is crude since the http request should prob be in a service, also I have not linted this code, BUT you should get the general IDEA!
APOLOGIES THIS IS ANGULAR, JQUERY WAS ASKED FOR ... HERE GOES ...
$.ajax({
method: "POST",
url: "/login",
data: { username: username, password: password }
})
.then(
function( data, textStatus, jqXHR ) {
console.log("success - do animation here");
},
function( jqXHR, textStatus, errorThrown ) {
console.log("failure a non 2xx HTTP response - handle error here");
}
);
Never tried this in Jquery before but the docs suggest this approach.
Check the docs at ...
http://api.jquery.com/jquery.ajax/
Thanks
Edit: in case promise based jQuery code not available:
$.ajax({
method: "POST",
url: "/login",
data: { username: username, password: password }
})
// for older versions of jQuery, replace .done and .fail with .success and .error
.done(function( data, textStatus, jqXHR ) {
console.log("success - do animation here");
})
.fail(function( jqXHR, textStatus, errorThrown ) {
console.log("failure a non 2xx HTTP response - handle error here");
});
Related
I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
I am implementing a video conference room and I have a variable (room_status) which holds the status of the room (0 = close & 1 = open). Now this variable is only accessible my the client who clicks open-room.
I need to save the room_status variable to the server so that it can be accessed on other client's side. Here is a piece of my code:
var room_status = 0; //room closed
$('#open-room').click(function () {
// http://www.rtcmulticonnection.org/docs/open/
$.ajax({
type: 'GET',
url: "../invite",
data: {
videoconference_id: $('#meetingID').val(),
invitee_id: 1111,
status: "Accepted"
},
success: function() {
alert("success!");
},
error: function() {
alert("fail");
}
});
//room_status = 1; //room opened
rmc.open();
rmc.streams.mute({video : true});
document.getElementById("on-off-video").style.color= 'red';
});
$('#join-room').click(function () {
if(room_status) {
// http://www.rtcmulticonnection.org/docs/connect/
rmc.connect();
rmc.streams.mute({video: true});
document.getElementById("on-off-video").style.color= 'red';
} else {
console.log("Waiting for meeting organizer");
}
});
Ajax is your friend.
Here is an example from a prject of mine with jquery ui :
function prepare_ajax_button(l){
$("#button").button().click(function(event,ui){
$.ajax({type: "GET",data: {"arg1":l},url: "update_variable.php",success: function(data){
alert("Success ?!");
},error: function(data){alert("Problem ?!");}});
});
}
The page "update_variable.php" can for instance write the variable in a text file, mysql...
I am using the Mailchimp API to submit a form. The goal is to prevent the default callback provided by Mailchimp. The majority of the time event.preventDefault() is behaving as it should. Then randomly it will not work:
$(function () {
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
if(event) event.preventDefault();
register($form);
});
});
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
var message = data.msg
var messageSh = data.msg.substring(4);
if (data.msg == '0 - Please enter a value' || data.msg == '0 - An email address must contain a single #') {
$('#notification_container').html('<span class="alert">'+messageSh+'</span>');
} else {
$('#notification_container').html('<span class="alert">'+message+'</span>');
}
} else {
// It worked, carry on...
var message = data.msg;
$('.popup-promo-container').addClass('thanks');
$('.checkboxes, #mc_embed_signup_scroll').addClass('hidden');
$('.complete-promo').html(message).removeClass('hidden');
setTimeout(function() {
document.querySelector('.popup-promo').style.display = "none";
},20000);
}
}
});
}
Try
take off ready function.
remove if on event
Code:
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
event.preventDefault();
register($form);
});
I'm having some trouble accessing the model correctly in a controller for a separate route.
Currently I have this going on...
App.CheckoutRoute = Ember.Route.extend({
model: function(){
return this.modelFor('product');
}
});
And that's working in my template and it seems in the other properties on the controller
App.CheckoutController = Ember.ObjectController.extend({
publishable: 'pk_test_AtBneKs2kGmWkyD60ymyh5fw',
number: '',
cvc: '',
expMonth: '',
expYear: '',
errors: '',
charge: function() {
var p = this.get('model.price');
return p + '00';
}.property('model.price'),
actions: {
tokenize: function() {
//disable the submit button to prevent repeated clicks
$('button[type=submit]').attr("disabled", "disabled");
//Set Stripe Publishable Key
Stripe.setPublishableKey(this.get('publishable'));
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: this.get('number'),
cvc: this.get('cvc'),
exp_month: this.get('expMonth'),
exp_year: this.get('expYear')
}, this.didCreateToken.bind(this));
return false;
}
},
didCreateToken: function(status, response) {
// console.log(status);
// console.log(response);
if(response.error) {
$('button[type=submit]').removeAttr('disabled');
return this.set('errors', response.error.message);
}else{
var form = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// post via ajax
$.ajax({
url: 'stripe/submit.php',
type: 'post',
data: $('#payment-form').serialize()
})
.done(function(data, status, xhr) {
console.log(data);
console.log(status);
console.log(xhr);
})
.fail(function(data, status, xhr){
console.log(data);
console.log(status);
console.log(xhr);
});
}
}
});
The problem comes to when I am trying to access the model to update it's quantity property to persist back to my parse server.
I want to do that in the done statement of the didCreateToken function but trying to get the model like normal I get an error in the console saying that it has no method get. How can I gain access to the model to be able to update and .save() the quantity property after the payment in stripe has gone though.
Also everything as far as stripe goes works just fine, I can successfully make payments and get to that done statement.
you're just out of scope, set a reference to this or the model and use it inside the done.
didCreateToken: function(status, response) {
var self = this;
// console.log(status);
// console.log(response);
if(response.error) {
$('button[type=submit]').removeAttr('disabled');
return this.set('errors', response.error.message);
}else{
var form = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// post via ajax
$.ajax({
url: 'stripe/submit.php',
type: 'post',
data: $('#payment-form').serialize()
})
.done(function(data, status, xhr) {
var model = self.get('model');
console.log(data);
console.log(status);
console.log(xhr);
})
.fail(function(data, status, xhr){
console.log(data);
console.log(status);
console.log(xhr);
});
}
}
This is a very small application for a prototype/experiment. A device is going into sleep every so often to save battery life and a user will access a local webpage and press a button to change something with the device--this sends a POST to the device using the javascript code below.
Since the device can be sleeping when the user presses a button it will miss the POST. I know this is bad practice but I basically need the webpage to keep POST-ing (don't even know if I'm using the terminology correctly) or sending data until it receives the response. I tried a while loop but it only sent it once, maybe I put it in the wrong place.
function execPOST(url, postData, callback) {
var postRequest = newAjaxRequest();
postRequest.onreadystatechange = function() {
if (postRequest.readyState == 4) {
if (postRequest.error) {
callback(1, "Request had an error.");
alert('postRequest Error');
} else {
var status;
try {
status = postRequest.status;
} catch (err) {
callback(1, "Failed to get HTTP status from server.");
return;
}
if (status == 200 || status == 0) {
callback(0, postRequest.responseText);
} else {
callback(1, "POST: Unexpected HTTP Status: "
+ postRequest.status);
alert('POST: Unexpected HTTP Status: '
+ postRequest.status);
}
}
}
}
if (postRequest.overrideMimeType){
postRequest.overrideMimeType("text/xml");
}
postRequest.open("POST", url, false);
//I tried adding this while loop hoping it would keep sending but it only sent once
while (postRequest.readystate != 4)
{
setTimeout('',2000);
postRequest.send(postData);
}
return postRequest;
}
I suggest looking at socket.io to "ping" the device in a loop until it wakes up, THEN send the POST request.
have you considered to use jquery?
function ping () {
$.ajax (
<url>
, {
error: function ( jqXHR, textStatus, errorThrown ) {
}
, timeout: 5000 // in ms
, type: 'POST'
}
}).done(function ( data, textStatus, jqxhr ) {
// whatever
}).fail(function ( jqxhr, textStatus, data ) {
// note that the order of arguments is different from that of the success handler ('done') !
if (textStatus === 'timeout') {
ping();
}
else {
// ... more error handling
}
});
for more info, consult the docs.