How to get current object you working with - javascript

I need to process an AJAX request twice, first, when the site has been opened first time, and second, when a button is clicked. I dont want to write 2 similar functions. So I created an ajaxPost function. I wonder how to detect what event has called the ajaxPost function? opening the browser or clicking a button?
function ajaxPost() {
url = "post.php";
if (this!=Window) {
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});

Check for the jQuery event that you're passing with a click.
function ajaxPost(event) {
url = "post.php";
if (event == undefined || event == null) { //Was not generated by a user click
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});

A simple solution would be to include an additional parameter when calling the function:
function ajaxPost( caller ) {
switch( caller ){
case "initial_load":
// called on page load
break;
case "button_click":
// called on button click
break;
}
...
}
Now you would need to pass this parameter from the two different types of calls:
$(document).ready(function() {
ajaxPost( "initial_load" );
$("input[type=button]").on( "click", function(){
ajaxPost( "button_click" );
});
});

Related

Alternative to AJAX async: false option for form submit button click event handler

I have a login form where we make an AJAX call to the server to perform a bit of validation before letting the login form continue submitting. The current code is outlined below:
(function ($) {
var errorMessageHtml = "";
function isUserValid(username) {
if (username.length <= 0) {
return false;
}
var userIsValid = false;
$.ajax({
async: false,
url: "/myAjaxCall?username=" + username
}).success(function (validationResult) {
userIsValid = validationResult.IsValid;
errorMessageHtml = validationResult.ErrorMessage;
}).fail(function () {
errorMessageHtml = "Error contacting server. Please try again.";
});
return userIsValid;
}
var $usernameTextbox = $("#UserName");
var $errorMessageLabel = $(".errorMessageContainer");
$(".loginButton").on("click", function (e) {
$errorMessageLabel.hide();
if (isUserValid($usernameTextbox.val())) {
return true;
} else {
$errorMessageLabel.show();
$errorMessageLabel.html(errorMessageHtml);
}
e.preventDefault();
return false;
});
})(jQuery);
I know that async: false is something that shouldn't be used since it's going out of style. My question is: What's the alternative. My click event handler needs to return true or false, meaning it has to wait for the ajax call to complete. If async: false is no longer an option, then the isUserValid method is going to return immediately without properly setting the userIsValid bool.
Now I can inline the ajax method call straight into the click event handler that's called on $(".loginButton"), but the same problem presents itself: It needs to either return true, or prevent default (i.e. prevent login) and return false depending on the result of the ajax call. Is there a way I can force the click event handler to wait for the result of the ajax call before returning, without using async: false? I understand there's a jQuery when() method, but I don't know if I can use that in this situation.
First thing, a form can be submited without clicking on respective submit button. So bind instead submit event to the form. Now depending ajax request result, you can submit the form, using e.g:
(function ($) {
var errorMessageHtml = "";
function isUserValid(username) {
$errorMessageLabel.hide();
if (username.length <= 0) {
return false;
}
var userIsValid = false;
// return the promise from ajax method
return $.ajax({
url: "/myAjaxCall?username=" + username
}).success(function (validationResult) {
userIsValid = validationResult.IsValid;
errorMessageHtml = validationResult.ErrorMessage;
}).fail(function () {
errorMessageHtml = "Error contacting server. Please try again.";
});
}
var $usernameTextbox = $("#UserName");
var $errorMessageLabel = $(".errorMessageContainer");
// "form:has(.loginButton)" or whatever more relevant selector
$("form:has(.loginButton)").on("submit", function (e) {
$errorMessageLabel.hide();
isUserValid($usernameTextbox.val())).always(function(validationResult ){
if(validationResult && validationResult.IsValid) {
this.submit();
} else {
$errorMessageLabel.html(errorMessageHtml).show();
}
}.bind(this));
e.preventDefault();
});
})(jQuery);
A. Wolff's answer is the answer I accepted, but I wanted to share my final code solution based off their input as well as the various comments made back and forth.
(function ($) {
"use strict";
var $usernameTextbox = $("#UserName");
var $passwordTextbox = $("#Password");
var $errorMessageLabel = $(".errorMessageContainer");
$("form").on("submit", function (e) {
$errorMessageLabel.hide();
var username = $usernameTextbox.val();
if (username.length <= 0 || $passwordTextbox.val().length <= 0) {
return; // Server posts back with "username/password required" so we don't handle it here.
}
$.get("/myAjaxCall?username=" + username).done(function (validationResult) {
if (validationResult.IsValid) {
this.submit();
} else {
$errorMessageLabel.html(validationResult.ErrorMessage).show();
}
}.bind(this)).fail(function() {
$errorMessageLabel.html("Error contacting server. Please try again.").show();
});
e.preventDefault();
});
})(jQuery);

jQuery toggle triggers effect instead of handler [duplicate]

$('.slideArrow').toggle(function (event) {
//some code
}, function (event) {
//some code
});
This works fine for content which are loaded on page-load.But the same function does not work for content loaded with ajax.It just does not intercept the click.
What should I do?
In an other scenario,i faced a same problem(not for toggle,for click) and sorted it this way.I dont know what to do for toggle?
$('.common-parent').on('click','.target-of-click',function(){
//some code
})
The flag method :
var flag = false;
$(document).on('click', '.slideArrow', function(event) {
if (flag) {
// do one thing
}else{
// do another thing
}
flag = !flag;
});
the data method
$(document).on('click', '.slideArrow', function(event) {
if ( $(this).data('flag') ) {
// do one thing
}else{
// do another thing
}
$(this).data('flag', !$(this).data('flag'));
});

Javascript onbeforeunload to open window.open() popup

