Vic
Vic

Reputation: 1

Pass Jquery variables to PHP using AJAX

I'm trying to make an app where if you click on a div, the data-id will be put into a variable, which will give PHP the select parameters to look for. Here's my code to better explain it.

HTML:

<div class="box" data-id="caption"></div>

JQuery:

$('.box').click(function () {
        var caption = $(this).data('id');
});

After Googling I found the best way to do this is through AJAX, which I then proceeded to try:

$.ajax({
    url: 'index.php',
    type: 'GET',
    dataType: 'json',
    data: ({ caption }),
    success: function(data){
        console.log(data);
    }, error: function() {
        console.log("error");
    }
});

However, this doesn't seem to work. If there's a better way to do what I mentioned above, I'm open to new ideas.

EDIT

Here is my PHP code.

if(isset($_GET['caption'])){
    echo $caption;
    $select = "SELECT * FROM pics WHERE text = '".$caption."'";
    }
?>

Upvotes: 0

Views: 45

Answers (1)

atefth
atefth

Reputation: 1623

Look through the api at jQuery.

Your data key should contain a json object -

$.ajax({
    url: 'index.php',
    type: 'GET',
    dataType: 'json',
    data: {caption: caption},
    success: function(data){
        console.log(data);
    }, error: function(error) {
        console.log(error);
    }
});

Upvotes: 2

Related Questions