very new coder here.
I have a page with four select inputs each with two possible options, and when all of the selections have a value and a submit button is clicked a certain song (1 of 16 based on the selections made) will echo out into an audioplayer.
In its current state I have been able to connect to my database which echos out the links and titles for the audio tracks.
My issue is that I want all of the selections to visually retain their option values once the submit button is clicked so that users can see what options they have selected for the current song that is playing.
I've found lots of examples online of implementing AJAX into a page with one selection that activates via an onchange event such as this one from W3 Schools http://www.w3schools.com/php/php_ajax_database.asp, but nothing with multiple selections and a submit button.
Someone from this community helped me out the other day so that the code for the W3 schools example could accommodate a submit button onclick event instead of the onchange on the select input, but with my lack of much fluency with PHP/Javascript I don't really have an idea of how to include multiple selections.
I was hoping someone could take a look at how far I got in my page with multiple selections but no AJAX implemented and explain to me in very simple terms how I could go about including AJAX so that the select options are visible once the submit button has been clicked. If one could even show me a version of my page with AJAX placed with comments to explain the process would be absolutely golden.
Here is my page...
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<link rel="shortcut icon" href="favicon.ico"/>
<title>MoodTunes -- Tunes for your mood</title>
<script src="prefixfree.min.js"></script>
</head>
<body>
<?php
$myDatabase = mysql_connect("localhost","root","root");
if (!myDatabase) die ('Oh dear.' . mysql_error());
if(isset($_GET['submit'])){
mysql_select_db("tunes",$myDatabase);
$volume = $_GET['volume'];
$tempo = $_GET['tempo'];
$complexity = $_GET['complexity'];
$key = $_GET['key'];
$query = "SELECT * FROM music WHERE volumeOption='".$volume."' AND tempoOption='".$tempo."' AND complexityOption='".$complexity."' AND keySignatureOption='".$key."'";
$mydata = mysql_query($query, $myDatabase) or die(mysql_error());
while($row = mysql_fetch_array($mydata)){
echo "<div id='submitContent'>";
echo "<h3><span>Now Playing:</span> " . $row['title'] . "</h3>";
echo "<figure id='audioplayer' style='display:inline-block;'>";
echo "<audio id='audiotrack' controls loop>";
echo "<source src='" . $row['link'] . "'type='audio/mpeg'>";
echo "</audio>";
echo "</figure>";
}
mysql_close($myDatabase);
}
?>
</div>
<header>
<div>
<h1>
<img src="assets/images/logo.png" alt="">
</h1>
<h2>Tunes for <span>your</span> mood</h2>
</div>
</header>
<main>
<h4>Choose your tune criteria</h4>
<form>
<label for="volume"></label>
<select name="volume" id="volume">
<option>Select One</option>
<option value="0" id="loud">heavy</option>
<option value="1" id="quiet">soft</option>
</select>
</label>
<label for="tempo"></label>
<select name="tempo" id="tempo">
<option>Select One</option>
<option value="0" id="fast">fast</option>
<option value="1" id="slow">slow</option>
</select>
</label>
<label for="complexity"></label>
<select name="complexity" id="complexity">
<option>Select One</option>
<option value="0" id="complex">complex</option>
<option value="1" id="simple">simple</option>
</select>
</label>
<label for="key"></label>
<select name="key" id="key">
<option>Select One</option>
<option value="0" id="minor">minor key</option>
<option value="1" id="major">major key</option>
</select>
</label>
<div id="submitDiv">
<input type="submit" name="submit" id="submit" value="Get My Tune!">
</div>
</form>
</main>
</body>
</html>
Any help would be greatly appreciated. Like I said, I'm still very new to much coding so please answer simply if you can help me out. Thanks.
I suggest splitting into 2 files: an HTML file and a PHP file. Keep the PHP separate and call it with an XHR object (Ajax).
music.html
<!-- skipped top stuff -->
<body>
<!-- replace your PHP code with straight HTML -->
<div id='submitContent'>
<h3><span>Now Playing:</span> <span id="musictitle"></span></h3>
<figure id='audioplayer' style='display:inline-block;'>
<audio id='audiotrack' controls loop>
<source id="musiclink" src='' type='audio/mpeg'>
</audio>
</figure>
</div>
<!-- skipped middle stuff -->
<form id="musicform"> <!-- give your form an id -->
<!-- skipped form stuff -->
</form>
<!-- add script tag to bottom of body -->
<script>
// function to handle music selection
function get_selection () {
// instantiate music url
var url = 'music.php'
// get form values or defaults
var musicform = document.getElementById('musicform')
url += ('Select One' == musicform.volume.value)? '?volume=1': '?volume=' + musicform.volume.value
url += ('Select One' == musicform.tempo.value)? '&tempo=1': '&tempo=' + musicform.tempo.value
url += ('Select One' == musicform.complexity.value)? '&complexity=1': '&complexity=' + musicform.complexity.value
url += ('Select One' == musicform.key.value)? '&key=1': '&key=' + musicform.key.value
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
//console.log(this.responseText)
var music = JSON.parse(this.responseText)
document.getElementById('musictitle').innerHTML = music.title
var audio = document.getElementById('audiotrack')
document.getElementById('musiclink').src = music.link
audio.load()
audio.play()
}
xhr.send()
}
// hook up music selection function to form submit
document.getElementById('musicform').addEventListener('submit', function(evt){
evt.preventDefault()
get_selection()
})
// execute music selection function at least once
get_selection()
</script>
</body>
</html>
music.php
<?php
$myDatabase = mysqli_connect("localhost","root", "root", "tunes");
$stmt = mysqli_prepare($myDatabase
, "SELECT title, link FROM music WHERE volumeOption = ? AND tempoOption = ? AND complexityOption = ? AND keySignatureOption = ?"
) or die(mysqli_error($myDatabase));
mysqli_stmt_bind_param($stmt, 'ssss', $_GET['volume'], $_GET['tempo'], $_GET['complexity'], $_GET['key']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $title, $link);
mysqli_stmt_fetch($stmt); // assuming only one result
echo '{"title": "' . $title . '", "link": "' . $link . '"}';
mysqli_close($myDatabase);
?>
And I'm using PHP MySQLi prepared statements for database access for security and the fact plain old PHP MySQL functions are deprecated.
Disclaimer The sessionStorage object will only be available while the browser is OPEN. If you wish to retain the information regardless of the browser being closed, please change to the localStorage object instead.
Here's your working jsFiddle example
One of the easiest and quickest ways to retain form input information without even bothering with serverside language is using the sessionStorage functions.
We can capture all of the change events on the form elements and push their values into the sessionStorage. We can then retrieve and apply them to each of the respective inputs on the page reload with very minimal code.
//First, we need to make sure our users support the Storage object.
if(typeof(Storage) !== "undefined") {
/**
| -----------------------
| All of your elements can be selected by the :input selector in jQuery
| We will bind to the change function and push to the sessionStorage whenever they are altered.
| -----------------------
*/
$(':input').change(function(){
sessionStorage.setItem($(this).prop('name'), $(this).val());
});
}
Basically, if the storage is available, we create an event handler that binds to the change event of all of our form elements. Now when they change, we'll have a bunch of keys we can retrieve from the sessionStorage element.
Now, we need to apply those values to our elements on page load.
//make sure we still have Storage available.
if (typeof (Storage) !== "undefined") {
/**
| -----------------------
| We capture each of the input elements below and then check if
| we previously had values saved for them.
| If not, the default is left selected.
| -----------------------
*/
$('form *').filter(':input').each(function () {
if(sessionStorage.getItem($(this).prop('name'))){
$(this).val(sessionStorage.getItem($(this).prop('name')));
}
});
}
Now in the above code we're simply looping over all of our form elements and applying the values that were stored in the sessionStorage to those elements.
Additionally
Let's get you away from the mysql_ library as it's deprecated, and will be completely removed in future versions of PHP. Let's also focus on sanitizing user input, so you don't have SQL injection vulnerabilities which could have catastrophic side effects.
$myDatabase = new mysqli('localhost', 'username', 'password', 'database');
Users can still bypass the if(isset($_GET['submit'])){ conditional, so let's add some more sanity checking.
$volume = isset($_GET['volume']) ? $_GET['volume']: null;
$tempo = isset($_GET['tempo']) ? $_GET['tempo'] : null;
$complexity = isset($_GET['complexity']) ? $_GET['complexity'] : null;
$key = isset($_GET['key']) ? $_GET['key'] : null;
Now we should check if all those are set at the same time.
if(isset($volume, $tempo, $complexity, $key)){
}
Inside of this conditional, we can then apply our database logic using mysqli's object oriented approach. We'll also use prepared statements to avoid the SQL injection.
$stmt = $mysqli->prepare('SELECT * FROM music WHERE volumeOption=? AND tempoOption=? AND complexityOption=? AND keySignatureOption=?');
$stmt->bind_param('ssss', $volume, $tempo, $complexity, $key);
if($stmt->execute()){
while($row = $stmt->fetch()){ ?>
<div id="submitContent">
<h3><span>Now Playing:</span> <?php echo $row['title']; ?> </h3>
<figure id="audioplayer" style='display:inline-block;'>
<audio id="audiotrack" controls loop>
<source src="<?php echo $row['link']?>" type="audio/mpeg"/>
</audio>
</figure>
<?php }
}
Related
I tried to implement a dependent drop down lists system. The code in contact.php page is:
<?php
$link = new mysqli("localhost", "root", "", "graphicdesign");
if($link->connect_error){
die("ERROR: Nu s-a putut realiza conexiunea la baza de date " .$link->connect_error);
}
$resultSet = $link->query("SELECT * FROM orase") or die('Error In Session');
/* $rowsn = mysqli_fetch_array($resultSet);
$n_oras=$rowsn['denumire_oras'];
$id_orasss=$rowsn['id_oras']; */
//$resultSetRep = $link->query("SELECT id_oras, denumire_rep FROM reprezentante where id_oras='$id_oras'") or die('Error In Session');
//$rows1= mysqli_fetch_array($resultSetRep);
?>
<!DOCTYPE HTML>
<html>
<head>
--head info
</head>
<body>
<form action="#">
<div class="row form-group">
<div class="col-md-12">
<label style="margin-right:15px;">Oras</label>
<select id="denum_oras" name="den_oras">
<?php
while($rows = mysqli_fetch_array($resultSet)) {
$n_oras=$rows['denumire_oras'];
$id_oras=$rows['id_oras'];
echo "<option value='$id_oras'>$n_oras</option>";
}
?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label style="margin-right:15px;">Reprezentanta</label>
<select id="reprez" name="reprez">
<?php
while($rows2=$resultSet->fetch_assoc()) {
$id_oras=$rows2['id_oras'];
$den_rep=$rows2['denumire_rep'];
$resultSetRep = $link->query("SELECT id_oras, denumire_rep FROM reprezentante where id_oras='$id_oras'") or die('Error In Session');
while($rows3=$resultSetRep->fetch_assoc()) {
$id_rep = $rows3['id_rep'];
$den_rep = $rows3 ['denumire_rep'];
echo "<option value='$id_rep'>$den_rep</option>";
}
}
?>
</select>
</div>
</div>
</form>
</body>
</html>
The first drop down list is working, it is retrieving the right data from table "orase" in the database:
But for the second drop down, i want that, when i select the option "Braila" form the first drop down, to show the values from the database with the foreign key "id_oras" as the selected choice.
In this case, when I select "Braila" from the first drop down list, with the id_oras=1 in the table orase, I want that the second drop down list to retrieve data from the table "reprezentante" where id_oras = 1, in this case to retrieve values "Rep Braila" and "Rep Braila 2" to be shown in the drop down, but this is not happening..
This is a capture of the page:
The code i posted is the best one i thought about, but still doesn't work.. please help me!
Thanks!
PHP is preprocessor language isn't compile on runtime you can use Ajax or XMLHttpRequest to get the data. After that, you can use Jquery or javascript to bind the data in the select box
You need to use Ajax for accomplishing this task. Using onChange jquery event when parent dropdown value gets changed will populate child or dependent dropdown accordingly.
Please refer this link: Populate a dropdown list based on selection of another dropdown list using ajax
Hope this helps.
As others have mentioned you will need to inject a little bit of Javascript into your code.
Your first Select looks fine, but the second would have to be re-written.
Put an onchange event into your first select like so:
<select name="list" id="list" onchange="update(this)">
And a Div to hold your second dropdown list.
<div id="secondlist">
// contents of returned html from "getsecondlist.php" will go here
</div>
Then put the following Javascript inbetween your head tags.
This will call "getsecondlist.php" and pass a parameter of idoras.
"getsecondlist.php" will return the second dropdown list, which is stored in this.responseText.
<script>
function update(e) {
idoras = e.options[e.selectedIndex].value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("secondlist").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getsecondlist.php?idoras=" + idoras, true);
xhttp.send();
}
</script>
getsecondlist.php
<div class="row form-group">
<div class="col-md-12">
<label style="margin-right:15px;">Reprezentanta</label>
<select id="reprez" name="reprez">
<?php
$id_oras=$_GET['idoras'];
$resultSetRep = $link->query("SELECT id_oras, denumire_rep FROM reprezentante where id_oras='$id_oras'") or die('Error In Session');
while($rows3=$resultSetRep->fetch_assoc()) {
$id_rep = $rows3['id_rep'];
$den_rep = $rows3 ['denumire_rep'];
echo "<option value='$id_rep'>$den_rep</option>";
}
?>
</select>
</div>
</div>
The $_GET['idoras'] gets the parameter sent in from the Javascript call.
Hope this helps.
I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>
You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.
Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.
The user goes change the nm_peca, will select tipo_preco and then find the price in MySQL database to complete the textbox vlr_peca.
What do I need to do to get the value of products?
<?php>
$query = mysql_query("SELECT id, nm_peca, vlr_original,
vlr_paralelo, fabricante
FROM peca
ORDER BY nm_peca");
<select id="nm_peca" name="nm_peca"
title="Selecione um status."
class="form-control" size="1">
<option value="">Status</option>
<option value="N/A">N/A</option>
<option value="S">S - Substituir</option>
</select>
</div>
</div>
<select id="tipo_preco" name="tipo_preco"
class="form-control" size="1">
<option value="">Tipo</option>
<option value="Peça Original">Original</option>
<option value="Peça Paralela">Paralela</option>
</select>
</div>
</div>
<div class="col-md-1">
<div class="input-group btn-group">
<input type="text" value="????????" name="vlr_peca"
class="form-control" readonly>
</div>
</div>
Well your code is a little confusing because what you really want is not clear to me, maybe it doesn't help that it's in a different language. What is the $query for? You are not using this in the code, so you'll need to do this to access it:
$rows = array();
while ($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
print '<pre>'. print_r($rows, true) . '</pre>';
Then you'll need to use an ajax request OR setup javascript vars on the front end to make changes. I'm just going to go ahead and use the latter since it's more illustrative.
So I would add the cdn of jQuery which is https://code.jquery.com/jquery-2.1.4.min.js to the top of your file in a tag like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Then you'll need to add an input id to that input tag like <input id="dynamic-variable" type="text" value="????????" name="vlr_peca"> and then use something like:
<script type="text/javascript">
$(document).ready(function() {
$('#tipo_preco').change(function() {
if ($(this).val() == 'Peça Original') {
$('#dynamic-variable').val('$5,000,000,000.00');
} else if ($(this).val() == 'Peça Paralela') {
$('#dynamic-variable').val('$300 billion trillion dollars');
} else {
$('#dynamic-variable').val('Bro. Choose one.');
}
});
});
</script>
I'm not going to program this whole thing for you since I don't know what kind of data you are getting from your DB, but this should be good enough to get you started. You need to be able to access the data in the mysql query, and you may just want to use the <?= $db_variable ?> or <?php echo $db_variable?> in your javascript where I have the amount variables. This should be good enough to get you started. Read up on php mysql_query and jQuery
AJAX
If you were to do this via AJAX, you would need a second page that accesses the database, you'd have to $_GET or $_POST variables and then print back the amount.
So your JavaScript would be something like this:
$.get('/the/page.php?tipo_preco=' + $('#tipo_preco').val(), function(response) {
if (response != '') {
$('#dynamic-variable').val(response);
}
});
And your second page would be something like this:
<?php
// code that sets up the database
// .... //
// now your code
$selected_value = $_GET['tipo_preco'];
$result = mysql_query("SELECT price FROM table WHERE column_val = '" . mysql_real_escape_string($selected_value) . "'");
$row = mysql_fetch_assoc($result); // assuming you're only fetching one row
print $row['price'];
?>
I would suggest you just go with the first suggestion, it's faster, less moving parts.
I am trying to change the contents of depending on the current option selected.
The getData(page) comes back correctly (onChange) but it just doesn't go over to the variable I get "Fatal error: Call to undefined function getData() in C:\xampp\htdocs\pdimi\admin\editpages.php on line 42"
EDIT: This is how I finished it!
Javascript:
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
Select form:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<select name="page" onChange="getData(this)">
<?php
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_POST['page']);
else
$page = '';
$query = "SELECT pageid FROM pages;";
?>
<option value="select">Select Page</option>
<option value="indexpage">Index Page</option>
<option value="starthere">Start Here</option>
</select>
Textarea:
<textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data">
<?php
if (isset($_GET['page'])) {
$sql1 = #mysql_query("SELECT * FROM pages WHERE pageid='".$_GET['page']."'") or die(mysql_error());
$sql2 = #mysql_fetch_array($sql1) or die(mysql_error());
if ($sql1) {
echo $sql2['content'];
}
}
?>
</textarea>
And that is that!
You cannot execute a Javascript function (client side) from PHP (which runs server side).
Also, you need to connect to a database server with user and password, and select a database. Do not use #, it will only prevent you from seeing errors -- but the errors will be there.
In the PHP file you need to check whether you receive a $_POST['page'], and if so, use that as the ID for the SELECT. You have set up a combo named 'page', so on submit the PHP script will receive the selected value into a variable called $_POST['page'].
Usual warnings apply:
mysql_* functions are discouraged, use mysqli or PDO
if you still use mysql_*, sanitize the input (e.g. $id = (int)$_POST['page'] if it is numeric, or mysql_real_escape_string if it is not, as in your case)
If you want to change the content of textarea when the user changes the combo box, that is a work for AJAX (e.g. jQuery):
bind a function to the change event of the combo box
issue a call to a PHP script server side passing the new ID
the PHP script will output only the content, no other HTML
receive the content in the change-function of the combo and verify success
set $('#textarea')'s value to the content
This way you won't have to reload the page at each combo change. Which reminds me of another thing, when you reload the page now, you have to properly set the combo value: and you can exploit this to dynamically generate the combo, also.
Working example
This file expects to be called 'editpages.php'. PHP elaboration is done (almost) separately from data presentation.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>PDIMI - The Personal Development and Internet Marketing Institution</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css' />
<link href="../style/default.css" rel="stylesheet" type="text/css" media="all" />
<!--[if IE 6]>
<link href="default_ie6.css" rel="stylesheet" type="text/css" />
<![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
</head>
<?php include 'aheader.php';?>
<?php
error_reporting(E_ALL);
if (!mysql_ping())
die ("The MySQL connection is not active.");
mysql_set_charset('utf8');
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_REQUEST['page']);
else
$page = False;
$query = "SELECT pageid, pagename FROM pages;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec)
trigger_error("Cannot fetch data from pages table: " . mysql_error(), E_USER_ERROR);
if (0 == mysql_num_rows($exec))
trigger_error("There are no pages in the 'pages' table. Cannot continue: it would not work. Insert some pageids and retry.",
E_USER_ERROR);
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['pageid'] === $page)
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $page)
$page = $row['pageid'];
$sel = '';
}
$options .= "<option value=\"{$row['pageid']}\" $sel>{$row['pagename']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['page_data']))
{
$page_data = mysql_real_escape_string($_POST['page_data']);
$query = "INSERT INTO pages ( pageid, content ) VALUES ( '{$page}', '{$page_data}' ) ON DUPLICATE KEY UPDATE content=VALUES(content);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
// Anyway, recover its contents (maybe updated)
$query = "SELECT content FROM pages WHERE pageid='{$page}';";
$exec = mysql_query($query);
// who says we found anything? Maybe this id does not even exist.
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textarea = $row['content'];
}
else
$textarea = '';
mysql_free_result($exec);
?>
<body>
<div id="page-wrapper">
<div id="page">
<div id="content2">
<h2>Edit Your Pages Here</h2>
<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>
<form name="editpage" method="POST" action="">
<table border="1" width="100%">
<tr>
<td>Please Select The Page You Wish To Edit:</td>
<td>
<select name="page" onChange="getData(this)"><?php print $options; ?></select>
</td>
</tr>
<tr>
<td><textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data"><?php print $textarea; ?></textarea></td>
</tr>
<tr>
<td><input type="Submit" value="Save the page"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
The biggest issue that you have here, is that you need to learn the difference between client side and server side.
Server Side: As the page is loading... We run various code to determine what is going to be displayed and printed into the source code.
Client side: Once the page has loaded... We can then use DOM elements to interact, modify, or enhance the user experience (im making this up as i go along).
In your code, you have a PHP mysql command:
$thisdata = #mysql_query("SELECT * FROM pages WHERE pageid=".getData('value'));
1, Don't use mysql. Use mysqli or PDO
2, You have called a javascript function from your PHP.
There is absolutely no way that you can call a javascript function from PHP. The client side script does not exist and will not run until after the page has stopped loading.
In your case:
You need to server up the HTML and javascript code that you will be using. Once, and only when, the page has loaded, you need to use javascript (client side scripting), to set an event listener to listen for your select change event. Once this event is triggered, then you can determine what you want to do (ie change a textbox value, etc).
I am a newby so appologise for asking a basic question.
I have a php page - a 'create new project' page
There are some simple data such as name, deadline etc...
but depending on the type of the project I have 4 different ends (different pages?) in this FORM and I can't find the solution for it.
Here is my code:
<h1>New Project</h1>
<form name="newpr">
New project name:<input type="text" placeholder="new project name..."><br />
New project end date:<input type="text" placeholder="date..."><br />
New project type:
<select name="menu" onChange="location=document.newpr.menu.options[document.newpr.menu.selectedIndex].value;" >
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
if ($listresult["listing"]!="...") $link=$listresult["value"].".php";
else $link="";
echo "<option value='".$link."'>".$listresult["listing"]."</option> ";
}
?>
</select>
</form>
As you see the select list comes from Mysql and I would like a div under a form to be able to open page1.php or page2.php etc as user selects...
Thanks in advance
Andras
it might be ajax question...
I'd solve this the following way
<!-- using jQuery -->
<h1>New Project</h1>
<form method="" action="post">
New project name:<input type="text" placeholder="new project name..."><br/>
New project end date:<input type="text" placeholder="date..."><br/>
New project type:
<select name="menu">
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
$link = '';
if($listresult['listing'] != '...') {
$links = $listresult['value'] . ".php";
echo "<option value='$link'>${listresult['listing']}</option>";
}
}
?>
</select>
<div id="page">
<!-- container for loaded page -->
</div>
<script type="text/javascript">
$("select[name=menu]").change(function() {
var url = $("option:selected", this).val();
// Load a page to the container
$("#page").load(url);
});
</script>
</form>
Using jQuery I added on change handler on select box and if it's changed it loads via ajax a page to the div container.
And let me give you and advice - try to avoid mixing code and html. It leads to difficulties in further development and maintenance.
You want to make a HTTP request to your php page Checkout http://mootools.net/docs/core/Request/Request.HTML
http://mootools.net/docs/more/Request/Request.JSONP
Listen for the callback on your request then inject the returned data as an element into the DOM. Mootools is my weapon of choice but Jquery etc. all have this same functionality. call php page under Javascript function This question is very similar to yours.