Taiga
Taiga

Reputation: 48

Jquery Ajax request with link id

I've already read a lot of tutorials and forum posts but for every more I read, I get more confused. I think my problem is very easy to solve... So, I have links with different Id's which I only want to have the number.

<a id="stream_1" class="change" href="javascript:void(0)">Stream1</a>
<a id="stream_2" class="change" href="javascript:void(0)">Stream2</a>
<a id="stream_3" class="change" href="javascript:void(0)">Stream3</a>

To get only the number I saw this code

$('[id^=strea_]').click(function() {
    var id = $(this).attr('id').replace(/strea_/g, '');

        /* Request to .php file */
        var request = $.ajax({
        url: "/request/ajax.php",
        type: "POST",
        data: { id : id },
        dataType: "html"
        });

      event.preventDefault();
      return false;
});

What I want to do now is: By clicking one of the links, I want the number given in the id to be send to a .php script, to change the content of a certain div

<?php
include '/var/www/jpanimes/scripts/php/connection/connection.php';
$streamId = $_POST['id'];

if($streamRequest = $con->prepare("SELECT link FROM stream WHERE id = ?"))
{
    $streamRequest->bind_param("i", $streamId);
    $streamRequest->execute();
    $streamRequest->bind_result($streamData);
    $streamRequest->fetch();
    $streamRequest->close();
}

echo $streamData;
?>

Upvotes: 0

Views: 1687

Answers (2)

Adrian Preuss
Adrian Preuss

Reputation: 3113

try that. You make an ajax request but you dont specific, what happens after the ajax request is complete. Here you must set a success method to handle the output.

$('[id^=strea_]').click(function() {
    var id = $(this).attr('id').replace(/strea_/g, '');

    /* Request to .php file */
    var request = $.ajax({
        url:    '/request/ajax.php',
        type:   'POST',
        data:   {
            id: id
        },
        dataType: 'html',
        success: function(new_html) {
            // Insert the HTML into an Element
            $('div.content').html(new_html);
        }
    });

    event.preventDefault();
    return false;
});

Upvotes: 1

Adrian Preuss
Adrian Preuss

Reputation: 3113

On the click event you can get the ID:

 $('[id^=strea_]').click(function() {
      var id = $(this).attr('id').replace(/strea_/g, '');
 });

Another solution is to use data attributes like that:

 $('a.open_stream').on('click', function(event) {
      var id = $(this).data('myOwnID');

      /* handle here your id */

      event.preventDefault();
      return false;
 });

 <a class="change open_stream" href="#" data-myOwnID="1">Stream1</a>

Upvotes: 4

Related Questions