jQuery modal dialog and ASP.NET postback - javascript

I have a modal dialog on my page using jQuery that a user enters a password into.
It's a standard jQuery dialog and it works fine. I have linkbuttons in a datagrid that open the dialog using this code:
$('.needsVal').click(function () {
$("#login1").dialog('open');
id = $(this).attr('id');
return false;
});
The problem is later on in the page I make an Ajax call, and based on the value returned, I want to selectively fire a postback for the page. The problem is the postback never fires. My postback code is as follows:
if (returnValue == "true") {
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(id, "", false, "", "", false, true));
return true;
}
else {
alert("Authentication failure!\nPlease check your password and try again.");
return false;
For some reason I can't get the postback to work with the modal dialog, and it's driving me nuts. I had this working with a regular Javascript prompt, but I had to change it because there's no way to mask the password in a prompt.
Any thoughts on how to get the postback to work?
id is a global variable that has the unique ID of the clicked button. I've confirmed that's being passed properly.

I managed to get this to work.
What I found was there are two ASP.NET controls on the page - two gridviews, one with regular linkbuttons and another with a linkColumn.
Because of the way the linkbuttons work in the two types of controls (linkbutton vs. commandbutton) I had to vary how I open the form, and how I interact with the prompt. I had to create two different events. (Maybe there's a way to do it with one, but I couldn't figure it out)
What I finally wound up with jQuery wise:
//Click event for gridview 1 (standard linkbutton)
$('.needsVal').click(function () {
$("#login1").dialog('open');
id = $(this).attr('id');
return false;
});
//Click event for second gridview (command button)
$('.needsValSideMenu').click(function () {
var h = $(this).html();
script = h.substring(h.indexOf("\"") + 1, h.indexOf("\">"));
$("#login2").dialog('open');
return false;
});
//AJAX call for standard linkbutton grid
function checkPassword() {
var returnValue;
$.ajax({
async: false,
type: "POST",
url: "myservice.asmx/Authenticate",
data: { "password": pw.value },
dataType: "xml",
error: function () { alert("Unexpected Error!"); },
success: function (msg) {
returnValue = $(msg).find('boolean').text()
}
});
if (returnValue == "true") {
//alert(id.replace("_", "$"));
id = id.split("_").join("$");
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(id.replace("_","$"), "", true, "", "", false, true));
}
else {
alert("Authentication failure!\nPlease check your password and try again.");
}
}
//Call for second grid (command button) - need to get and execute the script associated with this button
function checkPasswordSideMenu() {
var returnValue;
$.ajax({
async: false,
type: "POST",
url: "myservice.asmx/Authenticate",
data: { "password": pw2.value },
dataType: "xml",
error: function () { alert("Unexpected Error!"); },
success: function (msg) {
returnValue = $(msg).find('boolean').text()
}
});
if (returnValue == "true") {
eval(script);
}
else {
alert("Authentication failure!\nPlease check your password and try again.");
}
}
I couldn't think of a way to do this in one method since I need to call a different checkPassword routine depending on which type of button was clicked.

Related

preventDefault of a link depending on the Ajax response

I've created a controller in Magento which check whether or not there are products in a list. If there are products in list it will return true otherwise false.
Here is the front-end which triggers the ajax call, bare in mind I can not change this to be a form. It has to be a link.
Compare Products
Here is the ajax call.
jQuery(".compare-product-link").on("click", function(e) {
jQuery.ajax({
async : false,
dataType : "json",
url : "/compareextra/compare/allowed",
success : function(data) {
//console.log(data);
if(data.isAllowed != true) {
e.preventDefault();
}
}
});
});
The problem I have is that the async is deprecated and is not good for user experience, saying that there are many answer out there which add a delay of 3 seconds, I also don't want that because thats not good for user experience.
I've also tried using a promise call but it only works with async : false.
jQuery(".compare-product-link").on("click", function(e) {
var response = false;
jQuery.ajax({
dataType : "json",
url : "/compareextra/compare/allowed",
success : function(data) {
console.log(data);
if(data.isAllowed) {
response = true;
}
}
}).done(function (){
console.log(response);
if(response != true) {
e.preventDefault();
}
});
});
EDIT
Another problem I also have is if I store the link into a variable and then open a new window as so window.location = href; most browser will block it and users will have to manually accept pop ups from the target site, which again is not good for user experience.
you cannot really achieve this using preventDefault like you said - because of async.
what I would try is:
preventDefault
store href as a variable
call ajax
redirect to href variable if true and not if false
jQuery(".compare-product-link").on("click", function(e) {
var href = $(this).attr('href');
e.preventDefault();
jQuery.ajax({
async : false,
dataType : "json",
url : "/compareextra/compare/allowed",
success : function(data) {
//console.log(data);
if(data.isAllowed == true) {
window.location = href;
}
}
});
});
if you need to create a link action you can use this code:
function triggerClick(url){
$('body').append('<span id="click_me_js"></span>');
$('span#click_me_js a')[0].click();
$('span#click_me_js').remove();
}
which will mimic a regular click on <a>

