Jquery Impromptu function running order problem - javascript

I I hafe a function which uses the $.prompt Jquery (impromptu) pluggin. This works fine except that whenever I call the function it is run right at the end of the function that it was called from.
Here is the function...
function addfile(){
var txt = '<?php echo $JSString; ?>';
function mycallbackform(v,m,f){
if(v != undefined)
var newText = f.alertName + " , " + f.alertName.replace("-", " ").replace(".php", "");
alert(newText);
}
$.prompt(txt,{
callback: mycallbackform,
buttons: { Add: 'add', Cancel: 'cancel' }
});
}
The PHP bit just adds the html string in and is working fine, the problem still occours when using text (i.e. 'this is a prompt').
Whenever I call addfile() from JS it will run last. e.g. ...
function newfunction()
{
prompt("Before");
addfile();
prompt("after");
}
... will display do the following ...
Prompt - 'Before'
Prompt - 'After'
addfile();
No matter what I do the addfile() will always run last which confuses me. I'm pretty new to these things so If i'm doing anything really stupid please don't be afraid to point it out.Subnote: The function is sitting in the header of my php file so that the <?php echo $JSString; ?> works. I have removed the php and inserted the function into an external JS file but the same problem prevails so it is the $.prompt which seems to be causing the problem not the JS
Any ideas as to how to get this JS to behave greatly appreciated.Many thanks

your prompt function is asynchronous, that's why it accepts a callback function as parameter.
Try this:
prompt(
txt,
{callback: function() {
addfile();
prompt("after");
}}
);

Above approach is not working . Below is the code portion that. Alert is being displayed before blocking the page. I am using blockUI along with it.
function blockPage(){
$.blockUI({
message: "<img src='loading.gif'/>",
color: 'transparent',
backgroundcolor: '#777777',
top: $(window).height()/2
});
return true;
}
function dosomethingelse(){
var aa;
var bb;
alert("c");
}
function createOverlay(){
var overlaySubmit = function(e,v,m,f){
if(v === -1){
alert("Closing the prompt");
$.prompt.close();
return false;
} else if(v === 1){
dosomethingelse();
//blockPage();
return false;
}
};
var prompt = $.prompt(
"This is a test prompt",
{
opacity: 0.3,
buttons: {Add: 1, Cancel: -1},
position: {x: 300},
prefix: 'jqi',
submit: function(e,v,m,f){
blockPage();
try{
alert(g);
} catch (err){
alert("here");
}
overlaySubmit(e,v,m,f);
}
});
prompt.bind('promptsubmit',blockPage);
}
<!-- Ajax-->
$('#ajax').click(function(){
$.ajaxSetup({async:false});
$.ajax({
url: "test-server.txt",
success: function(response){
createOverlay();
return false;
},
error: function(){
return false;
}
});
});

Related

Execute jquery functions in order

function fn_one() {
$('#search-city-form').trigger('click');
}
function fn_two() {
$("form input[name='tariffId']").val("137");
$('#search-city-form').trigger('click');
}
function fn_three() {
$("form input[name='tariffId']").val("138");
$('#search-city-form').trigger('click');
}
function fn_four() {
$("form input[name='tariffId']").val("139");
$('#search-city-form').trigger('click');
}
$(document).on('click','.ui-menu li',function(){
fn_one();
fn_two();
fn_three();
fn_four();
});
I have this js code. I need to execute the functions in on(click) in order, i.e. fn_one() goes first, fn_two() second and etc.
Please give simple example of how can I achieve this.
Edit: OK, I used the next function to be executed in the previous one but still I was getting erraneous data. So I think I realized why this is happening. I will explain what $('#search-city-form').trigger('click'); does. It triggers a form submit which makes an Ajax call and other function are not waiting till ajax request is complete. So how do I make it to wait for ajax request to complete?
EDIT 2:
Event handler for $('#search-city-form'):
$('#cdek').submit(function() {
var formData = form2js('cdek', '.', true, function(node) {
if(node.id && node.id.match(/callbackTest/)) {
return {
name : node.id,
value : node.innerHTML
};
}
});
var formDataJson = JSON.stringify(formData);
// console.log(JSON.stringify(formData));
document.getElementById('testArea').innerHTML = 'Отправляемые данные: <br />' + JSON.stringify(formData, null, '\t');
$.ajax({
url : 'http://api.cdek.ru/calculator/calculate_price_by_jsonp.php',
jsonp : 'callback',
data : {
"json" : formDataJson
},
type : 'GET',
dataType : "jsonp",
success : function(data) {
console.log(data.result.price);
} else {
for(var key in data["error"]) {
console.log(data["error"][key]);
}
}
}
});
return false;
});
I'll do this. If you need validate when the function has triggered, maybe you need to work with promises.
function fn_one() {
$('#search-city-form').trigger('click');
fn_two()
}
function fn_two() {
$("form input[name='tariffId']").val("137");
$('#search-city-form').trigger('click');
fn_three()
}
function fn_three() {
$("form input[name='tariffId']").val("138");
$('#search-city-form').trigger('click');
fn_four()
}
function fn_four() {
$("form input[name='tariffId']").val("139");
$('#search-city-form').trigger('click');
}
$(document).on('click','.ui-menu li',function(){
fn_one();
});

