Paul
Paul

Reputation: 201

Automatically change PHP variable based on select option (AJAX?)

Right now, I have variables that default to the current d/m/y, which is then popped into a mySQL query that displays all data from a table WHERE date='$dday' AND month='$dmonth' AND year='$dyear'.

$ddate = date("d");
$dmonth = date("m");
$dyear = date("Y");

Instead, I'd like to have a select box that will change the variables based on the option selected. So the default option for the Day select will be the current date, but if I change that to day 12 for example, I want the variable to change when the select option changes, and then re-query the database automatically. I'm assuming this would be done with AJAX.

Is what I'm talking about even possible? If the automation of the query adds a big layer of complexity, I'd be fine with just changing the variable and updating based on the press of a submit button.

I promise to take a break from asking questions and start answering some, if questions below my simple level are even asked.

Upvotes: 1

Views: 3242

Answers (3)

Lawrence Cherone
Lawrence Cherone

Reputation: 46650

Heres an example, ill leave you to do the query:

<?php 
//Some pseudo data kinda as your receive it from your query
$datafromSql = array(
array('id'=>1,'date'=>1,'month'=>1,'year'=>2012,'theData'=>'This is some data when the user select 1/1/2012'),
array('id'=>2,'date'=>2,'month'=>2,'year'=>2012,'theData'=>'This is some data when the user select 2/2/2012'),
array('id'=>3,'date'=>3,'month'=>3,'year'=>2012,'theData'=>'This is some data when the user select 3/3/2012'),
);

//Super simple API to access the data
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
    header('Content-Type: text/html');
    //pseudo code, really you would just format your query result   
    $return=array();
    foreach($datafromSql as $row){
        //Select all from array which match select choice
        if($row['date']==$_POST['day'] || $row['month']==$_POST['month'] || $row['year']==$_POST['year']){
            $return[]=$row['theData'].'<br />';
        }
    }
    //output, with a fancy horizontal rule
    echo implode('<hr />',$return);
    die;
}?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
function update(){
    $.post('./<?php echo basename(__FILE__)?>',
       {
        day:  $("#day").val(),
        month: $("#month").val(),
        year:  $("#year").val()
       },
    function(data) {
            $('#result').replaceWith('<div id="result"><h1>The Result:</h1>'+ data +'</div>');
    });
}

$(document).ready(function(){
    update();
});
</script>

</head>

<body>

<form id="dateform" >
 <p>Select Date: 
  <select size="1" name="day" id="day" onChange="update()">
  <?php foreach(range(1,31) as $i){echo '<option value="'.$i.'">'.$i.'</option>';} ?>
  </select>
  <select size="1" name="month" id="month" onChange="update()">
  <?php foreach(range(1,12) as $i){echo '<option value="'.$i.'">'.$i.'</option>';} ?>
  </select>
  <select size="1" name="year" id="year" onChange="update()">
  <?php foreach(range(2008,2012) as $i){echo '<option value="'.$i.'">'.$i.'</option>';} ?>
  </select>
 </p>
</form>

<p id='result'></p>

</body>

</html>

Upvotes: 0

LonelyWebCrawler
LonelyWebCrawler

Reputation: 2916

Yes, this is possible. jQuery even makes it easy.

  1. Create your <select> element and give it an ID so it can be used in jQuery.

  2. Add an event listener in jQuery that is fired when the <select> changes, like $("#date").change().

  3. In the event handler for the change event, get the current value of the <select>, and then use jQuery's AJAX $.post() function to send that data to a PHP file.

  4. In that PHP file, sanitize the data to prevent MySQL Injections, and then query the database for the new data.

  5. Use PHP's echo function to send back the data.

  6. In the jQuery $.post() callback function (third parameter), receive the echoed data and put it into a variable.

  7. Use jQuery to update your HTML with the data.

Upvotes: 1

Brian Glaz
Brian Glaz

Reputation: 15696

Both of the solutions you suggest would work. You can send the values from the select box to a php script using AJAX, or you could just submit the form and access them that way via $_POST or $_GET depending on your form method.

Upvotes: 0

Related Questions