Is there a way to prevent a select menu from closing if the value change dynamically?

I need to be able to make an ajax request when a user opens a select menu "before the menu opens".
The ajax request will tell me what option should be enabled or disabled.
My first thought I was to bind an click event. In other words, on the click event make ajax call. The problem with using the click event is that I need to change the value dynamically when the ajax request finish to make sure the default value is selected after ajax completes.
The problem that I am running into is that every time the user clicks on the menu, the options come up and it immediately closes "unless the user hold down the mouse".
What event can I use to be able to make my ajax request, enable/disable options but keep the menu open instead of closing it?
Also, after the user clicks on the menu it will always rest to the value "0" because after the user clicks on the option it fires the event all over again.
Here is what I have done
$(function (e) {
$('#MasterWrapUps').on('click', function (e) {
var menu = $(this);
var status = "noattempt";
//enable only the noattempt dispos by default
attrWrapUpMenu(menu, status);
$.ajax({
type: "GET",
url: "/getstatus",
dataType: "json",
cache: false,
error: function (jqXHR, textStatus, errorThrown) {
alert("Error: " + errorThrown);
},
success: function (data) {
//reselect the selected option to the default
menu.val('0');
if ( data && ! $.isEmptyObject(data) ) {
status = data.status;
}
attrWrapUpMenu(menu, status);
}
});
});
function attrWrapUpMenu(menu, status)
{
menu.find('option').each(function (index, element) {
var option = $(element);
if (option.val() != '0' ) {
if (customIsAllowed(status, option)) {
option.attr("disabled", false);
} else {
option.attr("disabled", true);
}
}
});
}
function customIsAllowed(status, option)
{
var status = status.toLowerCase();
var group = option.attr('data-group');
if (group && group.toLowerCase().indexOf(status) > -1) {
return true;
}
return false;
}
});
This should do:
$('#MasterWrapUps').on('click', function (e) {
e.preventDefault();
...

Ajax- beforeSend

In order to prevent getting an error twice I use beforeSend.
hasSent = false
function submit() {
if (!hasSent)
$.ajax({
url: "${createLink(controller:'userInvitation', action:'ajaxUpdate')}",
type: "POST",
data: $("#invitationForm").serialize(),
success: function(data, textStatus, jqXHR) {
$('#invitationForm')[0].reset();
$('.thank-you-modal').modal('show');
hasSent = true;
console.log(hasSent)
},
complete: function() {
hasSent = false;
console.log(hasSent)
}
});
}
As you can see the ajax should happen only if hasSent=false.
For some reason the ajax happens also if the user clicks multiple time (very quick) on the submit button
To prevent this kind of issue disable the button before sending the ajax and then anable inside the success function
$(mybutton).prop("disabled",true);
// ajax call here
then
success: function(data, textStatus, jqXHR) {
$(mybutton).prop("disabled",false);
// code here
}
You can create another flag such as isSending
function submit() {
if(isSending)
return;
isSending = true
$.ajax({
// ...
complete: function() {
isSending = false;
}
});
}
there are two ways you can do this.
1) create a flag and check if the button is pressed. If pressed then do not execute the ajax code
change the flag back once the request is successful, like this
success:function(...)
{
flag=false;
}
Or you can disable the button at the button click so the request will be carried out and double click situation won't arise. Enable the button on complete like this
complete:function(..){ $("yourbutton").attr("disabled",false)}

Javascript Confirm showing twice in Safari, Works okay in Firefox but doesnt show in Chrome

Using a javascript confirm on my page but it is being odd.
As per the title, it shows twice in safari, works fine in firefox but doesnt show at all in chrome.
If i put my code into a jsfiddle it has no issues. No im not sure where to go from here. No errors in my console etc.
The code is below, but im not sure its actually related to it. Its the only place where the confirm is called / any actions for the button are. No duplicate ids etc.
Any help? Where to check next possibly? thanks for any help!
Here is a fiddle: http://jsfiddle.net/EEw9P/1/
NOTE: This works on all browsers for some reason.
The code i am using is this:
// if the save button is clicked, add a class to it
$(document).on('click','.saveupdatebutton',function(){
$(this).addClass('activeBtn');
});
// check the form for submit
$(document).ready(function () {
$(document).on('submit','.updatepost',function(){
// this var checks if the save button has been clicked and had the class added to it
var isSave = $(this).find('.saveupdatebutton').is('.activeBtn');
if (isSave) {
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// ... goes after Validation
if (check) {
$("#loaderEditPost").show();
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function (response) {
if (response.databaseSuccess) {
disableComments();
} else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
}
});
}
return false;
} else {
// check if the user REALLY wants to delete the post
if (confirm('Confirm deletion of your builds update?')) {
// DELETE POST!
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $ckEditor = $targetForm.find('.ckeditor'),
blogpost = $ckEditor.val();
// ... goes after Validation
if (check) {
$.ajax({
type: "POST",
url: "process/deletepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function (response) {
if (response.deleteSuccess)
$("#container").load("#container");
else
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
}
// if the user doesnt wish to delete their post
else
return false;
}
});
});

Magnific popup closes on content click after replacing content

I am using Magnific Popup version 0.8.9.
I am loading content into it via Ajax, and I use a callback for ajaxContentAdded. This callback sets up an event handler for submitting a form that was loaded into the popup, like so:
$('.add-item-btn').magnificPopup({
type: 'ajax',
closeOnContentClick: false,
callbacks: {
ajaxContentAdded: HandleItemFormSubmit
}
});
This works fine, the form submit is handled correctly. The event handler function posts it to the server, which (in case of errors) returns the entire form including error messages.
For this purpose I let it replace the popup's content with the returned form, and setup the submit handler again.
function HandleItemFormSubmit()
{
var popup = this;
// Submit form using ajax
$('form.item-form').submit(function()
{
var data = $(this).serialize();
var url = $(this).attr('action');
$.post(url, data, function(resp)
{
if (resp == 'OK')
{
// All good, close up
popup.close();
}
else
{
// Show HTML from response (with errors)
popup.closeOnContentClick = false;
popup.content.replaceWith(resp);
popup.updateItemHTML();
HandleItemFormSubmit();
}
});
return false;
});
}
However, despite setting closeOnContentClick to false at two different points, the popup immediately closes when content is clicked after the content was replaced (it does work the first time).
The content in the popup has a single root element by the way.
I hope the author or someone else can help out here, I have no idea what is wrong here.
Thank you very much!
I've found another solution:
$('html').on('submit', '#UR_FORM', function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
var magnificPopup = $.magnificPopup.instance;
magnificPopup.items[0].type = "inline";
magnificPopup.items[0].src = response;
magnificPopup.updateItemHTML();
}
});
});
You need to call the HandleItemFormSubmit for the popup object:
HandleItemFormSubmit.call(popup);
Otherwise when you call it the way you do, HandleItemFormSubmit();, the this will be set to window and this will not work as expected.
Update
Use this in the else clause:
if (resp == 'OK')
{
popup.close();
}
else
{
// Show HTML from response (with errors)
popup.closeOnContentClick = false;
popup.content.replaceWith(resp);
popup.updateItemHTML();
HandleItemFormSubmit.call(popup);
}

Categories