Passing data by Jquery

2

I'm trying to pass some data via Jquery to another php page.

I create tag < a > via echo :

echo "<a id='".$feed_id."' class='like'> Teste LINK </a>";

• The variable $ feed_id should return a numeric ID (eg 1234)

I have the function:

$(document).ready(function(){
            $("#like").click(function(){
                var url = "like.php";

                var data = $("#like").attr("id");

                $.post(url,{postdata:data},
                function(result) {
                    $("#result").html(result); // Só pra verificar retorno
                });

            });

And I try to get the value of the variable in the page like.php:

    $data = $_POST['postdata'];

    echo $data;

I need some tips to make this code work, and if possible, improve it.

    
asked by anonymous 19.05.2015 / 00:31

1 answer

3

Vitor, here are some remarks about your code.

ID attribute

In the snippet below you define link ID attribute with a numeric value. However, it is not a good practice to define the value of the ID attribute as a number only, ideally to define it according to the most common variable name definition practices: The name of a variable must start with a letter or with a "_" (underline).

echo "<a id='".$feed_id."' class='like'> Teste LINK </a>";

I suggest:

echo "<a id='like".$feed_id."' class='like'> Teste LINK </a>";

#like selector

In the section that follows, you use the #like selector, this selector understands that the id of your element is like , whereas, in fact, like is the CSS class of the element. Then the correct selector would be .like .

$("#like").click(function(){ ...

I suggest:

$(".like").click(function(){ ...

Get the ID of the clicked element

Within the click event you make the following assignment:

var data = $("#like").attr("id");

I understand that the $("#like").attr("id") intent is to capture the element ID that was clicked .

I suggest (If you have met the suggestion regarding the ID attribute):

$this = $(this); // jQuery

var data = /^like(\d+)$/.exec($this.attr("id"))[1];

Otherwise:

$this = $(this); // jQuery

var data = $this.attr("id");
    
19.05.2015 / 04:33