Solved

HTML code passed to client with AJAX with javascript in it is not firing.

Posted on 2015-01-07
19
189 Views
Last Modified: 2015-01-09
Hi,

I have an Ajax function on a web page that calls a dataset that I'm passing to the client in an HTML string. There are links that call a Jquery function to open a lightbox dialog box which populates with data. When the page is loaded for the first time, the links work, but when the html table (records) load from the Ajax, the javascript in the links doesn't work.

Part of the problem is that the lightbox is opened with a class designation inside the anchor tag, but if I include Javascript in the href attribute, it doesn't fire, but it does in the onclick event (see example below). Huh? Can anyone help me understand what's going on?

Thanks,
Steve



    <a href="javascript:showAlert();" class="pop">Link1</a>
    <a onclick="showAlert();" href="javascript:void(0);" class="pop">Link2</a>




<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="javascript/jquery.lightbox_me.js" type="text/javascript" charset="utf-8"></script>
    <title>Lightbox_me - Stupidly Simple Lightboxing - The jQuery lightbox plugin for people who know what they're doing.</title>
    <script type="text/javascript" charset="utf-8">
        $(function() {
            function launch() {
                 $('#sign_up').lightbox_me({centered: true, onLoad: function() { $('#sign_up').find('input:first').focus()}});
            }
           
            $('.pop').click(function(e) {
                $("#sign_up").lightbox_me({centered: true, preventScroll: true, onLoad: function() {
                    $("#sign_up").find("input:first").focus();
                }});
               
                e.preventDefault();
            });
        });
        function showAlert(){
            alert("Hello world");
        }
    </script>
    <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" title="no title" charset="utf-8">
   
</head>

<body>
   
    <a href="javascript:showAlert();" class="pop">Link1</a>
    <a onclick="showAlert();" href="javascript:void(0);" class="pop">Link2</a>
   
                   
    <div id="sign_up">
    Hello world hello world hello world.</span>
    <a id="close_x" class="close sprited" href="#">close</a>
    </div>

   </body>
</html>
0
Comment
Question by:tablaFreak
  • 11
  • 4
  • 4
19 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 40536543
Any click events in elements with class="pop" are triggering the jQuery event handler you have set up. However, the javascript you have in the href attribute of the first anchor is being cancelled by the e.preventDefault(); function in the event handler. The default action of an anchor is to execute whatever is in the href attribute. The onClick="showAlert()" in the second anchor triggers the showAlert function. This action is not affected by e.preventDefault(); because that's not the default action of an anchor.
0
 

Author Comment

by:tablaFreak
ID: 40536589
Thanks, Tom - that's helpful.

And I realize my real issue has more to do with something that's going on with maybe the Javascriptdeserializer I'm using.

If I include "<script type="text/javascript">alert('this is an alert');</script>" in the html string I'm sending to the browser, it fires when the page loads (since it's being sent as html with the whole page on load). But when the same string is passed into the page through Ajax, it doesn't fire (and nor do any of my links call their functions with javascript in the href attribute). Do you think  the html code is somehow getting encoded differently when it is deserialized? Here's the code I'm using:

var bulkproduct = Sys.Serialization.JavaScriptSerializer.deserialize(result);

Thanks a lot,
Steve
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 40536655
I'm getting beyond my pay grade with the deserialization question, but a few other thoughts occur to me.

1.) I'm trying to imagine a situation where I would have to send javascript in with an ajax request. Sounds like trouble. Why not just have the script as as part of the parent page already?

2.) I know eval() is considered a security risk, but I wonder if you wrapped that test alert in an eval function if that would cause it to trigger when the ajax loads. Just curious.

3.) Do you actually have function calls (like your test alert) that are part of the ajax data that you expect to fire automatically? Perhaps you need to hold all function calls until ajax "complete", i.e., $.ajax({ complete: function(){...} });

4.) You say function calls do not work when they are in the href attributes after ajax? Is that true even when e.preventDefault() is commented out?
0
 

Author Comment

by:tablaFreak
ID: 40536721
Hi Tom,

Thanks much for staying with me here - I'm not actually sending javascript code to the browser, just anchor tags that are referencing a javascript function on the page, such as <a href="javascript:callRecord(13);">link</a>. But those aren't firing. I'm hoping I can get this to work, since it's a pattern I'm using all over the site. For some reason, using the Jquery lightbox function is complicating matters.

And that's right, with e.preventDefault() commented out, those javascript links no workie workie.

Thanks much,
Steve
0
 

Author Comment

