Pass parameter via jquery with href

0

I have a table with automatically generated links and values being passed via json.

The link returns the correct values being generated using PHP.

<li>
    <a href='phpProcess/showFormDelegationPr.php?prId="+item.pr_id+"' class='link-form-delegation' id='show-form-delegation'>
        <i class='fa fa-user'></i> &nbsp; Delegar
    </a>
</li>

I want to pass values to PHP using jquery, but I'm not succeeding.

I tried the following code:

$("#consult").on("click", ".link-form-delegation", function(e){
    e.preventDefault();
    $.ajax({
        url: $("#show-form-delegation").attr("href"),
        type: 'GET',
        success: function(data){
            alert(data);
        }
    });         
});

The problem is that for all rows in the table the alert always shows the return value of the first row of the table.

    
asked by anonymous 01.02.2015 / 16:39

2 answers

2

As Julian mentioned you have repeated IDs. When you use:

url: $("#show-form-delegation").attr("href"),

This will return the href of the first element with this ID. Even though there is more, it only returns the first one because the ID must be unique.

To work around this problem (which you have to resolve on the server side) you can use this in the element that received the click, which I assume is the one you want to read href . You will have to reference it in a variable because you can not pass it directly to .ajax() because it will be read in another scope context.

So, I think what you're looking for is:

$("#consult").on("click", ".link-form-delegation", function(e){
    e.preventDefault();
    var url = $(this).attr("href"); 
    // ou usar var self = this; e depois usar ": $(self).attr("href"),"
    $.ajax({
        url: url,
        type: 'GET',
        success: function(data){
            alert(data);
        }
    });         
});

Note that if there are too many #consult duplicates you have to change that and use classes, or only $(document).on('click', ... to play by insurance.

    
01.02.2015 / 19:37
1

This happens because you are getting the value of a through id, and all your a s has the same id (which sucks, id must be unique). You are adding the event to the element itself, so you can refer to the element rather than looking for the id. Remove the html ids and make the request do so:

$("#consult").on("click", ".link-form-delegation", function(e){
    e.preventDefault();
    var url = $(this).attr("href"); 
    $.ajax({
        url: url,
        type: 'GET',
        success: function(data){
            alert(data);
        }
    });         
});
    
01.02.2015 / 17:04