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).
Related
I am currently trying to display data returned from my database onto my php display page. I have been following along this tutorial:
https://www.phpzag.com/ajax-drop-down-selection-data-load-with-php-mysql/
At first I tried it to test against my data. But I found it to be working incorrectly. So I then decided to use the sample data provided in the tutorial on my system to see where things are going wrong. Thus my pages are as follows:
populatePage.php <---This acts as my "index.php" from tutorial
<?php
require_once('../../config/sessionHandler.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="src/populatePage.js"></script>
<title>Populate Page</title>
</head>
<body >
<div class="page-header">
<h3>
<select id="employee">
<option value="" selected="selected">Select Employee Name</option>
<?php
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee LIMIT 10";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["employee_name"]; ?></option>
<?php } ?>
</select>
</h3>
</div>
<div id="display">
<div id="heading" class="row">
<h3>
</h3>
</div>
<div id="records" class="row">
<h3>
</h3>
</div>
</div>
</body>
</html>
populatePage.js <---My renamed version of getData.js from tutorial
$(document).ready(function(){
// code to get all records from table via select box
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url: 'popJax.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#heading").show();
$("#no_records").hide();
$("#emp_name").text(employeeData.employee_name);
$("#emp_age").text(employeeData.employee_age);
$("#emp_salary").text(employeeData.employee_salary);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
popJax.php <--- This is my getEmployee.php from the tutorial
<?php
require_once('../../config/sessionHandler.php');
$_SESSION['PopulateWorking'] = true;
if($_REQUEST['empid'])
{
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) )
{
$data = $rows;
}
echo json_encode($data);
}
else
{
echo 0;
$_SESSION['Fail'] = true;
}
?>>
My sessionHandler is used to achieve the database connection and session verification.
I followed along with the tutorial. And thus far my system will:
-Retrieve the users from the table.
-Populate the drop down with them.
-Allow me to select a user.
-Display $_SESSION['PopulateWorking'] as 'true'
AND
-Properly read through employee data while I watch it in JS debugger.
But somewhere along these lines I am missing something. I have worked with AJAX, PHP, and SQL pretty frequently. But am by no means an expert. I am looking for where I am missing an integral step? I just want to try and display the data like he does in the tutorial. Because then I can fine tune and change everything around to make it work how I would like. But right now when I click a user nothing populates on the page like it does in his tutorial. Mine works right up until the actual important part. Displaying the selected data.
When compared next to his mine also does not display : "Please select employee name to view details", anywhere on the page? So I am thinking I am missing an entire DIV somewhere? Or not generating it? Or the script is not calling it properly?
I just can't seem to figure out where I am incorrectly utilizing the JSON data?
TL;DR: Why will my page not display the result data on my page like it does in this tutorial?
Im sorry for the waste of time. I did not have any of the div's that i was trying to reference in popJax.php
I needed to add
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.
I have code below for a search bar that, upon clicking 'Search', loads a new page with the query results. How do I change it so instead of loading a new page, the query results open in a modal popup within the same page?
index.php
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form method="POST" action="search.php">
<input type="text" name="q" placeholder="Enter query"/>
<input type="submit" name="search" value="Search" />
</form>
</body>
search.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
include_once('db.php'); //Connect to database
if(isset($_POST['q'])){
$q = $_POST['q'];
//get required columns
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%$q%' OR `yupikWord` LIKE '%$q%'") or die(mysqli_error($conn)); //check for query error
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= "<a href='audio/$audio_name'>$audio_name</a> ";
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>
You need to use JavaScript on your page to executed an AJAX call to search.php. That PHP file preferable returns JSON data, or complete HTML that can be added to the modal window.
Conceptually:
Use JavaScript to executed AJAX POST to search.php
Have search.php return the data in JSON format.
Have JavaScript catch the returned data, iterate through it and create HTML elements.
Use JavaScript to open a new modal window.
Use JavaScript to add the HTML elements to the modal's body.
You don't necessarily need to use JavaScript to create the modal window. You can create it in plain HTML and fill it and open it using JavaScript.
Welcome to stackoverflow. Here's my solution for that, so first, you have to capture the form submission, the technique is doing GET request using jQuery which I assume you already using jQuery since you are using bootstrap and bootstrap uses jQuery
$('form').submit(function(e){
e.preventDefault() // do not submit form
// do get request
$.get( 'search.php', { q : },function(e){
// then show the modal first
$('#mymodal').modal('show');
// then put the results there
$('#mymodal:visible .modal-container .modal-body').html(e);
});
});
I am trying to fill a listbox on a webpage and I want the listbox to start blank. Once the button is clicked the listbox should populate. My code below automatically fills the listbox but I would rather have the button do it.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select name="RestName">
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
?>
</select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<input type="submit" name="Submit" value="Submit" />
<br />
</form>
</body>
</html>
I would either: Preload the data into the page as some ready but invisible html list (maybe a bit n00b), or save the data as a javascript array and a function will load it into the page (better), or do an ajax call to the same page (for simplicity) (probably best, leaves you the option open for updated data after page initiation).
The Ajax route will have to use jQuery (change this_page.php to whichever page this is called):
<?php
while ($nt= mysql_fetch_assoc($result))
$arrData[] = $nt;
//If you want to test without DB, uncomment this, and comment previous
/*$arrData = array(
array('RestID' => "1", 'RestName' => "Mike"),
array('RestID' => "2", 'RestName' => "Sebastian"),
array('RestID' => "3", 'RestName' => "Shitter")
);*/
if(isset($_GET["ajax"]))
{
echo json_encode($arrData);
die();
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function displayItems()
{
$.getJSON("this_page.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.RestID;
option.text=objRecord.RestName;
$("#RestName").append('<option value="' + objRecord.RestID + '">' + objRecord.RestName + '</option>');
});
});
}
</script>
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select id="RestName"></select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<button type="button" onclick="javascript:displayItems();">Insert options</button>
<br />
</form>
</body>
</html>
Essentially, what it does, it collects the data, checks if there is a request for the ajax data in the url, if not, it prints the rest of the page (with an empty select). If there is an ajax flag in the url, then the php will encode the data into json, print that and stop.
When the User receives the page with an empty select, it clicks the button which will trigger the displayItems() function. Inside that function, it does a jQuery-based ajax call to the same page with the ajax flag set in the url, and the result (which is json), is evaluated to a valid javascript array. That array is then created into options and loaded into the RestName SELECT element.
A final cookie? You could just print the data as options, into the select anyway, just like the previous answers described. Then, inside the displayItems() function, you clear the select before loading it from the jQuery/ajax call. That way, the user will see data right from the beginning, and will only update this with the most recent data from the DB. Clean and all in one page.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<html>
<head>
<script>
function displayResult()
{
var x =document.getElementById("RestName");
var option;
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo 'option=document.createElement("option");' .
'option.value=' . $nt['RestID'] . ';' .
'option.text=' . $nt['RestName'] . ';' .
'x.add(option,null);';
}
?>
}
</script>
</head>
<body>
<select name="RestName">
</select>
<button type="button" onclick="displayResult()">Insert options</button>
</body>
</html>
Read more about adding options to select element from java script here
how about this simple way,
is this what you mean,
its not safe, any one can post show=yes but i think you just like users to be able to simply click and see result
<select name="RestName">
<?php
// if show=yes
if ($_POST['show'] == "yes"){
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
}
?>
</select>
<form method="post" action="#">
<input type="hidden" name="show" value="yes" />
<input type="submit" name="Submit" value="Submit" />
</form>
you can also simply use a hidden div to hid listbox and give the button an onclick action to show div, learn how in here: https://stackoverflow.com/a/10859950/1549838
I want to submit search query form & get search result without redirecting/reloading/refreshing on the same page.
My content is dynamic so can not use those "submit contact form without refreshing page which replies back on success".
In order to submit a form, collect the results from the database and present them to the user without a page refresh, redirect or reloading, you need to:
Use Ajax to Post the data from your form to a php file;
That file in background will query the database and obtain the results for the data that he as received;
With the query result, you will need to inject it inside an html element in your page that is ready to present the results to the user;
At last, you need to set some controlling stuff to let styles and document workflow run smoothly.
So, having said that, here's an working example:
We have a table "persons" with a field "age" and a field "name" and we are going to search for persons with an age of 32. Next we will present their names and age inside a div with a table with pink background and a very large text.
To properly test this, we will have an header, body and footer with gray colors!
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="pt" dir="ltr">
<head>
<title>Search And Show Without Refresh</title>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<!-- JQUERY FROM GOOGLE API -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
</head>
<body style="margin:0;padding:0px;width:100%;height:100%;background-color:#FFFFFF;">
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
HEADER
</div>
<div style="width:1024px;margin:0 auto;height:568px;background-color:#f0f0f0;text-align:center;">
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
<div id="search_results"></div>
</div>
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
FOOTER
</div>
</body>
</html>
db_query.php
<?php
define("HOST", "localhost");
// Database user
define("DBUSER", "username");
// Database password
define("PASS", "password");
// Database name
define("DB", "database_name");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM persons
WHERE age='".$_POST['value']."'
");
echo '<table>';
while ($data = mysql_fetch_array($query)) {
echo '
<tr style="background-color:pink;">
<td style="font-size:18px;">'.$data["name"].'</td>
<td style="font-size:18px;">'.$data["age"].'</td>
</tr>';
}
echo '</table>';
?>
The controlling stuff depends from what you want, but use that code, place those two files in the same directory, and you should be fine!
Any problems or a more explicative code, please let us know ;)
You'll probably want to start with any of the thousands of "AJAX for beginners" tutorials you can find on the net. A Google search with that term should get you going.
Try this for starters:
http://www.destraynor.com/serendipity/index.php?/archives/29-AJAX-for-the-beginner.html
After you've read through that, keep in mind that you really don't need to be writing any XHR handling code. As pointed out by Jamie, jQuery or any of the other multitudes of Javascript libraries out there, can greatly simplify your client-side AJAX code.
This is what AJAX is for.
In jQuery (apologies if you're looking for a different library)
$("form#search").bind('submit',function() {
$.post("search.php",this.serialize(),function(data) {
// Put the code to deal with the response data here
});
return false;
});
It's good if you can get some basics of Ajax before straight away going to the code.
Ajax , is the exact solution for your problem. It asynchronously makes a request to the server, get the result and the data in the page can be modified with the result . It's all done in JavaScript.
Suppose you have an html like this:
<html>
<body>
<div id="myDiv"> your content area</div>
<button type="button" onclick="loadByAjax()">Change Content</button>
</body>
</html>
Now, your javascipr code will be like this:
<script type="text/javascript">
function loadByAjax()
{
$.ajax({
type: "POST",
url: "yourserverpage.php",
data: "searchkey=data_from_user_input",
success: function(response_data){
$('myDiv').html(response_data)
}
});
}
</script>
so, basically upon click of the button, the JavaScript will be executed. It wil call the php serverside script, pass the parameters it got from user input and retrieve the response data and place it inside the div.
So your page is updated without full refresh.
Also, please understand that, i used jquery library here for the Ajax function.