by:tablaFreak
ID: 40536739
Ah, correction - I am managing to get the javascript to fire from within the anchor tag, but it's not calling the Jquery lightbox element, which is references from the class designation:

<a href="javascript:showAlert();" class="popClick link11">


  <script type="text/javascript" charset="utf-8">
        $(function() {
            function launch() {
                 $('#sign_up').lightbox_me({centered: true, onLoad: function() { $('#sign_up').find('input:first').focus()}});
            }
           
            $('.pop').click(function(e) {
                $("#sign_up").lightbox_me({centered: true, preventScroll: true, onLoad: function() {
                    $("#sign_up").find("input:first").focus();
                }});
               
                e.preventDefault();
            });
        });
    </script>
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 40536887
I guessing that the mismatch between class="popClick" in the anchor and $('.pop') in the event handler is just a misprint in the post?
0
 

Author Comment

by:tablaFreak
ID: 40537006
Yes, that's right, the actual Javascript I'm using is

<script type="text/javascript" charset="utf-8">
    $(function() {
        function launch() {
            $('#popbox').lightbox_me({ centered: true, onLoad: function () { $('#popbox') } });
        }
        $('.popClick').click(function (e) {
            $("#popbox").lightbox_me({
                centered: true, preventScroll: true, onLoad: function () {
                    $("#popbox");
                  }});
            //e.preventDefault();
        });      
    });
</script>
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 40537107
This part doesn't look right (in bold). It's not a statement, just a jQuery selector:

$('#popbox').lightbox_me({ centered: true, onLoad: function () { $('#popbox') } });
0
 

Author Comment

by:tablaFreak
ID: 40537210
Hmmm, I have no idea - truth is, I don't know that much about how that code is working. Not sure how to tell.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 33

Expert Comment

by:Slick812
ID: 40538529
greetings tablaFreak, , hope I can help some, although there are VERY MANY coding ideas-rules that you are using here for Javascript and then for JQUERY syntax.

Here is what I think about for the <a> tag and the
      onclick="doSomething();"
or
      href="javascript:other(0);"

it is Bad idea to have both in a single element, as they are not needed, and are not meant to be read and interpreted by the browser (doing Both).

There were several many that I read , that said the  href="javascript:other();", should NOT be used, if other ways were available. So I always try and use the  onclick="doSomething();"  method, If you do not want the Link addy in <a> to go there, you add a false return, like this -
      <a onclick="showAlert(); return false;" href="#">Link2</a>

Please Notice that I have left out the -
     class="pop"
as In your HTML code there is NO CSS for anything , much less a CSS definition for that "pop" class

it is true that the JQUERY does a document scan for all elements with a class of "pop", and assigns a Click event to them. When javascript (or jquery) assigns a click event, it OVERWRITES (changes) any click events that were there before, so if the  onclick="showAlert();" as in <a> before, then it is no longer there after a javascript click assignment.

You will need to decide IF you want to use the code method of -
       <a onclick="showAlert(); return false;" href="#">Link2</a>
or
       <a class="pop" href="#">Link2</a>
, you can possibly use both methods, but you need to understand the how and why workings of both methods, to do that, I would guess.

as to the use of printing javascript in an Ajax return to the innerHTML of an element. DO NOT DO THAT!, if you need an Javascript changes, , then do it in the javascript of the Ajax Return function.
However, you can add any element event functions, like onclick, onmouseout, onblur, to the element like a return from ajax as -
     <div style="display:inline-block; padding:4px; border:3px outset #777;
         cursor:pointer;" onclick="adjust();">click me</div>

for a button click-able <div> that will NOT go to a href=