how to use noConflict for 2 js functions?

I have a different js framework and it stop below script.
So I read that I must using The noConflict() Method.
I try do it but just first function works. and second function do not works!
(if replace loction these two functions,Always only first function works.
what is my mistake?
I used this tutorial on w3school to do it.
http://www.w3schools.com/jquery/jquery_noconflict.asp
Also I try var jq = $.noConflict(); and other method.
I use this script inline in my html codes.
function checkCitySelect()
{
$.noConflict();
jQuery(document).ready(function($){
$("#province, #county, #district,#selectSubject").on('change', function() {
var txt;
var type = this.id;
txt = $("#"+type).val();
$.post("ajax/validation.php", {value: txt,id: type}, function(result){
if(type == 'province')
$("#county").empty().append(result);
else if(type == 'county')
$("#district").empty().append(result);
else if(type == 'district')
{
setAddressMap2("Paris, France");
}
else if(type == 'selectSubject')
{
$("#selectSubject").after(result);
}
});
});
});
}
function setAddressMap2(whereis)
{
$.noConflict();
jQuery(document).ready(function($){
$("#signup_map").gmap3({
getlatlng:{
address: whereis,
callback: function(results){
if ( !results ) return;
$(this).gmap3({
marker:{
latLng:results[0].geometry.location
}
});
}
}
});
});
}
checkCitySelect();
setAddressMap2("JAPAN");
</script>

how to pass a callback function to a button?

i have a php project which includes a few js files.
One of the js files, is a popup manager. This is the code:
function openYesNoPopup(message, callback) {
$('.popupBtn').unbind();
var popup_top = "<div class = 'popup_top'></div>";
var popup_bottom = "<div class = 'popup_bottom'></div>";
var yesNoButtonsDiv = '<div class="popupBtnContainer"><button class="popupBtn" data-type="yes">Yes</button><button class="popupBtn">No</button></div>';
$.fancybox.open({
padding: 0,
content: message
});
$('.fancybox-skin').prepend(popup_top);
$('.fancybox-skin').append(popup_bottom);
$('.fancybox-outer').append(yesNoButtonsDiv);
$(document).on('click', '.popupBtn', function() {
if ($(this).data('type') === 'yes') {
callback;
}
$.fancybox.close();
});
}
The problem is, the callback function that i want exacuted, is undefined.
Can anyone help me make this right?
Thank you!
the call to openYesNoPopup:
openYesNoPopup("Hello World",foo());
function foo(){
alert("bear");
}
for some reason, the alert is shown right on start...
You'd have to actually call it
if ($(this).data('type') === 'yes') {
callback();
}
but when calling the openYesNoPopup function, you'd reference it, not call it
openYesNoPopup("Hello World",foo);

How to delay 5 seconds in JavaScript

I have JavaScript function:
function validateAddToCartForm(object) {
value = $(".product-detail-qty-box").val();
if(!isInt(value) || value < 1) {
$(".product-detail-error").show();
return false;
} else {
$(".product-detail-error").hide();
var product_name = $("#product_detail_name").text();
var NewDialog = $('<div id="MenuDialog">\ ' + product_name + '</div>');
NewDialog.dialog({
modal: true,
title: "title",
show: 'clip',
hide: {effect: "fadeOut", duration: 1000}
});
}
return true;
}
I need to pause 3 to 5 seconds before returning true, because I want to show a New Dialog box for a while. How can I implement this delay?
The only way to simulate delay in js is callback on timeout.
change the function to:
function validateAddToCartForm(object,callback) {
value = $(".product-detail-qty-box").val();
if(!isInt(value) || value < 1) {
$(".product-detail-error").show();
callback(false);
} else {
$(".product-detail-error").hide();
var product_name = $("#product_detail_name").text();
var NewDialog = $('<div id="MenuDialog">\ ' + product_name + '</div>');
NewDialog.dialog({
modal: true,
title: "title",
show: 'clip',
hide: {effect: "fadeOut", duration: 1000}
});
}
setTimeout(function() {callback(true);},5000);
}
where you call it you should do something like:
instead of
function somefunct() {
//code before call
if (validateAddToCartForm(object)) {
//process true
} else {
//process false
}
//rest of the function
}
place something like:
function somefunct() {
//code before call
validateAddToCartForm(object,function(ret) {
{
if (ret) {
//process true
} else {
//process false
}
//rest of the function
}
}
In to answer to your comment.
I assume:
that you want to prevent click event if validate false,
that all elements that you added onclick="..." have class ".clickme",
the element now looks like
<input type="submit" onclick="return validateAddToCartForm(this)" class="clickme" />
so 1st change the element to
<input type="submit" class="clickme" />
add to your javascript the following:
//this handle original click, drop it out, and only pass after validation
$(function () {
$('.clickme').click(function (e) {
var $t = $(this);
//if event triggered return true
if (e.isTrigger) return true;
validateAddToCartForm(this, function (ret) {
if (ret) {
$t.trigger('click');
}
});
return false;
});
});
also I suggest to use "submit" event on the form itself instead of "click" (the demo of submit)
Instead of blocking, you can use seTimeout to remove the #MenuDialog after a certain time.
function validateAddToCartForm(o){
var keep_dialog_time = 5 * 1000; // five seconds.
// Whatever...
/* Use setTimeout(function, milliseconds) to delay deletion of #MenuDialog.
This will get executed keep_dialog_time milliseconds after this call, and
won't block. */
setTimeout(function(){
$('#MenuDialog').hide(); // maybe there is another function to do this, I'm not a jQuery guy really.
}, keep_dialog_time);
return true;
}
JavaScript is single threaded. This means, when you block, you block the everything. Thus, the DOM uses an event loop model, where callbacks are assigned to events. Such a model is also present in node.js too. Above, because setTimeout does not block, code after that call will continue to run without waiting the function we passed to setTimeout to get executed.
I'd suggest to study DOM in depth to get more comfortable with web front-end programming. You may use various search engines to find out cool documentation.

How do I create my own confirm Dialog?

The confirm box only has two options: ok and cancel.
I'd like to make one myself, so I can add a third button: save and continue. But the issue I currently don't know how to solve, is that: once the custom confirm dialog is up, how do I block the previously running script (or navigation) from running? and then how do I make the buttons return values for the confirmation?
my understanding of the confirm dialog box is this:
it's a visual boolean, that has the power to block navigation and scripts on a page. So, how do I emulate that?
If you want a reliable proven solution... Use jQuery... it'll work on every browser without worrying about crappy IE etc. http://jqueryui.com/demos/dialog/
In javascript, you don't stop while you're waiting for a user action : you set a callback (a function) that your dialog will call on close.
Here's an example of a small dialog library, where you can see how callbacks can be passed.
dialog = {};
dialog.close = function() {
if (dialog.$div) dialog.$div.remove();
dialog.$div = null;
};
// args.title
// args.text
// args.style : "", "error" (optionnel)
// args.buttons : optional : map[label]->function the callback is called just after dialog closing
// args.doAfter : optional : a callback called after dialog closing
dialog.open = function(args) {
args = args || {};
if (this.$div) {
console.log("one dialog at a time");
return;
}
var html = '';
html += '<div id=dialog';
if (args.style) html += ' '+args.style;
html += '><div id=dialog-title>';
html += '</div>';
html += '<div id=dialog-content>';
html += '</div>';
html += '<div id=dialog-buttons>';
html += '</div>';
html += '</div>';
this.$div=$(html);
this.$div.prependTo('body');
$('#dialog-title').html(args.title);
$('#dialog-content').html(args.text);
var buttons = args.buttons || {'Close': function(){return true}};
for (var n in buttons) {
var $btn = $('<input type=button value="'+n+'">');
$btn.data('fun', buttons[n]);
$btn.click(function(){
if ($(this).data('fun')()) {
dialog.close();
if (args.doAfter) args.doAfter();
}
});
$btn.appendTo($('#dialog-buttons'));
}
this.$div.show('fast');
shortcuts.on('dialog', {
27: function(){ // 27 : escape
dialog.close();
}
});
}
Two call samples :
dialog.open({
title: 'ccccc Protection Error',
text: 'There was an error related to cccc Protection. Please consult <a href=../cccc.jsp>this page</a>.',
style: 'error'
});
var ok = false;
dialog.open({
title: sometitle,
text: someHtmlWithInputs,
buttons: {
'OK': function() {
if (// inputs are valid) ok = true;
return true;
},
'Cancel': function() {
return true;
}
},
doAfter: function() {
if (ok) {
if (newvg) {
cccmanager.add(vg);
} else {
cccmanager.store();
}
if (doAfter) doAfter();
}
}
});
As specified by others, you may not need your own library if you just want to make a dialog.

Categories

Resources