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
Related
I have code for adding products into favorites using JQuery and AJAX, my JavaScript code looks like:
$('.product-item-btn-fav').on('click', function(e){
b = $(this).data("product_number");
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
$(this).addClass("active");
} else {
if (d == -1) {
$(this).removeClass("active");
}
}
}
})
});
And HTML:
<a class="product-item-btn-fav" data-product_number="[%item.product_number%]">
<svg class="svg-icon-heart-filled">
<use xlink:href="[%domain.url_media%]/images/svg-sprite.svg#svg-icon-heart-filled"></use>
</svg>
</a>
This code works, it adds product into favorite list at backend side (so AJAX works and it returns valid result 1 or -1), but this call $(this).addClass("active"); doesn't add css class to <a> tag.
You have to store $(this) in variable for a
$('.product-item-btn-fav').on('click', function(e){
b = $(this).data("product_number");
var _t = $(this);
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
_t.addClass("active");
} else {
if (d == -1) {
_t.removeClass("active");
}
}
}
})
});
this does not point the element you are thinking, store this in a variable and use that inside the ajax callback function:
$('.product-item-btn-fav').on('click', function(e){
var b = $(this).data("product_number");
var prod = $(this);
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
prod.addClass("active");
} else {
if (d == -1) {
prod .removeClass("active");
}
}
}
});
});
That is because context to anchor element is lost in ajax callback function. You can set the context using context option in ajax. See Ajax Docs:
$.ajax({
type: "POST",
context : this,
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
$(this).addClass("active");
} else {
if (d == -1) {
$(this).removeClass("active");
}
}
}
})
$.ajax({
type: "POST",
context : this,
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
}
})
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();
}
});
}
I currently have an .on(click) where an ajax call happens now the problem is I want everything in the .on(click) to happen also when the pages loads.
My plan is to create a function and put everything that happens in the .on(click) in this function. And when the pages loads I want this function to trigger too.
Here's what I've tried but doesn't seem to be working.
my .on(click):
$('.changetypevastgoed').on('click', function(e){
var termid = $(this).data('termid');
$('#slctypevastgoed').val(termid);
$('#vastgoedtypes').find('.active').removeClass('active');
$(this).addClass('active');
e.preventDefault();
$.ajax({
type: 'POST',
dataType: "json",
data: "termid=" + termid,
url: $('body').data('theme-url') + '/lib/getsearchoptions.php',
success: function(result) {
var juistekeyslanden=[];
$.each(result.landen, function(key1, value1) {
$.each(value1, function(key2, value2) {
if (key2 == termid){
juistekeyslanden.push(key1);
}
});
});
$('select#land').find('option').each(function() {
$(this).attr("disabled", true);
var currentoption = $(this).attr("data-id");
if ($.inArray(currentoption, juistekeyslanden) != -1){
$(this).attr("disabled", false);
}
}).after(function( x ) {
$('.chosen').trigger('chosen:updated');
});
var juistekeysoppervlakten=[];
$.each(result.oppervlakten, function(key1, value1) {
$.each(value1, function(key2, value2) {
if (key2 == termid){
juistekeysoppervlakten.push(key1);
}
});
});
$('select#oppervlakte').find('option').each(function() {
$(this).attr("disabled", true);
var currentoption = $(this).attr("data-id");
if ($.inArray(currentoption, juistekeysoppervlakten) != -1){
$(this).attr("disabled", false);
}
}).after(function( x ) {
$('.chosen').trigger('chosen:updated');
});
var juistekeyspostocodes=[];
$.each(result.postcodes, function(key1, value1) {
$.each(value1, function(key2, value2) {
if (key2 == termid){
juistekeyspostocodes.push(key1);
}
});
});
$('select#postcode').find('option').each(function() {
$(this).attr("disabled", true);
var currentoption = $(this).attr("data-id");
if ($.inArray(currentoption, juistekeyspostocodes) != -1){
$(this).attr("disabled", false);
}
}).after(function( x ) {
$('.chosen').trigger('chosen:updated');
});
}
});//success
});
So I've tried putting my AJAX call in a function like so:
$.fn.myfunction = function () {
$.ajax({
...
};
I set this right under my
jQuery(document).ready(function( $ ) {
And in my on.click I do this:
$('.changetypevastgoed').myFunction();
On this line I get this error
$(...).myFunction is not a function
$(document).ready(function(){
$(".changetypevastgoed").trigger("click");
});
have u tried something like this ?
in my jquery function i have two ajax call with serverside method and its working fine,
problem is ajax call at last amd after ajax line of code run but this lines of code depand on
function Rbook(b) {
var one = $(b).attr("data-oneislcc");
var two = $(b).attr("data-twoislcc");
var trip1 = $(b).attr("data-oneinfo");
var trip2 = $(b).attr("data-twoinfo");
var owflt = "l";
var inflt = 'r';
var owjdata = $(b).attr("data-ow");
var iwjdata = $(b).attr("data-iw");
var llccreturn, rlccreturn;
var lres, rres;
$("#fadeing").css("display", "block");
$("#fade").css("display", "block").css("height", $(document).height / 2);
if (one == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip1 + "','flt':'" + owflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
lres = response.d;
if (response.d == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
llccreturn = owlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
llccreturn = ownonlcc(owjdata);
}
if (two == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
if (rres == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
rlccreturn = iwlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
rlccreturn = iwnonlcc(iwjdata);
}
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}}
var owlcc = function (jdata, oldfare) {
//Some Calulation
retrun 'farechange';
}
var ownonlcc = function (jdata) { //Some Calulation
retrun 'nofarechange'}
var iwlcc = function (jdata, oldfare) { //Some Calulation
return 'farechange'}
var iwnonlcc = function (jdata) { retrun 'nofarechange'}
if run this code its run this line of code then rest so condition not validate
i dont know where i m doing wrong
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
It looks like you don't understand asynchronous javascript. When you do an ajax call, it sends the request, then continues running the code and only later runs the success handler. Otherwise, it wouldn't be able to do anything at all until the response came back, since javascript is single-threaded.
The Rbook function does the following: First, get lots of information from the DOM; then, send some ajax requests (and set handlers to run when the response comes back); then possibly make some changes to the DOM, depending on the values of llccreturn and rlccreturn (but they're still undefined). It's only when the ajax response comes back and the success handler is run that these variables are set, but by then it's too late.
If you want to run some code after hearing the ajax response, put it in the success handler (or call it from the success handler). In this case, it's further complicated by the fact that you don't want to run the code until both ajax responses have arrived, and also by the fact that you might just run iwnonlcc or ownonlcc synchronously instead of doing an ajax call. I'd say the easiest way to fix this would be to wrap the code you want to run at the end inside a function and an if block like this:
function dataWasReceived() {
if (llccreturn !== undefined && rlccreturn !== undefined) {
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
}
}
Then, every time you set the value of llccreturn or rlccreturn, call this function:
rlccreturn = iwlcc(data[0], data[1])
dataWasReceived();
and:
rlccreturn = iwnonlcc(iwjdata);
dataWasReceived();
etc.
I'm also concerned about this line (appears twice):
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
You probably wanted to apply the argument as an object, not a JSON string representing that object:
data: {ALcode: trip2, flt: inflt},
(Incidentally, the string you gave wasn't valid JSON anyway, since it used ' instead of ".)
var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
I know I need to attach the .live() event handler to prevent the function from triggering other events (what's currently happening), but where do I add it?
Full Script:
$(document).ready(function() {
$("input#name").select().focus();
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
$("input#name").swearFilter({words:'bob, dan', mask:"!", sensor:"normal"});
var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)");
jQuery.validator.addMethod("tagcheck", function(value, element) {
return tagCheckRE.test(value);
}, "");
$("#addname").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#naughty').fadeIn('fast');
$('#naughty').delay('1000').fadeOut('fast');
} else {
$('#naughty').hide();
}
}
});
$('#showall').live('click', function() {
$('#showall').hide();
$('div#shownames').slideDown('fast');
});
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
var names = '';
var dot = '.';
$('#addname').ajaxForm(function() {
var options = {
success: function(html) {
/* $("#showdata").replaceWith($('#showdata', $(html))) */
var value = $("input#name").val().toUpperCase();;
$("span.success").text(value);
if (names == '') {
names = value;
}
else {
names = ' ' + value + ', ' + names;
$("span#dot").text(dot);
}
$("span#name1").text(names);
$('#working').fadeOut('fast');
$('#success').fadeIn('fast');
$('#added-names').fadeIn('fast');
$('#success').delay('600').fadeOut('fast');
$("input#name").delay('1200').select().focus();
$('#event-box').delay('600').fadeTo('fast', 1.0);
$(':input','#addname')
.not(':button, :submit, :reset, :hidden')
.val('')
},
cache: true,
error: function(x, t, m) {
if(t==="timeout") {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
} else {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
alert(t);
}
}
}
$(this).ajaxSubmit(options);
$('body').select().focus();
});
$("input").bind("keydown", function(event) {
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) {
document.getElementById('#submit').click();
return false;
} else {
return true;
}
});
});
The ajaxForm function is being triggered using my current implementation.
The fault:
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
As .ajaxStart() is a global parameter, it was being triggered during every AJAX call, including .load(), I'm surprised no one spotted it.