Ask your JavaScript questions! Pay money and get answers fast! (more info)

Why is this Javascript never triggered? JavaScript

  • SOLVED

Frustrating. Look at the modal that appears here:

http://www.shermanstravel.com//?refer=D25-adblade_2010_10_20&t25_modal_show=1&t25_modal_guide=1101966

I'm trying to control the Javascript that gets loaded when that modal loads. I've been adding alert() statements to see how far the code gets. This is the file that gets loaded (on dev, not the live site):



<script type="text/javascript" charset="utf-8">

alert('5hi');


</script>

sdjf;lksjdf;alkdfj;asldkfja;sldkfja;sldkfjas;df
asdfajlsdkfj;alsdkjf
asdfl;kajsd;flkaj
asdfl;akjsd;flkajsd;flkj
a;laksjdf;laskdj

<style type="text/css" media="screen">
#top25_signup{font:12px Arial;margin:0 10px;}
#top25_signup .left{float:left;width:310px;}
#top25_signup .right{float:left;margin:13px 0 0 50px;}
#top25_signup .left #logo{text-align:center;margin:20px 0;}
#top25_signup .left #headers{color:#004F9E;}
#top25_signup .left #headers h1{font-size:18px;text-align:center;font-weight:bold;margin-bottom:15px;}
#top25_signup .left #headers h1.small{font-size:13px;}
#top25_signup .left #headers p{text-align:center;font-size:13px;color:#333;font-weight:bold;}
#top25_signup .left #headers p.large{font-size:18px;}
#top25_signup .left #headers ul{padding-left:15px;}
#top25_signup .left #headers ul li{margin:5px;list-style:disc outside;}
#top25_signup .left form{margin-top:35px;}
#top25_signup .left form h2{font-size:14px;color:#489EE1;margin:0 0 10px 3px;font-weight:bold;}
#top25_signup .left form input.text{font-size:11px;width:300px;padding:2px;margin-bottom:8px;}
#top25_signup .left form .close{float:right;margin:8px;}
#top25_signup .left form .close a{color:#666;}
#top25_signup .left form .close a:hover{color:#000;}
#top25_signup .left form .button{float:right;}
#top25_signup .left form .button input{width: inherit;}
#top25_signup .left #footer{font-size:10px;color:#666;text-align:center;margin-top:30px;}
#top25_signup .left #footer a{color:#999;}
#top25_signup .left #footer a:hover{color:#000;}
#top25_signup .placeholder{color:#666;}
#top25_signup .clear{clear:both;}
</style>

<div id="top25_signup">

<div class="left">
<div id="logo">
<img src="http://i.stcdn.net/top25/signup2/25Logo.gif" width="169" height="55" />
</div>

<div id="headers">
<? if (isset($dealTitle)): ?>
<h1 class="small">Find out how to book this deal:</h1>
<p class="large"><?= $dealTitle ?></p>
<? elseif (isset($travelGuideTitle)): ?>
<h1 class="small">Read Expert Advice &amp; Get Our Top Picks</h1>
<p class="large"><?= $travelGuideTitle." Travel Guide" ?></p>
<? elseif (isset($snapshot)): ?>
<p><?= $snapshot['Deal']['display_title']; ?></p>
<h1>Find out how to book this deal:</h1>
<? else: ?>
<h1>Save Up To 70% On Travel</h1>
<ul>
<li>Our editors screen hundreds of deals each week</li>
<li>Flight, cruise, hotel, car rental &amp; vacation packages</li>
<li>Worldwide travel destinations</li>
</ul>
<? endif ?>
</div>

<form id="st_email_form" action="/top25/save_signup" method="post">

<h2>Sign up for our Top25 Deals email:</h2>

<input name="primary_email" id="primary_email" maxlength="100" title="Please enter a valid email address" class="text" placeholder="Email address..." />
<input name="postal_code" id="postal_code" maxlength="10" class="text" title="Please enter a valid zip code" placeholder="Zip code..." />

