JQuery UI Multiple Dialogs Not Working - jquery-ui

I have a page with two links that open two different modals, the "forgotten password" link opens the "forgotten password" modal and the "tell-a-friend" link opens the "tell-a-friend" modal.
Both modals contain forms that can be submitted.
The problem is if I open the first modal and submit it or close it, I cannot submit the second modal.
I can open the second modal, but I cannot submit it.
Please advise what the problem could be!
Here below is the javascript code that resides in separate javascript file, which is then imported into the HTML file. It is not inline javascript, if that would matter.
[code]
var forgottenPasswordDiv;
var tellAFriendDiv;
function clearErrorMessages() {
$('#errorMessage').text("");
}
function openForgottenPassword() {
forgottenPasswordDiv = $('#forgotten-password');
$('#forgotten-password').load("/Templates/include/new/ajax/modal/forgottenPassword.jsp")
.dialog(
{
autoOpen:false,
modal:true,
position:'left+35% top+20%',
width:'330',
height:'auto'
}
);
$('#forgotten-password').dialog('open');
}
function closeForgottenPassword() {
forgottenPasswordDiv.dialog("close");
}
function submitForgottenPassword() {
clearErrorMessages();
var email = $('#email').val();
if (email == null || email == '') {
$('#errorMessage').text("Please enter your user name or email");
} else {
clearErrorMessages();
/* Ajax Post */
var formData = $("#forgottenPasswordForm").serialize();
$.ajax({
type: "GET",
url: "/Templates/include/new/ajax/forgottenPassword.jsp",
data: formData,
success: function(data) {
if (data.error != null) {
$("#errorMessage").text(data.error);
} else {
$('#forgottenPasswordForm , .info').fadeOut(1000);
$("#successMessage").text(data.success);
$("div").removeClass('display-none');
}
},
dataType: 'json'
});
}
}
function openTellAFriend(gunId) {
tellAFriendDiv = $('#tell-a-friend');
$('#tell-a-friend').load("/Templates/include/new/ajax/modal/tellAFriend.jsp?id=" + gunId)
.dialog(
{
autoOpen:false,
modal:true,
position:'center top+10%',
width:'330',
height:'auto'
}
);
$('#tell-a-friend').dialog('open');
}
function closeTellAFriend() {
tellAFriendDiv.dialog("close");
}
function submitTellAFriend() {
clearErrorMessages();
var yourname = $('#yourname').val();
var errorMessage = "";
if (yourname == null || yourname == '') {
errorMessage += "Please enter your name<br />";
}
if (errorMessage != '') {
$('#errorMessage').html(errorMessage);
} else {
clearErrorMessages();
/* Ajax Post */
var formData = $("#tellAFriendForm").serialize();
$.ajax({
type: "GET",
url: "/Templates/include/new/ajax/tellAFriend.jsp",
data: formData,
success: function(data) {
if (data.error != null) {
$("#errorMessage").text(data.error);
} else {
$("#tellAFriendForm").fadeOut(1000);
$("#successMessage").text(data.success);
$("div").removeClass('display-none');
}
},
dataType: 'json'
});
}
}
[/code]

The ui-dialog widget will stay in the DOM as a hidden element even after the dialog is closed.
So, in order to isolate your two dialog functionalities from each other I'd suggest that you call:
forgottenPasswordDiv.dialog("destroy")
in your "closeForgottenPassword" function and
tellAFriendDiv.dialog("destroy")
in your "closeTellAFriend" function.
This will return the dialog back to its pre-init state (which is not harmful at all because you reinit it in your "open" functions.)

Related

Square Payment Form Request Card Nonce not working in versions of safari

