how to send the value of an anchor with jquery ajax to php-ThrowExceptions

Exception or error:

I am trying to send to values of a couple of anchors with jquery to php file but i got no callback from the php script.

<div class="result"></div>

<a href="#" value="5" class="star">Star 5</a>
<a href="#" value="4" class="star">Star 4</a>
<a href="#" value="3" class="star">Star 3</a>
<a href="#" value="2" class="star">Star 2</a>
<a href="#" value="1" class="star">Star 1</a>

the jquery:

$('a').on('click', function(e) {
    e.preventDefault();

    var star = $(".star").val();

    $.ajax({
        url: 'process.php',
        type: 'POST',
        data: {
                star:star                           
                },

        success: function(data){
            $('.result').html(data);                        
        }       
    });
});

And the php (process.php):

if (isset($_POST['star'])) {        
    $star = $_POST['star'];
    echo $star;

}

what am i doing wrong?

What i want to achieve: click on Star 5, give me value “5” back.
Click on Star 4, give me value “4” back and so on…

How to solve:

value is not an accepted attribute for <a> tags, you can view available attributes at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

I would recommend:

<div class="result"></div>

<a href="#" data-value="5" class="star">Star 5</a>
<a href="#" data-value="5" class="star">Star 4</a>
<a href="#" data-value="5" class="star">Star 3</a>
<a href="#" data-value="5" class="star">Star 2</a>
<a href="#" data-value="5" class="star">Star 1</a>

<script>
$('a').on('click', function(e) {
    e.preventDefault();

    var star = $(this).data('value');

    $.ajax({
        url: 'process.php',
        type: 'POST',
        data: {star:star},
        success: function(data){
            $('.result').html(data);                        
        }       
    });
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *