i am working on chat application and here is my javascript code.
function PushMessage(e , textarea)
{
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13)
{
//Enter keycode
var text1 = document.getElementById('myTextArea').value;
var div = document.getElementById('textmesage');
div.innerHTML = div.innerHTML + '<br>' + text1;
document.getElementById('myTextArea').value = "";
if (text1.length !== 0) {
opner.sendMessage(text1);
event.preventDefault();
} else {
alert('Provide a message to send!');
}
}
}
from this upper code i want to call sendMessage(text1); ajax function from other page i also imbbed path for connection but it is not working, here is my ajax function
sendMessage: function(message)
{
alert('fakhir is jumping');
var that = this;
$.ajax({
url: '/ajax/add_msg.php',
method: 'post',
data: {msg: message},
success: function(data)
{
$('#chatMsg').val('');
that.getMessages();
}
});
}
Related
I have a login page and I have the API for matching the password. If the password doesn't match it will show an error message but my problem is if the password is matching also it showing an error message. because am looping the data so every time it is checking I need to break the loop if it matches how to do. Here is my
code
HTML
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
},
error: function(data) {
console.log(data);
}
});
});
});
I have forked and break your code when the password gets matched. You may test this from here: code
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
var BreakException = {};
try {
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
throw BreakException;
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
} catch (e) {
if (e !== BreakException) throw e;
}
},
error: function(data) {
console.log(data);
}
});
});
});
NOTE: You can break forEach like other loops. To make this thing done you need to add your code in try-catch and throw exception when the password gets matched. That is what I have done in your above code.
Hello everybody. I have a problem with my code. I use the jquery framework. When I want to call $.ajax(requestOptions), function xmlParser(xml) don't working.
I try to find a resolve this problem, but I can't nothing find.
$(document).ready(function () {
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser //Calling function
};
function xmlParser(xml) {
$("#load").fadeOut();
$(xml).find("Valute").each(function() {
$("#outputListValutes").append(
"<option value=" + $(this).find("CharCode").text() + ">" + $(this).find("CharCode").text() + "</option>");
});
};
$.ajax(requestOptions);
$("#clear").click(function() {
var sumValue = document.getElementById("sum").value = "";
var resValue = document.getElementById("result").value = "";
});
$("#convert").click(function(xml) {
//var selectCurrency = $("#inputListCurrency").val();
//findData(xml);
}(requestOptions));
function findData(xml) {
var decimalOnly = /^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/;
try{
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if(value == "") throw new Error("Empty value");
else if(!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if(value < 0) throw new Error("Value isn't to be below zero");
else if(isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function() {
if(shortName == $(this).find("CharCode").text()) {
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch(e) {
alert(e);
}
}
});
change the success parameter of the request to use the xmlParser function (forgot () ):
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser(data) //Calling function
};
I found the solution this promlem. I am happy.
var courseFilePath = "xml/Course_Currency_02-07-2014.xml";
var listCurrency = [];
function insertOptions(){
for (var i = 0; i < listCurrency.length; ++i){
$("#outputListCurrency").append(
"<option value=" + listCurrency[i] + ">" + listCurrency[i] + "</option>");
}
}
function xmlParser(xml){
$("#load").fadeOut();
$(xml).find("Valute").each(function(){
var value = $(this).find("CharCode").text();
listCurrency.push(value);
});
listCurrency.sort();
};
function findData(xml){
var decimalOnly = /^\s*-?[0-9]\d*(\.\d{1,2})?\s*$/;
try {
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if (value == "") throw new Error("Empty value");
else if (!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if (value < 0) throw new Error("Value isn't to be below zero");
else if (isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function(){
if (shortName == $(this).find("CharCode").text()){
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch (e){
alert(e);
}
}
$(document).ready(function(){
$.ajax({
type: "GET", //The method of sending for data
url: courseFilePath, //It is reference on xml file
dataType: "xml", //The type of data
success: function(xml){
xmlParser(xml);
insertOptions();
}
});
//insertOptions();
$("#clear").click(function() {
document.getElementById("sum").value = "";
document.getElementById("result").value = "";
});
$("#convert").click(function() {
var selectCurrency = $("#inputListCurrency").val();
$.get(courseFilePath, findData, "xml");
});
});
I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
var data = 'user='+ fullname;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
}
});
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}
I have on click jquery that submits ajax request.
There are no forms.
I'd like keyboard ENTER to be used also to submit ajax request.
I've allot of these buttons, this confuses me as I cannot simply do:
$('#myForm input:text').keypress(function (e) {
if (e.which == 13) {
$("#button1").click()
}
});
My currect on click event looks like this (how do I extend this to accomodate ENTER?)
//Check answer
$("body").on("click", ".unlocked figcaption .check", function(){
var logo_id = $(this).parent().attr("id");
var answer = $("#" + logo_id + " input[name=guesslogo]");
var logo_lang = answer.attr("data-lang");
answer.removeAttr("class").attr("disabled","true");
//Submit answer for review
$.ajax({
url: "actions.php",
get: "GET",
data: "answer=" + answer.val() + "&logo_id=" + logo_id + "&logo_lang=" + logo_lang,
cache: false,
success: function (data){
var response = jQuery.parseJSON(data);
if (response.result == 1) {
answer.addClass("correct").siblings(".clear, .hint").fadeTo("slow","0.4");
answer.parent().append('<div class="alert"><h3>Correct!</h3> <p>Score: '+ response.score +'</p></div>');
$("#" + logo_id).siblings(".logo").removeClass("logo").addClass("answered").removeAttr("style");
snd_correct.play();
//update user_score and user_level values in leaderboard and header widgets
var this_user = $("header aside").attr("data-usern");
if (this_user) {
var this_user_score = $("header aside .user_score").text();
var this_user_level = $("header aside .user_level").text();
$("[data-usern="+ this_user +"] .user_score").empty().append(parseInt(this_user_score) + parseInt(response.score));
if (response.level_up == 1) {
var new_level = parseInt(this_user_level) +1;
$("[data-usern="+ this_user +"] .user_level").empty().append(new_level);
update_view(new_level);
}
//
update_level_progress_bar();
}
} else if (response.result == 0) {
answer.addClass("wrong").removeAttr("disabled");
snd_wrong.play();
} else if (response.result == 2) {
answer.addClass("almost").removeAttr("disabled");
snd_wrong.play();
}
}
});
return false;
});
I uploaded sample here: http://gamoicani.es/logo/ click on any logo, I'd like to use keyboard ENTER also to submit.
// Try this!! :)
$(document).ready(function(){
$(this).on('keypress click','.unlocked figcaption .check',function(e){
if((e.type === 'keypress' && e.keyCode === 13) || e.type === 'click')
{
// All your code inside the .on()
}
});
});
You can make the ajax function external and then call it on click and keypress (enter) events like this:
$(document).on("click", ".unlocked figcaption .check", ajaxFunction);
$(document).on("keypress", "#myForm input:text", function (e) {
if (e.keyCode == 13){
e.preventDefault();
ajaxFunction();
}
});
function ajaxFunction(){
var logo_id = $(this).parent().attr("id");
var answer = $("#" + logo_id + " input[name=guesslogo]");
var logo_lang = answer.attr("data-lang");
answer.removeAttr("class").attr("disabled","true");
//Submit answer for review
$.ajax({
url: "actions.php",
get: "GET",
data: "answer=" + answer.val() + "&logo_id=" + logo_id + "&logo_lang=" + logo_lang,
cache: false,
success: function (data){
var response = jQuery.parseJSON(data);
if (response.result == 1) {
answer.addClass("correct").siblings(".clear, .hint").fadeTo("slow","0.4");
answer.parent().append('<div class="alert"><h3>Correct!</h3> <p>Score: '+ response.score +'</p></div>');
$("#" + logo_id).siblings(".logo").removeClass("logo").addClass("answered").removeAttr("style");
snd_correct.play();
//update user_score and user_level values in leaderboard and header widgets
var this_user = $("header aside").attr("data-usern");
if (this_user) {
var this_user_score = $("header aside .user_score").text();
var this_user_level = $("header aside .user_level").text();
$("[data-usern="+ this_user +"] .user_score").empty().append(parseInt(this_user_score) + parseInt(response.score));
if (response.level_up == 1) {
var new_level = parseInt(this_user_level) +1;
$("[data-usern="+ this_user +"] .user_level").empty().append(new_level);
update_view(new_level);
}
//
update_level_progress_bar();
}
} else if (response.result == 0) {
answer.addClass("wrong").removeAttr("disabled");
snd_wrong.play();
} else if (response.result == 2) {
answer.addClass("almost").removeAttr("disabled");
snd_wrong.play();
}
}
});
return false;
};
jsfiddle
like this jquery code, how should i delay the ajax request? input is a text field...over my head ....thx for help...
var proname = "" ;
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}) ;
You want to use setTimeout.
From your usage, it seems to be a good idea to have a timeout that is being cleared every time another keyup event occurs, to avoid a queue.
var requestDelay;
var proname;
$('input[name=proname]').keyup(function() {
if(e.which == 13 || $(this).val() == proname)
return;
proname = $(this).val();
// postpone the submit another 300 ms upon every new character
window.clearTimeout(requestDelay);
requestDelay = window.setTimeout(function() {
$.ajax(...);
}, 300);
});
I see you are doing some kind of autosearch/autocomplete feature.
Have you considered just using the jQuery UI Autocomplete? http://jqueryui.com/demos/autocomplete/#remote-jsonp
As for the question itself you have already been answered.
Use setTimeout.
var proname = "" ;
$("input[name='proname']").keyup(function(e){
if (e.which == 13) return;
setTimeout(function() {
if ($(this).val() != proname) {
proname = $(this).val();
} else {
return;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
});
}, DELAY_IN_MSECS);
});
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
setTimeout(function() {
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}, 1000);
}) ;