I am trying to write a onbeforeunload event that triggers a window.open(url) etc. I want it to be triggered if the user trys to leave the page or if they close their browser, but not when they click any of the buttons on the page. The buttons on the page post data to the same page via a javascript.
javascript:
window.onbeforeunload = doSync;
function doSync(){
if(doSync == true){
//do sync via popup
window.open("http://mydomain.com/page.php?var=<?php=sync_var?>", "Synchronizing cluster....", "location=0,menubar=0,statusbar=1,width=10,height=10");
}
else {
//somehow do nothing and allow user to leave
}
}
-->
</script>
The buttons calls a javascript function that creates a form and submits it. In that javascript function I set the global variable of doSync = false. I'll include the basic code of this function just to illustrate it.
function buttonPush(){
var form = document.createElement('form');
form.setAttribute('method' bla bla
//before submit set dosync to false
doSync = false;
form.submit();
}
right now I am getting a Not Implemented error on the window.onbeforeunload = doSync; statement.
Any help would be appreciated.
Thanks,
Jim
Is there something wrong with my window.open? if i do a window.open('','','height=100,width=100');
it opens fine but this below does not.
window.open('https://mydomain.com/support/sync_cluster.php?sync_cluster=mycluster','Synchronizing...', 'toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=0,width=100,height=100');
doSync is a function, not a boolean; just create a variable and set it appropriately:
var sync = true;
window.onbeforeunload = doSync;
function doSync() {
if (sync == true) {
//do sync via popup
window.open("http://mydomain.com/page.php?var=<?php=sync_var?>", "Synchronizing cluster....", "location=0,menubar=0,statusbar=1,width=10,height=10");
}
else {
//somehow do nothing and allow user to leave
return;
}
}
function buttonPush(){
var form = document.createElement('form');
// form.setAttribute('method' bla bla
//before submit set dosync to false
sync = false;
form.submit();
}
Try this:
var vals = 0;
function displayMsg() {
window.onbeforeunload = null;
window.location = "https://www.google.com";
}
window.onbeforeunload = function evens(evt) {
var message = 'Please Stay on this page and we will show you a secret text.';
if (typeof evt == 'undefined') {
evt = window.event;
}
timedCount();
vals++;
if (evt) {
evt.returnValue = message;
return message;
}
trace(evt);
}
function timedCount() {
t = setTimeout("timedCount()", 500);
if (vals > 0) {
displayMsg();
clearTimeout(t);
}
}
$(document).ready(function() {
$('a,input,button').attr('onClick', 'window.onbeforeunload = null;')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Leave

Adding a third step to my Wizard-step Jquery code

I am using Wizard-Step in my MVC3 project, it is two steps right now but I want to add a third step into to it.
However, I still want to submit my form in the second step.
This is how my Wizard-step Jquery code looks like:
$(function () {
$(".wizard-step:first").fadeIn(); // show first step
// attach backStep button handler
// hide on first step
$("#back-step").hide().click(function () {
var $step = $(".wizard-step:visible"); // get current step
if ($step.prev().hasClass("wizard-step")) { // is there any previous step?
$step.hide().prev().fadeIn(4500); // show it and hide current step
// disable backstep button?
if (!$step.prev().prev().hasClass("wizard-step")) {
$("#back-step").hide();
}
}
});
// attach nextStep button handler
$("#next-step").click(function () {
var $step = $(".wizard-step:visible"); // get current step
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find("select").each(function () {
if (!this.disabled && !validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
if ($step.next().hasClass("confirm")) { // is it confirmation?
// show confirmation asynchronously
$.post("/wizard/confirm", $("form").serialize(), function (r) {
// inject response in confirmation step
$(".wizard-step.confirm").html(r);
});
}
if ($step.next().hasClass("wizard-step")) { // is there any next step?
$step.hide().next().fadeIn(4500); // show it and hide current step
$("#back-step").show(); // recall to show backStep button
}
else { // this is last step, submit form
$("form").submit();
}
return false;
}
});
});
Any solutions is highly appreciated.
use an indexer variable then submit your form at step 2 and post the result in third step
for example... i'm posting some of my projects code here for reference...
if (indexer < 2 && $step.next().hasClass("wizard-step")) {
$step.hide().next().fadeIn();
indexer++;
ShowStep();
}
else {
$.post(paths + "/Auction/Post", $('form').serialize(), function (data) {
alert(data);
})
.complete(function () {
});
}

Is it possible to bind to the Click event and not use an anonymous function -- I just want to call a named function

I have the following code. The first attempt at binding to click event does not work. The second way does. The first shows the alert "CheckBox1" during Page_Load. The second one shows the alert "CheckBox4" during the proper time -- during clicks.
$(document).ready(function () {
$(document.getElementById(checkBox1ID)).click( SetCheckBox1State(this.checked) );
$(document.getElementById(checkBox4ID)).click(function () { SetCheckBox4State(this.checked) });
});
function SetCheckBox1State(checked) {
alert("CheckBox2");
var radNumericTextBox1 = $find(radNumericTextBox1ID);
var wrapperElement = $get(radNumericTextBox1._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox1.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox1.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
function SetCheckBox4State(checked) {
alert("CheckBox4");
var radNumericTextBox2 = $find(radNumericTextBox2ID);
var wrapperElement = $get(radNumericTextBox2._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox2.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox2.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
Am I doing something improper? I'd rather not use an anonymous function...but maybe this just how things work?
This code:
.click( SetCheckBox1State(this.checked) );
Assigns the .click() function to be the output of this function: SetCheckBox1State(this.checked).
You will have to get rid of the argument (make it internal) and just pass the function name:
.click( SetCheckBox1State );

Categories