Passing data through Jquery

Asked

Viewed 155 times

2

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

I create the tag < a > via echo:

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

• The $feed_id variable must return a numeric ID (ex: 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 on the like.php page:

    $data = $_POST['postdata'];

    echo $data;

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

  • 2

    And what’s the problem?

1 answer

3

Vitor, here are some remarks about your code.

Attribute ID

In the excerpt below you define ID attribute of the link with a numeric value. However, it is not a good practice to define the value of the ID attribute as just a number, the ideal is to define it according to the practices for defining the most common variable names: The name of a variable should start with a letter or with "_" (underline).

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

I suggest:

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

Selector #like

In the following section, you use the selector #like, this selector understands that the id of your element is like, while actually, 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 clicked element ID

Within the event click you make the following assignment:

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

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

I suggest (if you have answered 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");
  • 2

    Good answer! +1 regarding "Get the clicked element ID" I think this.id serves because inside the Event Handler the this will already be the element. Just a hint, I will delete when you read.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.