here is some code that you can look at and see if it gives you some Ideas, It is UNTESTED, so it may not work entirely , but notice I have left out the -
      $('.pop').click(function(e) {
altogether, and use the onclick="" method in elements. I have consolidated the identical code into a single function setLighbox()

<script>/* <![CDATA[ */
        $(function() {
            function launch() {
                setLighbox();
            }
 
        });


        function setLighbox(){
            $('#sign_up').lightbox_me({centered: true, 
                onLoad: function() $('#sign_up').find('input:first').focus()}});
        }

/* ]]> */</script>


<div style="display:inline-block; padding:4px; border:3px outset #777;
         cursor:pointer;" onclick="setLighbox();">click me</div>

 - <a onclick="setLighbox(); return false;" href="#">Set Light Box</a>

Open in new window

 
I hope this means something to help, ask questions if you need more info.
0
 

Author Comment

by:tablaFreak
ID: 40539194
Thanks a bunch, Slick for your thorough help there. Yes, my knowledge of Javascript, as you can see, has big holes in it.

A question I have, lightbox aside, is I'm trying to return a recordset with Ajax of an html string (a table of data) which has links in it which call other Ajax functions. Are you saying there isn't a way to do that, since by necessity, those links would have to include javascript function calls? (If there's any confusion, I'm not sending any javascript blocks back in the return string.) And if Jquery strips all elements of hrefs, then looks like I'm out of luck using that lightbox, since the page won't work otherwise.

And thanks for the code - I couldn't get it to work, not sure what the problem might be.

Here a more thorough inclusion of the lightbox code I'm using, below.

Thanks so much for your help.

Steve


<html>
<head>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="javascript/jquery.lightbox_me.js" type="text/javascript" charset="utf-8"></script>
    <title>Lightbox_me</title>
    <script type="text/javascript" charset="utf-8">
        $(function() {
            function launch() {
                 $('#sign_up').lightbox_me({centered: true, onLoad: function() { $('#sign_up').find('input:first').focus()}});
            }
           
            $('.pop').click(function(e) {
                $("#sign_up").lightbox_me({centered: true, preventScroll: true, onLoad: function() {
                    $("#sign_up").find("input:first").focus();
                }});
               
                //e.preventDefault();
            });
        });
        function showAlert(){
            alert("Hello world");
        }
</script>
<style>
   
.sprited {
    background: url(images/download_sprite.png) no-repeat;
    line-height: 1000px;
    overflow: hidden;
    display: block;
}
#sign_up {
    background: #FFF;
    border: 1px solid #536376;
    -webkit-box-shadow: rgba(0,0,0,.6) 0px 2px 12px;
    -moz-box-shadow:  rgba(0,0,0,.6) 0px 2px 12px;;
    padding: 14px 22px;
    width: 600px;
    height:800px;
    position: relative;
    display: none;
}
#close_x {
    width: 24px; height: 23px;
    overflow: hidden; line-height: 1000px;display: block;
    position: absolute; top: 5px; right: 5px;
    background-position: -387px -102px;
 }
</style>
   
</head>

<body>
   
    <a href="javascript:showAlert();" class="pop">popup</a>
                     
    <div id="sign_up">
    text text text</span>
    <a id="close_x" class="close sprited" href="#">close</a>
    </div>

   </body>
</html>
0
 

Author Comment

by:tablaFreak
ID: 40539201
Hi Slick - here's the lightbox javascript file.
Thanks.
jquery.lightbox-me.js
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 40539396
OK ,  I do not know where to start, you seem to not understand how these several things (AJAX, javascript, server code-return-string, jquery) can work together to get a working page.

You say - "And if Jquery strips all elements of hrefs" - That is NOT the case, I did not say that, you can have jquery-javascript, NOT change a single character in the server return string that gets placed into a the innerHTML of a page element. So if you send back from server this text -
      <a onclick="showAlert();" href="javascript:void(0);" class="pop">Link2</a>
that is exactly what goes into the page code base, and it will work just as if it was native ( not from ajax) in the page code.

The main point I was trying to make, is that you do NOT do correct javascript methods for adding and using element events, the click event for a <a> in this case.

I have looked at the code in your last posts, and I do not have time to read and analyze the  jquery.lightbox-me.js  javascript at this time, but to make a short explanation, I will say - IF you have a script procedure that sets a ONCLICK event, you should NOT have any other script call in that element for that event, onclick.

