Mylon James Marcell
Mylon James Marcell

Reputation: 23

Passing a value to PHP from jQuery Ajax

I'm trying to get a value back to PHP which I can work with and send to the database. I don't seem to be able to do that using the GET type of jQuery AJAX. Here's the PHP I'm using to catch the value:

<?php require_once("header.php"); ?>
<?php require_once("class.php"); ?>
<?php

//$month = $_POST['month'];
//$year = $_POST['year'];

$month = 8;
$year = 2013;
$numDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$empty = "<table class='box'><td>&nbsp</td></table>";

$cal = new calendar();
$cal->mkMonth($month);
$cal->emptyDays($empty, $numDays, $month, $year);
$cal->mkdays($numDays, $month, $year);

echo "</div>";


echo "<div id='jresult'>";
if (isset($_GET['id'])) {
   echo ($_GET['id']);
}

echo "</div>";
?>

Here's the jQuery...

$(document).ready(function(){
    $(".box").mouseenter(function(){$(this).css("background-color", "red");});
    $(".box").mouseout(function(){$(this).css("background-color", "transparent");});
    $(".box").click(function() {
        date_time = $(this).attr('id');
        console.log(date_time);
        $.ajax({
            type: 'GET',
            url: '/book.me/loop.php',
            data: "id=" + $(date_time).val(),
            success: function(data){
                alert('successful');
            }
        });
    });
});

I'm trying to pass in the id of the .box class element to the date_time variable which works, but it doesn't seem to be working when I call $_GET['id'] in PHP. I'm just getting an undefined value back.

Upvotes: 0

Views: 8784

Answers (4)

omma2289
omma2289

Reputation: 54619

If you want to send the id attribute, not the value, you can use

$(".box").click(function() {
    date_time = $(this).attr('id');
    $.ajax({
        type: 'GET',
        url: '/book.me/loop.php',
        data: "id=" + date_time,
        success: function(data){
            alert('successful');
        }
    });
});

Upvotes: 3

Shlomi Hassid
Shlomi Hassid

Reputation: 6596

you should set the data like this:

$(".box").click(function() {
    $.ajax({
        type: 'GET',
        url: '/book.me/loop.php',
        data: "id=" + this.id,
        dataType: 'html',
        data: { id: $(this).val() },
        success: function(data){
            alert('successful');
        }
    });
});

Upvotes: 2

rink.attendant.6
rink.attendant.6

Reputation: 46208

You can reference the clicked .box by using $(this):

$(".box").click(function() {
    $.ajax({
        type: 'GET',
        url: '/book.me/loop.php',
        data: {
            id: $(this).val()
        },
        success: function(data){
            alert('successful');
        }
    });
});

Upvotes: 2

jcubic
jcubic

Reputation: 66478

Try this:

$('#' + date_time).val()

Upvotes: 0

Related Questions