Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    Regular Coder
    Join Date
    May 2008
    Posts
    446
    Thanks
    23
    Thanked 5 Times in 5 Posts

    get id value of selected element in prototype

    So I am new to prototype but have used javascript and jquery quite a bit.

    Currently I am trying to send an ajax call using ajax.request but am failing to get the id value of the of the selected html element.

    >> get selected html element upon click event using name attribute (there will be multiple of these <a> with the same name value)
    >>get id value of the current <a> which was clicked on
    >> pass id value to php for processing

    Here is my method of doing it:

    Code:
    <a href="#" name="anchor_name" id="1">1st value</a>
    <a href="#" name="anchor_name" id="2">2cd value</a>
    <a href="#" name="anchor_name" id="3">3rd value</a>
    
    <script>
        
        document.observe("dom.loaded", function(){
           $('[name=anchor_name]').observe("click", function(evt){ 
              var id_value = this.id;
              new Ajax.Request('http:domain.com?id='+id_value, {
                  method: "GET",
                  onSuccess: function(response) {
                      // give me my content
                  },
                  onFailure: function(response) {
                      // tell me why it failed
                  }
              } ); 
           });
           
           
        });
        
    </script>

    It seems my problem is how I am trying to target the specific id value which the user clicked on.
    This is how I am used to doing it jquery and I was able to find a straight answer online, so I tried and it didnt work. Any ideas, or anything else I am missing to make this ajax call succeed?

    Thanks a lot

  • #2
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Id's cannot start with a number. Although HTML5, and some browsers, will tolerate this, I wouldn't recommend it.

    If an anchor tag has both a name and an id then they should be the same. And two anchor tags should not have the same name.

    Your function call needs to 'return false' to prevent the link from being followed (unless prototype cancels this automatically - but I know nothing about prototype).

    You should encodeURIComponent(id_value) when appending it to the url.

    I think you should be careful not to assume that everything works the same in prototype as jQuery - they don't. For example, I believe $() uses id's but $$() is for (css/attribute) selectors.

    As I say, I know nothing about prototype, but was using my old mate Google
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #3
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    This presentation might be worth a look. It's a bit old but still looks useful.

    BTW You might use $(this) rather than just this, although for your code sample they are probably the same object.

    And, I believe it is: dom:loaded
    Last edited by AndrewGSW; 08-22-2012 at 11:58 PM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #4
    Regular Coder
    Join Date
    May 2008
    Posts
    446
    Thanks
    23
    Thanked 5 Times in 5 Posts
    Thanks for the reply. I will make adjustments about id values.

    You say name attributes should not be duplicated, why does javascript's selector (getElementByNames) return an array unless it was specifically designed to expect more than one name attribute to be found?

    Would you have a better suggestion of having multiple html elements be assigned to react to a similar click event but narrow down to itself based on its individual id value?

    My one thought would be to run a javascript onclick="" and simply pass the id value as a parameter.

    onclick="runAjax(id_value)"

    <script>
    function runAjax(id_value){
    var encoded_id = encodeURIComponent(id_value);
    new Ajax.Request('http:domain.com?id='+encoded_id, {
    method: "GET",
    onSuccess: function(response) {
    // give me my content
    },
    onFailure: function(response) {
    // tell me why it failed
    }
    } );
    }
    </script>


    I have mixed javascript and jquery like this in the past with usually no troubles. It certainly would clear up trouble of accessing the id value to pass to php.
    Thoughts?

  • #5
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    You say name attributes should not be duplicated, why does javascript's selector (getElementByNames) return an array unless it was specifically designed to expect more than one name attribute to be found?
    Elements such as radio buttons and checkboxes can have the same name, but their usage for anchor elements is different. For these the name is (used to be) the target for links. Ids are now used to target links which is why, I assume, the names and ids must be the same. Ids must always be unique, but anchor-names have to be as well - otherwise, where would a targetted-link arrive?!

    Would you have a better suggestion of having multiple html elements be assigned to react to a similar click event but narrow down to itself based on its individual id value?
    If the elements are in the same location I would use li's, otherwise a class, or put all the elements in a DIV with a specific id. [One (sophisticated) way to work with li's is to attach the click event to the ul and delegate the event; that is, examine the event object's target element to determine which li was clicked. But you might want to keep it simple for the moment.]

    There is no problem mixing JS with a framework - I do this all the time . But you mentioned jQuery rather than prototype: I trust you are not trying to use both frameworks at the same time?!

    Using an HTML attribute such as

    Code:
    onclick="runAjax(this)"
    is a backward step. I recommend spending more time studying the prototype docs . But, hey, it's your code!
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #6
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    BTW I tried to run a version of your code but couldn't get past document.observe: Firebug told me there was no such method
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #7
    Regular Coder
    Join Date
    May 2008
    Posts
    446
    Thanks
    23
    Thanked 5 Times in 5 Posts
    So now I am unit testing outside my app while I am not getting any errors, I still get no results.

    My only thought as to why you're getting the document.observe non function error is maybe the prototype library is not loaded properly. I got the same error until I got library loaded, then it went away.

    Figured out the dom.loaded needed to be dom:loaded with a colon not a period separating them.

    So after reading the docs more and watching a video tut on it Here is what I have:

    Code:
    <a href="javascript:void(0);" class="task_report_id" id="1" >Full report</a>
    
    
    <script>
    	
    	document.observe("dom:loaded", function(){
           $$('a.task_report_id').observe("click", getTaskReport);
    	   
    	   function getTaskReport(event){
    		alert('anchor clicked');
    		}
           
        });
    </script>
    A simple alert upon click event is all.

    Here is the docs I read up on about it in case you are feeling ambitious
    http://api.prototypejs.org/dom/dollar-dollar/
    http://api.prototypejs.org/dom/Event/



    Thanks a lot

  • #8
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Figured out the dom.loaded needed to be dom:loaded with a colon not a period separating them.
    Erm, well done

    href="javascript:void(0);" is deprecated so I'm not sure why you've introduced it.

    And I see you are ignoring my advice about ids beginning with (being only) a number.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #9
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    BTW I managed to get past 'observe' but now I'm told that 'attachEvent' (coded in the prototype library) doesn't exist, even when running in IE. So I'm afraid I'm going to assume that prototype is broken. But good luck!
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #10
    Regular Coder
    Join Date
    May 2008
    Posts
    446
    Thanks
    23
    Thanked 5 Times in 5 Posts
    Thanks for the help,

    href="javascript:void(0);" is deprecated? so what would be a good alternative to killing that ugly jump to the top of the page when running javascript on an <a> click event?

    The id value issue, I'm simply just trying to get prototype to work for me at the moment.

    Seeing that prototype doesnt have a dedicated forum or ample video tutorials on youtube like most popular frameworks and the trouble I am having with it so far.... I may try to

    a. rip out prototype from my platform and insert jquery (would be a lot of work, and begs for bugs)
    b. write a javascript ajax function or find a javascript ajax class that doesnt conflict with prototype.


    B seems like the better choice here, and just use CSS3 for my simple animations.

    Thanks a lot for the help

  • #11
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    You can just use href="#" as you had originally.

    Provided that attaching the prototype library doesn't cause any error message - which it shouldn't!! - you can just ignore it pro-tem, and use JavaScript.

    Handling ajax via standard JS would be similar to the following, but you may want to fill in some gaps in the code

    Code:
    function using_ajax(get_var) {
        var ajax = false;
    
        if (window.XMLHttpRequest) {
            ajax = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e1) {
                try {
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e2) {
                    // Doh!
                }
            }
        }
        if (ajax) {
            ajax.open('get', 'somefolder/somefile/somepage.extn?=' + 
                encodeURIComponent(get_var));
            ajax.onreadystatechange = handle_change;
    
            ajax.send(null);
        } else {
            // do something..
        }
    }
    
    // Function that handles the response.
    function handle_change() {
        // if everything's ok
        // status == 0 (local) 200 (live)
        if ((ajax.readyState == 4) && (ajax.status == 200)) {
            if (ajax.responseText && ajax.responseText != '') {
                    // do something exciting..
            }
        }
    }
    Added: You can perform animation with JS (of course) and perhaps find some code to do this. Personally, I would leave the animations for a while until you either manage to get prototype working or decide to go with jQuery. Otherwise you'll end up having to re-write a lot of code. That is, re-writing the ajax bits is straight-forward, but the animations would involve a bit more work!
    Last edited by AndrewGSW; 08-24-2012 at 07:08 PM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •