jquery dialog pause a script like alert() - javascript

I have next javascript code:
function getLetterOfResponsibilityNote(dialogNoteLink, visitCountryName) {
$.ajax({
type: "GET",
url: "/Admin/Applications/GetLetterOfResponsibilityNote/?selectedCountryName=" + visitCountryName,
cache: false,
success: function(data) {
if (data != "") {
dialogNoteLink.dialog();
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
}
}
});
}
I want to call it, for example, 5 times and get data from server, then I will display it in dialog. But I get one Jquery UI Dialog with message. Problem is that script doesn't pause while dialog is open.
If I write instead of it:
dialogNoteLink.dialog();
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
with alert() - it works fine!
How I can resolve this problem?

That is how JavaScript alert works. If you want to make the calls wait for the dialog to close, then you will have to make the subsequent calls in a callback after the dialog is closed. You should do something like this -
var arrayofNotesAndCountryNames = [{
"dialogNoteLink" : link1,
"visitCountryName" : "country1"
},{
"dialogNoteLink" : link2,
"visitCountryName" : "country2"
},{
"dialogNoteLink" : link3,
"visitCountryName" : "country3"
}];
var currentIndex = 0;
function getLetterOfResponsibilityNote() {
var dialogNoteLink = arrayofNotesAndCountryNames[currentIndex].dialogNoteLink;
var visitCountryName = arrayofNotesAndCountryNames[currentIndex].visitCountryName;
$.ajax({
type: "GET",
url: "/Admin/Applications/GetLetterOfResponsibilityNote/?selectedCountryName=" + visitCountryName,
cache: false,
success: function(data) {
if (data != "") {
dialogNoteLink.dialog({close : function(){
currentIndex++;
if (currentIndex < arrayofNotesAndCountryNames.length){
getLetterOfResponsibilityNote();
}
}
});
dialogNoteLink.attr("title", "Letter Of Responsibility Note for " + visitCountryName);
dialogNoteLink.html("<p>" + data + "</p>");
}
}
});
}
getLetterOfResponsibilityNote();

The dialog should be shown from the callback of the query to the server.
There are no blocking function or dialogs on JQuery.

Related

Change a tooltip content on hover over session times button

My ASP.Net webpage generates buttons with below codes
<a id="1173766" val="248506" titletext="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1" target="_self" href="https://localhost:6969/VenueTicketing/Start.aspx?sessionId=248506&cinemaId=cbcc0921bb8e233ab9626690" class="tooltip" title="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1">11:30am</a>
When I hover over session I see basic information about session like screen name and seats remaining. Please see screenshot attached
On hover over session I want to display real time seats remaining number, So i am making an ajax call to a function which send api request and get live seats remaining number.
I am trying to update seats remaining number on rendered page by using following java script code.
<script type="text/javascript">
$(document).ready(function () {
function handler(ev) {
var target = $(ev.target);
var sessionid = target.attr('id');
var sessionPOSid = target.attr('val');
var TooolTipText = target.attr('titletext');
target.attr('title', TooolTipText);
if (sessionPOSid == "done")
{
}
else
{
if (target.is(".tooltip")) {
$.ajax({
type: "POST",
url: '../WebService/Home_SessionTimes.asmx/GetSeatsRemaining',
data: "{sessionId: '" + sessionid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//alert(msg.d);
var n = TooolTipText.indexOf("Seats Available: ");
var t = TooolTipText.substr(n + 17, 3);
if (t.indexOf("<") >= 0) {
if (t.indexOf("<") == 2) {
t = t.replace("<", "");
}
else {
t = t.Substring(0, 1);
}
}
TooolTipText = TooolTipText.replace(t, msg.d);
$('#' + sessionid).attr('title', TooolTipText);
$('#' + sessionid).attr('titletext', TooolTipText);
//$('#' + sessionid).attr('val', "done");
target.attr('title', TooolTipText);
target.tooltiptext = TooolTipText;
},
});
}
}
}
$(".tooltip").mouseover(handler);
});
Above code updates the "titletext" field of tag but does't change anything on "title" field.
Any help would be appreciated.
I have solved this by using qtip. Every time user hovers over div with 'sessiontimes' class, I make ajax call to generate tooltip text (that comes from server based upon session time).
This is my output now:
This is the jQuery code. you need to import qtip css and script files from their website.
<script type="text/javascript">
$(document).ready(function () {
$('.sessiontimes').qtip({
style: { classes: 'qtip-bootstrap' },
content: {
text: function (event, api) {
$.ajax({
url: '../SessionToolTip.aspx',
data: 'sid=' + $(this).children("a").attr("id"),
dataType: "text",
})
.then(function (content) {
api.set('content.text', content);
}, function (xhr, status, error) {
api.set('content.text', status + ':' + error);
});
return 'Loading...';
}
}
});
});
</script>
If you may look at this post and see if the same answer could apply to your situation
JQUERY Change Title not working with tooltip

Multiple ajax calls in event function full calendar