I seem to be having an issue with the requestCardNonce() function for some safari users This is using the Javascript API in my .net MVC application.
The current version I'm testing on appears to be working (13.0.4) but users are still reporting an inability to complete their orders with previous versions of safari. When filling in their information they're able to see the dialog that contains the fields for the Card Name, Number, CVV, and Postal code and expiration date but can't seem to proceed to the next dialog. The onGetCardNonce(event) function seems to be having issues executing properly.
The code I have currently looked like this
if (gateway == "Square Payment Gateway") {
paymentForm = new SqPaymentForm({
applicationId: appId,
inputClass: 'sq-input',
autoBuild: false,
cardNumber: {
elementId: 'sq-card-number',
placeholder: 'Card Number'
},
cvv: {
elementId: 'sq-cvv',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: 'Postal'
},
// SqPaymentForm callback functions
callbacks: {
cardNonceResponseReceived: function (errors, nonce, cardData) {
let errMsg = "";
if (errors) {
// Log errors from nonce generation to the browser developer console.
console.error('Encountered errors:');
errors.forEach(function (error) {
console.error(' ' + error.message);
errMsg += ' ' + error.message;
});
alert('Encountered errors' + errMsg);
return;
}
$("#CardNumber").val(cardData["last_4"]);
$("#squareToken").val(nonce)
$("#form-container").dialog("close");
var isValid = true;
$('#CardName,#CardNumber').each(function () {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "",
"background": ""
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if ($("#Total").val() == "0.00" || $("#Total").val() == "0")
isValid = true;
if (isValid == false) {
$('#PayCreditCard')[0].disabled = false;
}
else {
var targetUrl = $(this).attr("href");
// Open Terms & Conditions
$("#dvTermsConditions").dialog("open");
$("#dvTermsConditions").dialog({
autoOpen: false,
modal: true,
buttons: {
"Proceed": function () {
if ($('#AgreeToTerms').is(':checked')) {
$(':input[type="submit"]').prop('disabled', true);
$(this).dialog("close");
$("#frmCheckOut").submit();
}
else {
alert("You must agree to the terms & conditions.");
}
},
"Cancel": function () {
$('#PayCreditCard')[0].disabled = false;
$(this).dialog("close");
}
}
});
}
}
}
});
paymentForm.build();
function onGetCardNonce(event) {
// Don't submit the form until SqPaymentForm returns with a nonce
event.preventDefault();
// Request a nonce from the SqPaymentForm object
paymentForm.requestCardNonce();
}
function closeCC() {
$("#form-container").dialog("close");
}
}
Originally the issue was that payment form was not found so I moved the definition of that outside the if statement and that seemed to clear up the issue for safari 13.0.4+
Does anyone have suggestions on how to make the square payment form (v2) work on all (or at least the last 3+ years) of versions of Safari (not on mobile)?

Titaniuim: Facebook login event doesn't fire

I am trying to login through facebook.
I have all info in plist and in entitlelements file
So when I click to button it is redirecting safari facebook page and asking to confirm
When I click to OK it doesn’t fire ‘login’ event and it is not logged.
Currently I am testing on iOS 5s Simulator
Here is the code
var fbook = require('facebook');
fbook.appid = <MyAPP_ID>;
fbook.permissions = ['public_profile'];
//fbook.forceDialogAuth = true;
if (fbook.loggedIn) {
//progress.hide();
params = {
access_token : fbook.accessToken
};
fbook.requestWithGraphPath('/me', params, 'GET', function(e) {
var result = JSON.parse(e.result)
});
} else {
fbook.addEventListener('login', function(e) {
//alert('try to login');
if (e.success) {
//progress.hide();
params = {
access_token : fbook.accessToken
};
fbook.requestWithGraphPath('/me', params, 'GET', function(e) {
var result = JSON.parse(e.result);
Ti.API.info("Result is : " + e.result);
});
} else if (e.error) {
Ti.API.info("error");
//alert('Error: ' + e.error);
} else if (e.cancelled) {
Ti.API.info("cancelled");
}
});
fbook.authorize();
/*
fbook.addEventListener('logout', function(e) {
fbook.logout();
});*/
}

gapi.auth.signOut(); not working I'm lost

Below is the code I am using to login with google. I have an element on login.php with id authorize-button. When clicked it logs in just fine.
I have a logout link in my header file. When I click the logout it calls gapi.auth.signOut(); then it destroys session and redirects back to login.php
This happens as far as I can tell but then it just logs the user right back into our site with google. This is a pain as some of our users switch from google to facebook logins.
Thanks in advance for any help.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
//authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
//authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function signOut() {
gapi.auth.signOut();
}
function makeApiCall() {
gapi.client.load('oauth2', 'v2', function() {
var request = gapi.client.oauth2.userinfo.get();
request.execute(function(logResponse) {
var myJSON = {
"myFirstName": logResponse.given_name,
"myLastName": logResponse.family_name,
"name": logResponse.name,
"socialEmailAddress": logResponse.email
};
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(logResponse2) {
//alert(JSON.stringify(logResponse));
myJSON['profilePicture'] = logResponse2.image.url;
myJSON['socialId'] = logResponse2.id;
//alert(JSON.stringify(myJSON));
$.ajax({
type: "POST",
url: "includes/login-ajax.php",
data: "function=googleLogin&data=" + JSON.stringify(myJSON),
dataType: "html",
success: function(msg) {
if (msg == 1) {
//window.location = "settings.php";
}
}
});
});
});
});
});
}
Make sure you have set your cookie-policy to a value other than none in your sign-in button code. For example:
function handleAuthClick(event) {
gapi.auth.authorize(
{
client_id: clientId,
scope: scopes,
immediate: false,
cookie_policy: 'single_host_origin'
},
handleAuthResult);
return false;
}
Note that sign out will not work if you are running from localhost.
Weird issue, but solved my problem by rendering the signin button (hidden) even if the user is authenticated.
See full question/answer here https://stackoverflow.com/a/19356354/353985
I came across the same issue today. I have search for solution the whole. The only reliable solution that worked for me is through revoke as explained here
I stored access_token in session which is needed during revoke
Below is my code you may find it useful
function logout() {
var access_token = $('#<%=accessTok.ClientID %>').val();
var provider = $('#<%=provider.ClientID %>').val();
if (access_token && provider) {
if (provider == 'GPLUS') {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' +
access_token;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
},
error: function (e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
}
});
}
else if (provider == 'FB') {
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.logout();
}
});
}
} else {
}
}

