How can I get the data attribute from a php variable?

后端 未结 2 2034
猫巷女王i
猫巷女王i 2021-01-16 00:29

I have a form that can delete records from a MySql database using ajax and jQuery. I\'m trying to get the jQuery to only select the relevant record passed to it and not just

相关标签:
2条回答
  • 2021-01-16 01:05

    First in your PHP do something like this, you add the data attributes to your delete button since you are not actually submitting a real form. I also moved the deleteReview class to the button.

    print '<button type="submit" class="deleteReview" data-id="'.$id.'" data-film-id="'.$film_id.'" data-username="'.htmlentities($username).'" class="btn btn-danger btn-xs pull-right">delete</button>';
    

    Then, in your jQuery, update click event callback like so:

    $(".deleteReview").click(function (e) {
        e.preventDefault();
        var username=$(this).data('username');
        var film_id=$(this).data("film-id");
        var id=$(this).data('id');
        /* the rest of your code */
    

    The data attributes become accessible easily with jQuery using $(this).data('some-attribute-name')

    0 讨论(0)
  • 2021-01-16 01:06

    I would recommend you to use data-* prefixed attributes to persists your data.

    HTML

     <div data-id="'.$id.'" data-username="'. $username.'" data-filmid="'.$film_id .'" class="deleteReview">
        <button type="submit" id="" class="btn btn-danger btn-xs pull-right">delete</button>
     <div >
    

    Then you can fetch it using .data(key)

    Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute

    Script

     //Delete Review
    $(document).ready(function(){
        //Need to get $id here.
        $(".deleteReview").click(function (e) {
            e.preventDefault();
            var username = $(this).data("username");
            var film_id = $(this).data('filmid');
            var id = $(this).data('id');
    
            ......
            return false;
        });
    });
    
    0 讨论(0)
提交回复
热议问题