I am using fullcalendar jQuery plugin in our page for create/view meeting invitation.
And my new requirement is to show meetings created in outlook for that particular user in our page . My webservice(used to pull meetings from outlook) took min of 45 secs to send the reponse . I don't want the user to wait completely for 45 secs .(Performance Issue) So I just want to load events from db first and then i want to append events coming back as webservice response . Hence user couldn't feel that much delay.
So I just made two ajax calls to pull required details. One ajax call is to pull events from local database(SUCCESS) and another one is to call the webservice to pull events created in Outlook.
events: function(start, end, timezone,callback) {
$.ajax({
url: // url hits db and gets meeting details in db
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
callback(events);
}
$.ajax({
url: // url calls webservice and gets meetings in Outlook
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
alert("External Events "+ events.length); //EXECUTED
callback(events); //NOT EXECUTED
}
});
}
And now the problem is ,
1 . First ajax call is working fine .
2 . Am getting proper response from Webservice but the response wasn't attached to calendar .
And my queries are ,
Can't we use callback(events) twice ?
Or else please suggest me the alternative solution for this ?
If am using two event function separately,only second event function will gets executed . Why first event function is not getting executed ?
A little old, but a way around for reference. In your first ajax call, instead of the callback, put in the second ajax call
$.ajax({
url: // url hits db and gets meeting details in db
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
//second call
$.ajax({
url: // url calls webservice and gets meetings in Outlook
dataType: 'json',
success: function(response) {
var events = [];
if(response != null){
alert("Success");
$.map(response ,function ( r ){
alert(r.title + " " + r.start + " " + r.end);
events.push({
title : r.title,
start : r.start,
end : r.end
});
});
}
alert("External Events "+ events.length);
callback(events); // return all results
}
});
}
Nothing is wrong with your code. Ensure the responses you're getting from your server is what you expect (response != null for instance).
https://jsfiddle.net/5ds8z06p/
var foo = function(callback) {
$.ajax({
url: '/echo/json',
success: function() {
callback('first');
}
});
$.ajax({
url: '/echo/json',
success: function() {
callback('second');
}
});
};
foo(function(bar) {
console.log(bar);
});

jQuery refresh div based upon HTML5 data element

My code is as follows:
$('*[data-pickup]').change(function(){
var value = $(this).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(this).attr("data-pickup") + "']").show();
})
The AJAX call shows a response when viewed through Firebug, which wasn't being refreshed on the screen, so I changed it to a simple "Hello" response, which still doesn't work.
If I comment out the .html("HELLO 2") line, it shows the once hidden div containing the HTML5 data element of data-pick=1 or data-pick=2, etc. (depending on what attr("data-pickup") is) which is automatically filled with "Test", so it shows "Test".
If I uncomment the .html("HELLO 2") line, the div once shown says "HELLO 2". But, in the case of the commented out .html("HELLO 2") line, it should be being updated from "Test" to "Hello" via the AJAX call, but it isn't. If I change the data* to a simple HTML id element and update all the code to #" + $(this).attr("data-pickup") + ", it works the exact same with the data attribute (the AJAX call doesn't update anything).
And when I make a var called "el" and make it equal to *[data-pick='" + $(this).attr("data-pickup") + "'], and then print it to the console it appears as: "[data-pick='1']" or "[data-pick='2']", etc. Then if I update all the code from $("*[data-pick='" + $(this).attr("data-pickup") + "']").whatever to $(el).whatever (thinking there might be a bug somewhere), it still works the same as before.
So, what have I done wrong? Why won't the div get refreshed via the AJAX call but it will after the AJAX call?
The problem is that 'this' in the success handler of the ajax function is the ajax function itself not the element that triggered the event handler. What you need to do is store the value of the element var el = $(this) then reference that whenever you want to access the element taking advantage of closures.
$('*[data-pickup]').change(function(){
var value = $(this).val();
var el = $(this);
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + el.attr("data-pickup") + "']").show();
})
Try this:
$('*[data-pickup]').change(function() {
var self = this;
var value = $(self).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(self).attr("data-pickup") + "']").show();
})
this inside the success function is not the same this as elsewhere in the change handler.
Here's a solution :
$('*[data-pickup]').change(function(){
var value = $(this).val();
var $el = $("*[data-pick='" + $(this).attr("data-pickup") + "']");//here keep a reference to the element(s) of interest.
console.log(value);
$.ajax({
type: "POST",
cache: false,
url: "a.php?pickup",
data: {'X': value},
success: function(data) {
$el.html("HELLO");//$el is still available here, from the closure formed by the outer function
}
});
$el.show().html("HELLO 2");
});

How to display a progress bar during an ajax request (jquery/php)

I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.

Why does my alert statement not fire?

When testing this code, I purposely make it so the text returned from the ajax call is not 1. It reaches that else statement. The other statements execute, however, I never see an alert.
$.ajax ( {
type: "GET",
processData: false,
url: SITE_URL + "/system/check_user_project/" + session_id + "/" + cart_id + "/" + project_id + "/" + revision_id, //send data to this url
dataType: 'text',
})
.done (function(text) //When we have the data
{
if ("1" == text)
{
photos_populate_albums(session_id); //Call function to populate albums
if (typeof(project_id) !== "undefined" && project_id > 0) //If we have a project
{
mattes_add_default_matte(null, null, null, null, SITE_URL + "/system/xml/export/" + project_id + "?rid=" + revision_id);
}
else //otherwise...
{
mattes_add_default_matte(); //Add the default matte
}
common_change_step(document.getElementById("step1")); //Set the step to 1
}
else
{
$("#content").empty();
alert("Invalid project.");
window.location.href = (SITE_URL + "/user/mystuff/projects/?pid=" + partner_id);
}
});
UPDATE: I just realized I accidentally checked the box that asks if you want to keep receiving alerts from this webpage when it came up. Now I don't know where to undo it.
The code works. To reset the alert setting I had to re-open the tab.
Probably it's because you're doing a redirect just after the alert, and it is being supressed.
You may try replacing this:
$("#content").empty();
alert("Invalid project.");
window.location.href = (SITE_URL + "/user/mystuff/projects/?pid=" + partner_id);
For something like this:
$("#content").empty();
if (alert("Invalid project.") || true)
window.location.href = (SITE_URL + "/user/mystuff/projects/?pid=" + partner_id);

Categories