as here might show you, I have left out light box for now -
<!doctype html>
<html><head><title>jQuery tester</title>
<style>
body{background:#e3f7ff;}

.cl{background:#fd9; color:#c00; padding:2px;}
.opp{width:20em; background:#dfb; border:3px solid #00c; padding:9px; margin:9px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>/* <![CDATA[ */
$(function() {
$( "#chng" ).append("<br/>Added in the OnLoad function.");

  $('#clik').click(function(e) {
    e.preventDefault();
    $( "#chng" ).append("<br/>stuck on in the click function."); 
  });
});

/* ]]> */</script>
</head>
<body><h3 style="text-align:center;">jQuery tester</h3>
<hr>
<a href="#" id="clik" class="cl">click me</a>
<div id="chng" class="opp">Javascript operations shown here</div>
</body></html>

Open in new window


Now is you want to add an alert show for the on click , you DO NOT add anything to the <a> , , , as do NOT change to this -
    <a href="javascript:alert('alert me');" id="clik" class="cl">click me</a>

instead ADD any extra operations (alert in this case) to the onclick event from the jquery
    $('#clik').click(function(e) {
        e.preventDefault();
        $( "#chng" ).append("<br/>stuck on in the click function.");
        alert('alert me'); // add alert HERE, not in the element code
      });

I do NOT use a class search here as you did -
    $('.pop').click(
these are inefficient and can cause problems with crossed fuctioning if you want some elements with the "pop" class to NOT do ckicks,
It is better to use id as -
   $('#clik').click(
if you do not have but one element to click . .
(jquery can have several ID and or class to assign a click, look at the options for the   $('#clik')  method)

I did not do any light box or ajax here but -
AJAX is not so easy to understand, but is necessary these days for interactive web pages
0
 

Author Comment

by:tablaFreak
ID: 40539534
Hi Slick,

Thanks much for your input again - I think I'm just not strong enough in JQuery and Ajax to navigate all those complex conflicts, so I managed to find another lightbox that uses only css, very nice solution, and now there's no conflict with the Javascript I'm using. Here's a link to what I found:

http://www.corelangs.com/css/box/fulloverlay.html

And here's the HTML that shows it at work:

<!DOCTYPE html> <html >
<head>
<style type="text/css">
.box_button { width: 150px; padding: 10px; background-color: #FF8C00; box-shadow: -8px 8px 10px 3px rgba(0,0,0,0.2); font-weight:bold; text-decoration:none; }
#cover{ position:fixed; top:0; left:0; background:rgba(0,0,0,0.6); z-index:5; width:100%; height:100%; display:none; text-align:center; }
#popBox { position:absolute; top:25px; right:0;left:0;  width:800px; z-index:10;  margin:auto; display:none; background: #FFF; border:5px solid #cccccc; border-radius:10px; padding:50px 15px;
-webkit-box-shadow: rgba(0,0,0,.8) 0px 5px 24px;-moz-box-shadow:  rgba(0,0,0,.8) 0px 5px 24px;}
#popBox:target, #popBox:target + #cover{ display:block; opacity:2; }
.cancel { display:block; position:absolute; top:3px; right:2px; background:rgb(245,245,245); color:black; height:30px; width:35px; font-size:30px; text-decoration:none; text-align:center; font-weight:bold; }
</style>
<script type="text/javascript">

</script>
</head>
<body>

<div align="center"> <br><br><br><br> <a href="#popBox" class="box_button">Click here to Log In</a> </div>
<div id="popBox">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<a href="#" class="cancel">&times;</a> </div>
<div id="cover" > </div>
</body>
</html>
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40539549
??? , I do not understand ? The  jquery.lightbox_me.js  , works, I have just tested it. Now you show us some CSS overlay that shows a form. Sorry But I have no Idea what you hope to accomplish here, I do not know where you want to go, , as in , , what you need to do and the results you need to have after doing it. You can do overlay "modal" display, with hundreds of different add-ons , however, I can not know what to do or suggest for this, if I am just trying to get you to do basic jquery and basic javascript. This code you gave is UNALTERED code copied from the  http://buckwilson.me/lightboxme sight, and it is without any FORM or div in your code to even see if it works, you use the exact same ID as  '#sign_up' that is used in that example page, and yet there is NO id as '#sign_up'  in your code? ? ?

I do not know what to say or do? ? ?
0
 

Author Comment

by:tablaFreak
ID: 40540481
Hi Slick,

The problem I was having with the JQuery was the links in my Ajax return code weren't working, and you suggested it was because the JQuery code scanned all objects with the 'popClick ' class and removed the href attributes, if I followed you. (I figured I had to use a class, since each row in the Ajax html string had its own link and ID for its own Ajax call). I didn't send you the actual code I'm using since it's very long, and I hoped to get help with the core issue. Not seeing a way around that, when I found another lightbox solution that only used css, it solved the apparent jquery conflict, so now there's no need to resolve what was going on there. Thanks so much for your help.

Best,
Steve
0
 

Author Closing Comment

by:tablaFreak
ID: 40540484
Thanks so much!
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40540572
glad you got it to work! !
just a note - it is Important , when you display code here at EE that is more than 4 or 5 lines, you should place it in an EE code container. Please do this on your next posts here. You just click-touch the  Code reference point , on the Top of the "Post a Comment" user input box, and get the BB bracketed code inputs.

ALSO, the CSS modal you show uses a very NEW technique for browsers usin CSS click, and I know it is NOT backward compatible to MANY older browser versions, and is not supported in some new (current) browsers versions, so my view is that it is NOT a safe bet for web page use.
0
 

Author Comment

by:tablaFreak
ID: 40540673
Hi Slick - Thanks for the suggestions, and the heads-up on the browser issue - it's not a problem, since this is for an intranet site where we can set the browser version.
All the Best,
Steve
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now