Trouble displaying SQL AJAX call results from jQuery onto HTML - php

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

Related

Display Data from a dependent dropdown in php

i need help, i'm new to php and jquery
i created a two tier dependent dropdown list populated from mysql database,which uses two tables products and fieldo with pid as the foreign key.
//code for dropdown.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head><?php include "connectdb.php"; ?>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "states.php",
data:'pid='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
function showMsg()
{
$("#msgC").html($("SELECT name, email from fieldo where state = '#state-list option:selected'").text());
return false;
}
</script>
<body >
<form>
<label style="font-size:20px" >Products:</label>
<select name="product" id="product-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Products</option>
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["pid"]; ?>"><?php echo $rs["Name"]; ?></option>
<?php
}
?>
</select>
<label style="font-size:20px" >State:</label>
<select id="state-list" name="state" >
<option value="">Select State</option>
</select>
<button value="submit" onclick="return showMsg()">Submit</button>
</form>
Result: <span id="msgC"></span><br>
</body>
</html>
//code for states.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">//alert("sdfsd");</script>
<body>
<?php
require_once("connectdb.php");
//$db_handle = new DBController();
$query ="SELECT oid,state FROM fieldo WHERE pid = '".$_POST["pid"]."'";
$results = $dbhandle->query($query);
?>
<option>Select State</option>
<?php
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["oid"]; ?>"><?php echo $rs["state"]; ?></option>
<?php
}
?>
</body>
</html>
this list is working correctly but i want to display the other columns of stated (email , name and contact) upon selection of the state.
its not working
Have you tried running the while loop without breaking the PHP script? It seems you are almost trying to run a for loop.
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
echo '<option value="' . $rs["pid"] . '">' . $rs["Name"] . '</option>';
}
?>
UPDATE
Okay, so I heard your comment, and I have used an ajax call to get the full display of the content; I was not really sure as to what you were trying to do with your showMsg() function. I was assuming you were wanting to create a new query request.
So I changed the function to create an Ajax call that would look something along these lines:
<script>
function showMsg()
{
var val;
val = $("#state-list").val();
$.ajax({
type: "POST",
url: "table.php",
data: "state_id="+val,
success: function(data){
$("#msgC").html(data);
}
});
}
</script>
And then table.php would be along these lines...
<?php
// check to see if state_id has been submitted
if(isset($_POST['state_id']))
{
$state_id = $_POST['state_id'];
}
// if it is not set, add something in place.
else
{
$state_id = "1";
}
// query goes here - ask for the ID
$query = "SELECT name, email from fieldo where state = " . $state_id;
$results = $dbhandle->query($query);
while($rs=$results->fetch_assoc()) {
//... create table with all content;
}
?>
PHP cannot react to what is happening in the browser. Once PHP has processed the page and the web server has sent it to the browser, JavaScript takes over.
This means that if a customer selects a new state, it will not automatically get PHP to populate the rest of the page with the matching email, name and contact. You need to change your approach a bit.
One approach is to use Ajax. It would work like so:
In jQuery, register an onChange event handler for the states dropdown.
When customer selects a new state, the event handler will be triggered. Within the handler, make an Ajax request that sends the PHP the selected state.
the PHP document that receives the request would query for the matching email, name and contact from the DB and send the results, perhaps as a JSON
Back in the jQuery handler, when data comes back from the PHP server (in the response callback), use that data to populate the page with the right email, name and contact.
An alternative, even simpler approach (if you don't have a lot of data) is to have PHP send all data at once in a multi-dimensional array when the page loads. This time when the user selects a new state, the jQuery event handler will look up the data under that state within the big array, and fill the form with the data.

Taking values from form, pulling results from MySQL, and using AJAX for results

I am having a bit of trouble figuring out how exactly to make a certain connection. It's a project I thought might be simple enough for me to do on my own without help, but I've hit a wall unfortunately. It's an 'exercise generator' that basically asks a few basic questions, and based on your answers, it outputs a recommended workout routine. I've constructed the MySQL database with plenty of exercises, have successfully connected the database, and have made the form.
What I am having trouble though, however, is storing those form results into variables, and based on those variables (if workout days is 3, for example, there would only be 3 groups of workouts printed instead of 5) output a routine into the same div as the form, effectively replacing it with the answer instead of placing it underneath the submitted form.
Index.php
<!DOCTYPE html>
<html>
<?php $page_title = "Workout Generator"; ?>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
</head>
<body>
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="appWindow">
<h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3>
<form id="homeForm" method="post" >
<label for="name">Name: </label>
<input type="text" name="name"><br>
<label for="age">Age: </label>
<input type="number" name="age"><br>
<label for="workoutdays">How many days a week can you workout?</label>
<select name="workoutdays">>
<option value="1">3</option>
<option value="2">5</option>
</select><br>
<label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label>
<select name="workoutstyle">>
<option value="1">Gym</option>
<option value="2">Bodyweight</option>
</select><br>
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
<div class="form_result"></div>
</form>
<?php
$age = $_POST['age'];
$workoutdays = $_POST['workoutdays'];
$workoutstyle = $_POST['workoutstyle'];
?>
</div>
<br><br><br>
<?php include("footer.php"); ?>
</body>
</html>
I don't necessarily want an answer giving me the exact code to enter, but would appreciate being pointed in the right direction to get that form pulling data from MySQL, and using AJAX to print in the same window without refreshing.
THANK YOU
First of all, you need to post your request. With $.ajax this
//Do this thing on page load
$(function() {
//handle submit
$("#homeForm").submit(function(e) {
//customize your submit
e.preventDefault();
$.ajax({
type: "POST",
url: youURL, //maybe an url pointing to index.php
data: yourData, //attach everything you want to pass
success: function(response) {
$("#appWindow").html(response);
}
});
});
});
code should help. You need to make sure you pass the necessary elements and you provide the correct url. On server side, generate the desired html and send back as response.
In the script file
$(document).ready(function(){
$(document).on('click','#submit_btn',function(){
var url = '/xyz.php'; //full path of the function where you have written the db queries.
var data = '';//any data that you would like to send to the function.
$.post(url,{data: data}, function(result){
var arr = JSON.parse(result);
});
});
});
in your php file once your database query has been executed and you get the result. for example
$result = //result of your mysql query.
echo json_encode($result);
exit;

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

auto complete extender not working in PHP

this auto complete extender is working perfectly but i dont whats the reason its stopped working , No javascript error is coming .Here is my code
<script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="scripts/jquery-ui.min.js" type="text/javascript"></script>
<link href="scripts/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function() {
$("#autocomplete").autocomplete({
source: "searchEAN.php",
minLength: 2,//search after two characters
select: function(event,ui){
// alert ($value.$id);
alert (ui.item.value);
//do something, like search for your hotel detail page
}
});
});
</script>
</head>
<body>
<div class="demo">
<div class="ui-widget">
<label for="autocomplete">Hotel Name: </label>
<input id="autocomplete" name="autocomplete"/>
</div>
</div>
and this is searchEAN.php page code . its return data when i run this page directly by passing terms as query string
<?php
include_once('config.php');
if (isset($_GET['term'])) {
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT Distinct CONCAT(City,',',StateProvince,',',Country) AS value,EANHotelID AS id FROM ActivePropertyList WHERE City LIKE '%".$term."%' GROUP BY value limit 0,10 ";
echo $qstring;
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
mysql_close();
}
?>
searchEAN.php can be check here .live link and auto complete which is not working can be check here
your echo $qstring; is in your PHP script. Comment it out!
Sorry , Problem solved that is mine mistake , I echo the query to check it but forgot to comment it. thats the reason its no working .
I comment out the
//echo $qstring; in searchEAN.php file
and its working now
thanks

Submit Search query & get Search result without refresh

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.

Categories