<div>
<div class="button">
<? if (isset($dealTitle)): ?>
<input type="image" src="http://i.stcdn.net/top25/signup2/get_my_deal.png" />
<? elseif (isset($travelGuideTitle)): ?>
<input type="image" src="http://i.stcdn.net/top25/signup2/get_my_guide.png" />
<? else: ?>
<input type="image" src="http://i.stcdn.net/top25/signup2/sign_up.png" />
<? endif ?>
</div>
<div class="close">
<a href="#" class="nothanks">No Thanks</a>
</div>
<div class="clear"></div>
</div>

</form>

<div id="footer">
<a href="http://www.shermanstravel.com/privacy" target="_blank" class="no_modal_signup">Privacy Policy</a> |
<a href="http://www.shermanstravel.com/terms" target="_blank" class="no_modal_signup">Terms of Use</a>
</div>

</div>
<div class="right">
<img src="http://i.stcdn.net/top25/signup2/partners_no_bg.gif" width="168" height="352" />
</div>

<div class="clear"></div>



<?
//get the base host name
$urlArray = explode ( '.' , $_SERVER["SERVER_NAME"] );
$rootHost = $urlArray[count($urlArray)-2] . '.' . $urlArray[count($urlArray)-1];
?>


</div>





<script type="text/javascript" charset="utf-8">

alert('h3i');

</script>






<script type="text/javascript" charset="utf-8">

alert('h8888i');

