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.
Yes, this is possible. jQuery even makes it easy.
Create your <select> element and give it an ID so it can be used in jQuery.
Add an event listener in jQuery that is fired when the <select> changes, like $("#date").change().
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.
In that PHP file, sanitize the data to prevent MySQL Injections, and then query the database for the new data.
Use PHP's echo function to send back the data.
In the jQuery $.post() callback function (third parameter), receive the echoed data and put it into a variable.
Use jQuery to update your HTML with the data.
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.
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>
Related
<select id="postnr" name="post_postnr" onChange="updatePlace()">
<?php do { ?>
<option value="<?php echo $row_postnr['postnr'] ?>" ><?php echo $row_postnr['postnr']?></option>
<?php } while ($row_postnr = mysql_fetch_assoc($postnr));?>
</select> <div id="place" style="display:inline"></div>
When user changes value in dropdown, I want to search a database (same table) for the corresponding place and paste it into innerHTML of #place.
The values for the dropdown is collected from a SQL table, column postnr.
postnr place
-----------------
1234 Place1
3456 Place2
and so on...
So when 1234 is selected, Place1 should pop up next to it.
Very basic question about the use of AJAX.
updatePlace() should be a Javascript method that will make an AJAX request to a specific PHP page. This page have to connect to the database and get all needed values.
Take a look at this sample to have a clearer idea.
Hope that helps
If you are using jQuery, you can use the following (the way to do it is the same without jQuery):
<script type="text/javascript">
$("#postnr").on('change', function(){
$.get('get_place.php', {postnr: postnr}, function(data){
$("#place").html(data);
});
});
</script>
Then create a *get_place.php* file with something like the following:
$query = mysql_query("SELECT * FROM places WHERE postnr='".mysql_real_escape_string($_GET['postnr'])."'");
$row = mysql_fetch_assoc($query);
echo $row['place'];
I want to pass area name selected from drop down menu to query of MySQL through PHP. I retrieved name in JavaScript but I am unable to store value from JavaScript to PHP. My Code is As follows
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script>
function getIndex()
{
var x=document.getElementById("cmbArea").selectedIndex;
var y=document.getElementById("cmbArea").options
var z= y[x].text;
alert(z);
}
</script>
</head>
<body>
<form name ="form1" action="Demo1.php" method="post">
<select id="cmbArea" name="cmbArea">
<?php
include 'Connect.php';
$query = "SELECT varAreaName FROM tbArea" ;
$result = mysql_query($query);
while($row = mysql_fetch_assoc( $result )) {
echo '<option value="'.$row['varAreaName'].'">' . $row['varAreaName'] . '</option>';
}
?>
</select>
</form>
<input type="Button" onclick="getIndex()" value="Alert index of selected option">
</body>
</html>
You need to post your form. The value will be available in $_POST['cmbArea'].
If I am understanding you correctly I would use AJAX in this case. Something like this: http://openenergymonitor.org/emon/node/107
Yes, you can not 'store' value from javascript to PHP, as javascript is in client-side(literally in your Browser-side), not in the server-side.
You need to post the data using ajax(Jquery ajax may be), and post them in JSON format.
Check this thread..
PHP will run on server and then javascript will be run on the browser. So you cannot do both in the same page, as you try.
I think the best way is to submit the form, and read the value there using PHP. There you can execute your query.
If you don't want to submit you can check AJAX which will send an asynchronous server side request, without refreshing the webpage.
How would I go about creating the following:
I am looking to create a dropdown menu full of form input types but when one is selected I would like it to create the respective html for the input and save it to the database. I will be using codeigniter.
Example:
If I select Text Area from the dropdown menu it will then create <textarea></textarea> so then I could escape it and save it to the database.
I have come up with the following code so far
if (isset($_REQUEST['general_options']))
{
$optionName = $_REQUEST['general_options'];
$optionValue = strtolower(str_replace(" ", "", $_REQUEST['general_options']));
//$this->load->view( $page, $data, FALSE);
echo form_label($optionName, $optionValue);
echo form_input($optionValue, '', '');
}`
`
Unless your intent on reloading the page every time you make a select choice, your best bet is to incorporate something like jQuery which is a javascript library.
Then with that you can do something like
<select id="mySelect">
<option value="none" selected="selected">---Select---</option>
<option value="textarea">Textarea</option>
</select>
<div id="appendElem"></div>
<script type="text/javascript">
$('#mySelect').change(function()
{
if($(this+' option:selected').val() == "textarea")
{
$('#appendElem').html('<textarea>Some Text...</textarea>');
}
})
</script>
A note worth mentioning is just cause Codeigniter has a form helper class, and makes it sound through its docs that its the only way to build a form on your page. Standard HTML forms work just as well in your views.
I want to populate the text fields from the database based on particular option is selected in the dropdown. e.g dropdown contains the titles of the articles and when i select or click on certain article such that "science" then the content from the database against science should be shown in the textarea in the form...
please.......
Any thing will be appreciated :)
Here's a working example of retrieving info using ajax: (this uses jQuery)
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div>
<select id="myselect">
<option>---</option>
<option>Milk</option>
<option>Coffee</option>
<option>Tea</option>
</select>
</div>
<div>
<textarea id="result"></textarea>
</div>
<script>
$(document).ready(function()
{
$('#myselect').change(function()
{
var selected = $(this).find(':selected').html();
$.post('http://localhost/tests/ajax.php', {'beverage': selected}, function(data) {
$('#result').html(data);
});
});
});
</script>
</body>
</html>
And this is your ajax.php file (change the code to retrieve information from the database).
if (isset($_POST['beverage']))
{
switch($_POST['beverage'])
{
case 'Milk':
print 'Milk makes you grow!';
break;
case 'Coffee':
print 'Coffee does not let you sleep!';
break;
case 'Tea':
print 'Tea comes from China!';
break;
default:
print 'Nothing was selected';
break;
}
}
Two ways to accomplish it :
First, PHP without ajax way: There should be two forms ..one with the the first drop down which contains the data pre-populated from db...Once user submits this form (i.e javascript submit or traditional submit button click) that data can be evaluated against content of query statements by passing this as a value ...
Data returned from the SELECT statement is then re-displayed in the textarea of another form on the same page..
Second,Use ajax to do the POST instead of using the two form approach that will be faster and more efficient..
I have the following code to get the selected item value and post it to a DIV. That is okay, it is working fine, my DIV shows the selected value. But my question is how can I use that value in the DIV ? so that I can create a php msyql query.
<head>
<style>
.response {
padding:10px;
background-color:#9F9;
border:2px solid #396;
margin-bottom:20px;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$("#developer").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#developer option:selected");
var output = "";
if(selected.val() != 0){
output = selected.val();
}
$("#output").html(output);
$('#output').slideDown("slow");
}
</script>
</head>
<select id="developer">
<option value="0">Select</option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
<div align=center class=response id=output style="display:none;">
<?php
$sql = "SELECT * FROM users WHERE name='$name'";
$result = mysql_query($sql) or die("err");
while($row=mysql_fetch_array($result)){
$age = $row[age]; }
echo $age;
?>
</div>
Javascript executes on the front-end, in the user's browser. PHP and mysql are executed on the backend, on your server. If you want to use values from your javascript in PHP and mysql, you will need to make a request to the back-end.
You should read up on
http://api.jquery.com/jQuery.ajax/
and/or
http://api.jquery.com/jQuery.post/
The answer to your question is that you submit the form or send an ajax request back to your server. Your server using PHP, in your case, uses that data to form the DB query.
I think that you are mixing up the timing for when this code is being run.
PHP process and sends to Html loads
Javascript runs (hopefully after
HTML loads) Request is submited from
HTML or Javascript Back to the top
I think you can use $("#output").text(output) instead of $("#output").html(output).
Then you can use $("#output").text(output) to get the value your need.