Passing Multiple Checkbox value using jquery ajax

I am displaying multiple records on my ASP.NET MVC 4 view where each record has a checkbox. I want the user to be able to select multiple records (by checking checkboxes) and click Delete button in order to delete them. So far I can call the Delete Action method via jquery ajax but the problem is my action method does not seem to be accepting the passed array.
Here is my jquery code:
$(function () {
$.ajaxSetup({ cache: false });
$("#btnDelete").click(function () {
$("#ServicesForm").submit();
});
$("#ServicesForm").submit(function () {
var servicesCheckboxes = new Array();
$("input:checked").each(function () {
//console.log($(this).val()); //works fine
servicesCheckboxes.push($(this).val());
});
$.ajax({
url: this.action,
type: this.method,
data: servicesCheckboxes,
success: function (result) {
if (result.success) {
}
else {
}
}
});
return false;
});
});
and here is my action method:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
if (deleteservice != null)
{
//no hit
}
}
What am I missing?
Edit
I also tried console.log(servicesCheckboxes); before $.ajax() which outputs ["3", "4"] but still get null when I pass data as specified in answer below data: { deleteservice: servicesCheckboxes }. Even I tried data: [1,2] but still action method shows null for deleteservice in action method.
Just pass the array to your action:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: { deleteservice: servicesCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
Or, just use the serialize() jquery method to serialize all fields inside your form:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: $(this).serialize(),
success: function (result) {
if (result.success) {
}
else {
}
}
});
In your controller:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
bool deleted = false;
if (deleteservice != null)
{
// process delete
deleted = true;
}
return Json(new { success = deleted });
}
Finally got it working. "MVC detects what type of data it receive by contentType" as explained here so I made the following changes to $.ajax()
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
//data: { deleteservice: servicesCheckboxes }, // using the parameter name
data: JSON.stringify({ deleteservice: servicesCheckboxes }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});

How to change the value of a JQueryUI progressbar dynamically?