$(document).ready(function() {

if ($.getUrlVar('t25_modal_hst') == 1) $('#top25_signup .close').hide();

$('#top25_signup .close .nothanks').click(function(){
$.cookie('ST_top25_signup_ajax_modal_opt_out', '1', { path: '/', domain: '.<?= $rootHost; ?>', expires: 90 });
Omniture.trackModalNewsletterSignupWindowOptout();

tb_remove();
if ($.getUrlVar('t25_no_rd') == 1) {
return false;
} else if (window.st_url_forward != undefined) {
$(this).attr('href', window.st_url_forward);
$(this).attr('target', window.st_url_forward_target);
return window.st_url_forward != undefined;
} else if ($.getUrlVar('t25_modal_show') == 1) {
if ($.getUrlVar('t25_modal_guide') != undefined) {
$(this).attr('href', '<?= $travelGuideUrl ?>');
} else if ($.getUrlVar('t25_modal_deal') != undefined) {
$(this).attr('href', '<?= $this->TrackedLink->dealUrl($deal, array('sitePageId' => 1)) ?>');
} else {
return false;
}
return true;
}

return false;
});


$('#st_email_form').submit(function(){
var zip = $(this).find('#postal_code').val(),
email = $(this).find('#primary_email').val(),
regex = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;

if (!regex.test(email)) {
alert("Please input a valid email address!");
$(this).find('#primary_email').focus();
return false;
}

if (isNaN(zip) || (zip.length != 5)) {
alert('Please enter a valid 5-digit postal code');
$(this).find('#postal_code').focus();
return false;
}

var ajaxResponseURL = (location.href.indexOf('/blogs/') != -1) ? '/ajax-response.php' : '/top25/save_signup/';
var queryStr = location.href.replace(/^[^\?]+\??/,'');

$.post(ajaxResponseURL, { zip: zip, email: email }, function(result){
if (result.success) {
tb_remove();
$('body').after('<div id="hiddenAjax" style="display:none"></div>');

// We need to wait a bit for IE8 ...
window.setTimeout(function () {
if (result.existing_subscriber == 'yes') {
$("#hiddenAjax").load('/top25/you_are_already_a_subscriber_ajax/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);
} else {
$("#hiddenAjax").load('/top25/interests_address_form/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);
}
} else {
alert('Your Email or Zip code is not valid');
}
}, 'json');

return false;
}); //end submit

var i = document.createElement('input');
if ('placeholder' in i) {
// do nothing
} else {
var isPassword = function(input) {
return $(input).attr('realType') == 'password';
}

var valueIsPlaceholder = function(input) {
return input.value == $(input).attr('placeholder');
}

var showPlaceholder = function(input, loading) {
if (input.value == '' || (loading && valueIsPlaceholder(input))) {
if (isPassword(input)) {
try {
input.setAttribute('type', 'input');
} catch (e) { }
}
input.value = $(input).attr('placeholder');
$(input).addClass('placeholder');
}
}

var hidePlaceholder = function(input) {
if (valueIsPlaceholder(input) && $(input).hasClass('placeholder')) {
if (isPassword(input)) {
try {
input.setAttribute('type', 'password');
input.focus();
} catch (e) { }
}

input.value = '';
$(input).removeClass('placeholder');
}
}

$('input[placeholder]').each(function(index) {
if ($(this).attr('type') == 'password') {
$(this).attr('realType', 'password');
}

showPlaceholder(this, true);

$(this).focus(function() { hidePlaceholder(this); });
$(this).blur(function() { showPlaceholder(this, false); });
});
}

});
</script>


<div id="pixel-tracking_html">
<?php // $this->element('pixels/tool') ?>
</div>

<?php // $this->element('omni') ?>




This gets called:

alert('5hi');

and this:

alert('h3i');

but not this:

alert('h8888i');

And yet a function seems to get attached to the form, for execution on submit. What the hell?

Why is alert('h8888i'); not getting called? Where is the form.submit() being set?

Answers (3)

2011-08-13

Christianto answers:

Sir,

there are code that might turn error regarding setTimeout, on part ajax when form #st_email_form submitted:

$.post(ajaxResponseURL, { zip: zip, email: email }, function(result){
if (result.success) {
tb_remove();
$('body').after('<div id="hiddenAjax" style="display:none"></div>');

// We need to wait a bit for IE8 ...
window.setTimeout(function () {

if (result.existing_subscriber == 'yes') {

$("#hiddenAjax").load('/top25/you_are_already_a_subscriber_ajax/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);

} else {

$("#hiddenAjax").load('/top25/interests_address_form/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);

}
} else {
alert('Your Email or Zip code is not valid');
}
}, 'json');

Separating setTimeout function & closing tag base on certain condition may cause this error, maybe by adding different setTimeout to each will make it work.

$.post(ajaxResponseURL, { zip: zip, email: email }, function(result){
if (result.success) {
tb_remove();
$('body').after('<div id="hiddenAjax" style="display:none"></div>');

if (result.existing_subscriber == 'yes') {

// We need to wait a bit for IE8 ...
window.setTimeout(function () {
$("#hiddenAjax").load('/top25/you_are_already_a_subscriber_ajax/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);

} else {

// We need to wait a bit for IE8 ...
window.setTimeout(function () {
$("#hiddenAjax").load('/top25/interests_address_form/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);

}

} else {
alert('Your Email or Zip code is not valid');
}
}, 'json');


Or put all inside single setTimeout function.

$.post(ajaxResponseURL, { zip: zip, email: email }, function(result){
if (result.success) {
tb_remove();
$('body').after('<div id="hiddenAjax" style="display:none"></div>');


// We need to wait a bit for IE8 ...
window.setTimeout(function () {

if (result.existing_subscriber == 'yes') {

$("#hiddenAjax").load('/top25/you_are_already_a_subscriber_ajax/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});

} else {

$("#hiddenAjax").load('/top25/interests_address_form/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});

}

}, 100);

} else {
alert('Your Email or Zip code is not valid');
}
}, 'json');

Hope this help..


Lawrence Krubner comments:

But would an issue with settimeout() explain why the 2nd alert() does not appear:

<script type="text/javascript" charset="utf-8">

alert('h3i');

</script>





<script type="text/javascript" charset="utf-8">

alert('h8888i');

$(document).ready(function() {


Why does alert('h3i'); appear, but not alert('h8888i'); ?

I'm testing with FireFox.


Christianto comments:

IMO, its not about setTimeout but its about syntax error.
As you already know, each <script> tag will be interpreted independently but connected each other. So if error occur it won't affect other code on unless there are required global variable/object is missing in other code on another <script> block.

And syntax error is different with runtime error in the way it stop the script. To make it clear, please check code below and run it on your browser.

<script type="text/javascript" charset="utf-8">
alert('h3i'); // won't run
/**
illegal character occur, syntax error
'h3i' will not being output although it run before the error..
*/
%
</script>


<script type="text/javascript" charset="utf-8">
/**
Without jQuery
*/

alert('h8888i without jQuery'); // working

/**
missing variable/object occur, runtime error
'h888i' will still being output since it run before the error..
but 'What??' will not being output..
*/
alert(good);
alert('What??'); // will not run..
</script>


<script type="text/javascript" charset="utf-8">
/**
With jQuery
*/
alert('h8888i with jQuery'); // working

jQuery(document).ready(function(){
/**
missing variable/object occur, runtime error
'h888i' will still being output since it run before the error..
but 'What??' will not being output..
*/
alert(good);
alert('What??'); // will not run..
});
</script>

Hope this help, thanks


Christianto comments:

And in your code, the error appear when the closing tag of setTimeout is being separated with conditional block, which I think the way browser interpreted is different with server side language (like php).


Christianto comments:

But honestly, if the submit event is being set without a problem although there is syntax error, it hard find where it comes from..

I try to run it in my browser with some modification, just to make sure the submit event is attach to the element, but I found it won't attach in my part. The script just stop since there is error on setTimeout that I mention.

But when I change the code to fix the syntax, the submit event is being set to the element.


Lawrence Krubner comments:

Interesting. I suspect the form.submit() is being set by some other code block, which I have not yet found.


Lawrence Krubner comments:

When I look in the error log on FireFox, there is nothing there.


Christianto comments:

Since my goal to test if the submit event is attach, I stripped code by only put the submit function and it produce the error..

<script type="text/javascript" charset="utf-8">
alert('h8888i');
$(document).ready(function() {

$('#st_email_form').submit(function(){

var ajaxResponseURL = (location.href.indexOf('/blogs/') != -1) ? '/ajax-response.php' : '/top25/save_signup/';
var queryStr = location.href.replace(/^[^\?]+\??/,'');
var zip = '17700',
email = '[email protected]';

$.post(ajaxResponseURL, { zip: zip, email: email }, function(result){
if (result.success) {
tb_remove();
$('body').after('<div id="hiddenAjax" style="display:none"></div>');

// We need to wait a bit for IE8 ...
window.setTimeout(function () {

if (result.existing_subscriber == 'yes') {

$("#hiddenAjax").load('/top25/you_are_already_a_subscriber_ajax/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);

} else {

$("#hiddenAjax").load('/top25/interests_address_form/?'+queryStr, function(){
tb_show('', '#TB_inline?width=560&height=190&modal=true&inlineId=hiddenAjax', false);
});
}, 100);

}

} else {
alert('Your Email or Zip code is not valid');
}
}, 'json');

return false;

}); //end submit

});
</script>


In your live site, I found there are 2 event handler that target the same element #st_email_form which is your form submit function, both look similar.
on firebug the location of the script
http://www.shermanstravel.com/event/seq/3
or
http://www.shermanstravel.com//?refer=D25-adblade_2010_10_20&t25_modal_show=1&t25_modal_guide=1101966/event/seq/3


Lawrence Krubner comments:

Thanks much. I do not really understand why, the settimeout was the main aspect of the problem. And there was a syntax problem, as you said, which for some reason did not show up in the FireFox error console.

Thanks again.

2011-08-12

Julian Drei├čig answers:

Well, it seems the form submit handler is set via jQuery starting with the line
$('#st_email_form').submit(function() {...
I can't see why thealert('h8888i') should not be called. Maybe you have some illegal characters in your file, like protected spaces or wrong line ending encodings?


Lawrence Krubner comments:

Possibly, but I'm using a simple Linux text editor (Kate) and uploading to a Linux server (CentOs) so I'm not sure where a problem with line endings might arise. Anyway, there is a function set for the form.submit(), which seems to be below my alert(), so if the form.submit() is called, then my alert() should be called, unless the form.submit() is actually being called elsewhere.

2011-08-12

Jarret Minkler answers:

Try using console.log instead, also try to put an alert/log inside the doc ready func. See what happens then, can't really tell without running the code on dev and checking firebug/chrome with the rest of the code that is running.


Lawrence Krubner comments:

Okay, on my dev site, I added an alert to doc.ready():

<script type="text/javascript" charset="utf-8">

alert('h3i');

</script>






<script type="text/javascript" charset="utf-8">

alert('h8888i');

$(document).ready(function() {


alert('inside of doc.ready()');


if ($.getUrlVar('t25_modal_hst') == 1) $('#top25_signup .close').hide();



However, the alert('h3i') is still the last alert that appears on my screen.