Jesse J.
Jesse J.

Reputation: 13

How do I change the value of textarea by option selected?

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!

Upvotes: 1

Views: 2434

Answers (2)

LSerni
LSerni

Reputation: 57418

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):

  1. bind a function to the change event of the combo box
  2. issue a call to a PHP script server side passing the new ID
  3. the PHP script will output only the content, no other HTML
  4. receive the content in the change-function of the combo and verify success
  5. 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>

Upvotes: 2

Samuel Cook
Samuel Cook

Reputation: 16828

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).

Upvotes: 0

Related Questions