In my import photos script, I try to update a progressbar (Jquery UI) following a while loop with Ajax requests.
The JQueryUI progressbar, which is supposed to be displayed before the launch of ajax requests do it after. So I have the user feedback at the end of the execution of my while loop ... (The console shows me that these applications are running well, in the right order)
I thought about using live () or bind (), but I do not know how to test it ...
Here is my jquery code:
$(function() {
var percent_progressbar=0;
$('#myform').submit(function() {
$('#myform').hide();
$("#text_result").html("Import in progress : <span class='progression'>0/0</span>").show(10, function() {
$("#myprogressbar").progressbar({value:percent_progressbar});
$("#myprogressbar").show(10, function() {
if (jQuery.trim($("#id_src").val()).length!=0) {
// Total number of photos to import
$.ajax({
type : 'POST',
async : false,
url : '/nbphotos.php',
data : 'chem=mydir',
success : function(nbphotos){
if (nbphotos>0){
$(".progression").html("0"+" / "+nbphotos);
var finish=false;
var nb_photos_imported=0;
var ajax_done = false;
var resultat_ajax="";
// Variables envoyées en Ajax
var datas = desvariables;
while (nb_photos_imported < nbphotos) {
ajax_done = false;
$.ajax({
type : 'GET',
async : false,
url : '/traitement.php',
data : datas,
success : function(resultat){
resultat_ajax=resultat;
ajax_done=true;
nb_photos_imported++;
}
});
if (ajax_done==true){
if (resultat_ajax=="ok") {
percent_progressbar = Math.floor(nb_photos_imported*100/nbphotos);
$("#myprogressbar").progressbar("option", "value", percent_progressbar);
console.info("Succès ajax (resultat : OK) : "+percent_progressbar);
$(".progression").html(nb_photos_imported+" / "+nbphotos);
} else {
finish=true;
$("#text_result").html(ajax_done);
return false;
}
} else {
// ajax error => exit the while
console.info("Ajax execution error "+nb_photos_imported);
return false;
}
} // While
if (finish==true) {
$("#myprogressbar").hide('slow');
$('#text_result').html("Import of "+nb_photos_imported+" photos done.");
}
} else{
$("#text_result").html("No photo to import.");
$("#myprogressbar").hide(10);
$('#myform').show("slow");
}
}
});
}
});
}); // callback #text_result.show()
return false;
});
});
Here is my new code. The console log show the progression of the percentage, the photos are imported, but I still have the display at the end. If I put a breakpoint with me debugging tool somewhere in the loop, the display is refreshing and everything is OK...
$(function () {
$("#myprogressbar").show();
var RetourNbPhotos = "";
var RetourImported = "";
var fini = false;
var percent_progressbar = 0;
var nb_photos_imported = 0;
var datas = desvariables; // datas sent with ajax
// Number of photos to import
function NbPhotoAjax() {
return $.ajax({
type: 'POST',
async: false,
url: '/boutique/modules/importimageswithiptc/ajax-nbphotos.php',
data: 'chem=$cheminimport',
success: function (nbphotos) {
RetourNbPhotos = nbphotos;
}
});
}
// Photo Ajax Import
function ImportPhotoAjax() {
$("#text_result").html("Import in progress : <span class='progression'>0/0</span>").show();
// RetourImported = "";
return $.ajax({
type: 'GET',
async: false,
url: '/boutique/modules/importimageswithiptc/ajax-traitement.php',
data: datas,
success: function (resultat) {
RetourImported = resultat;
}
});
}
$("#myprogressbar").progressbar({
value: percent_progressbar
});
$('#generator').submit(function () {
$('#generator').hide();
if (jQuery.trim($("#id_product_src").val()).length != 0) {
$.when(NbPhotoAjax()).then(function () {
if (RetourNbPhotos > 0) {
while (nb_photos_imported < RetourNbPhotos) {
$.when(ImportPhotoAjax()).then(function () {
nb_photos_imported++;
if (RetourImported == "ok") {
percent_progressbar = Math.floor(nb_photos_imported * 100 / RetourNbPhotos);
$("#myprogressbar").progressbar("option", "value", percent_progressbar);
console.info("Success : " + percent_progressbar + "%");
$(".progression").html(nb_photos_imported + " / " + RetourNbPhotos);
} else {
fini = true;
$("#text_result").html("ajax_reussi");
return false;
}
}).fail(function () {
// ajax error => exit the while
console.info("Ajax execution error " + nb_photos_imported);
return false;
});
} // While
if (fini == true) {
$("#myprogressbar").hide('slow');
$('#text_result').html("Import of " + nb_photos_imported + " photos done.");
}
} else {
$("#text_result").html("No photo to import.");
$("#myprogressbar").hide(10);
$('#generator').show("slow");
}
});
}
return false;
});
});

Resources