dynamic <div> content on change <select> - php

what i want to do:
1.) is shown on page after first load.
When an user selects one or multiple options dynamic content is loaded into a <div>
2.) in this first dynamic <div> an other php page echos a second with further entries.
--- till here my code works just fine ---
3.) after selecting one or multiple options in this second <select> in the first dynamic <div> a second dynamic <div> should be printed with another <select>
But after selecting entries from second nothing is shown in second dynamic
Example:
- Page Load: First Cars, Bikes, Trucks, Planes...
- I choose "Cars"
- First dynamic <div> shows: <select> Mustang, Chrysler, Jeep, etc...
- I choose Chrysler
(till here my code works fine)
- Second dynamic <div> shows: red, white, brown, yellow, ...
My Code:
Page which is loaded in browser:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Unbenanntes Dokument</title>
</head>
<body>
<?
include_once('includes/functions.inc.php');
$conn = connection();
$sql = "SELECT * FROM Faecher WHERE Fach_Studienabschnitt = 1 ORDER BY Fachname ASC";
$sql_erg_VKH_Faecher = send_sql($sql);
mysql_close($conn);
?>
<!-- the select -->
<select name="Fach[]" size="25" multiple="multiple" id="Fach">
<?
echo '<optgroup label="Vorklinik-Humanmedizin">';
while($vkhfaecher = mysql_fetch_array($sql_erg_VKH_Faecher)){
echo "<option value=".$vkhfaecher['Fach_ID'].">".$vkhfaecher['Fachname']."(".$faecher[$vkhfaecher['Fach_ID']]['Fragenanzahl'].")"."</option>";
}
echo '</optgroup>';
?>
</select>
<!-- the DIVs -->
<div id="Semester"></div>
<div id="Tags"></div>
<!-- the jQuery -->
<script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$('#Fach').change(function(event) {
var form_data = $('#Fach').serialize();
$.ajax({
url: "ajax_reload.php",
type: "post",
data: form_data,
success: function(data){
//adds the echoed response to our container
$("#Semester").html(data);
}
});
});
</script>
<script type="text/javascript">
$('#Semester').change(function(event) {
var form_data = $('#Semester').serialize();
$.ajax({
url: "ajax_reload.php",
type: "post",
data: form_data,
success: function(data){
//adds the echoed response to our container
$("#Tags").html(data);
}
});
});
</script>
</body>
</html>
ajax_reload.php which dynamically loads content from mysql_db:
<?
session_start();
include_once('includes/functions.inc.php');
$conn = connection();
if(isset($_POST['Fach'])){
foreach($_POST['Fach'] as $elem){
$sql_fach_temp1 .= "T1.Fach_ID = ".$elem." OR ";
$sql_fach_temp2 .= "T2.Fach_ID = ".$elem." OR ";
}
$sql_fach_temp1 = substr($sql_fach_temp1, 0, -4);
$sql_fach_temp2 = substr($sql_fach_temp2, 0, -4);
$_SESSION['ajax_sql'] = "(".$sql_fach_temp1.") AND (".$sql_fach_temp2.")";
$sql = "SELECT DISTINCT T3.Semester,T3.Semester_ID FROM Fragen T1, Faecher T2, Semester T3 WHERE (".$sql_fach_temp1.") AND (".$sql_fach_temp2.") AND T1.Semester_ID = T3.Semester_ID";
$FaecherSemester_temp = send_sql($sql);
echo '<select name="Semester[]" size="25" multiple="multiple" id="Semester">';
while($semesterliste = mysql_fetch_array($FaecherSemester_temp)){
echo "<option value=".$semesterliste['Semester_ID'].">".$semesterliste['Semester']."</option>";
}
echo "</select>";
}
if(isset($_POST['Semester'])){
echo $_SESSION['ajax_sql']."ja";
foreach($_POST['Semester'] as $elem){
$sql_semester_temp .= "T3.Semester_ID = ".$elem." OR ";
}
$sql_semester_temp = substr($sql_semester_temp, 0, -4);
$sql = "SELECT DISTINCT T4.Tag, T4.Tag_ID FROM Fragen T1, Faecher T2, Semester T3, Tags T4, Frage_Tags T5 WHERE ".$_SESSION['ajax_sql']." AND (".$sql_semester_temp.") AND T1.Semester_ID = T3.Semester_ID AND T4.Tag_ID = T5.Tag_ID AND T1.Frage_ID = T5.Frage_ID";
$FaecherSemesterTags_temp = send_sql($sql);
echo '<select name="Tags[]" size="25" multiple="multiple" id="Tags">';
while($tagsliste = mysql_fetch_array($FaecherSemesterTags_temp)){
echo "<option value=".$tagsliste['Tags_ID'].">".$tagsliste['Tags']."</option>";
}
echo "</select>";
}
mysql_close($conn);
?>
I tried to copy the ajax code into ajax_reload.php so that the cod is echoed into the dynamic <div>, but no response...
any idea?
thanks a lot!

Since the #Semester SELECT is added dynamically, you need to use event delegation:
$('#SemesterDiv').on("change", "#Semester", function(event) {
var form_data = $('#Semester').serialize();
$.ajax({
url: "ajax_reload.php",
type: "post",
data: form_data,
success: function(data){
//adds the echoed response to our container
$("#TagsDiv").html(data);
}
});
});
I'm assuming you renamed <div id="Semester"> to <div id="SemesterDiv">, and similarly for the Tags DIV.

Related

How to populate Twitter Typeahead based on select box value?

I have an input text that is correctly populate with Twitter Typeahead. In this case i would like to select a value from select box and populate the input text with values that are related with selected dropdownlist value. I found similar questions about my doubt but unfortunatly i didnt get the correct way to solve this:
Dynamically populating Twitter Bootstrap Typeahead
Twitter bootstrap Typeahead to populate hrefs
jQuery Autocomplete / Twitter Typeahead Populate Multiple Fields
Below is the code that display a select box that is populate with php code and an input text that is populated with Twitter TypeAhead script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
</head>
<body>
<div class="container">
<br>
<h1>DYNAMIC TWITTER TYPEAHEAD</h1>
<br>
<div class="row">
<?php
// Include the database config file
include_once 'dbConfig.php';
// Fetch all the category data
$query = "SELECT * FROM categories ORDER BY category ASC";
$result = $db->query($query);
?>
<!-- category dropdown -->
<div class="col-md-4">
<select id="categoryFK" name="categoryFK" class="form-control">
<option value="">Select category</option>
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="'.$row['categoryID'].'">'.$row['category'].'</option>';
}
}else{
echo '<option value="">Category not available</option>';
}
?>
</select>
</div>
<div class="col-md-4">
<input type="text" name="products" id="products" class="form-control input-lg" autocomplete="off" placeholder="" />
</div>
</div>
</div>
</body>
</html>
Below is the script that call php script via Ajax:
<script>
$(document).ready(function(){
$('#categoryFK').on('change', function(){
var queryID = $(this).val();
if(queryID){
$('#products').typeahead({
source: function(query, result)
{
$.ajax({
url:"fetch.php",
method:"POST",
data: 'query='+queryID,
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
}
});
});
</script>
And below is the php script (fetch.php) that populate values according to categoryID:
<?php
//fetch.php
include 'dbConfig.php';
if(!empty($_POST["query"])){
$request = mysqli_real_escape_string($db, $_POST["query"]);
$query = "
SELECT * FROM products WHERE productName LIKE '%".$request."%' AND categoryFK = ".$_POST["query"]."
";
$result = $db->query($query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["productName"];
}
echo json_encode($data);
}
}
?>
As i showed the code above, when i type something into input text after i selected any option into select box, the input text with Twitter TypeAhead just populate one register.
In this case, how can i improve php code above to populate input text with values related with select box value correctly? Thanks.
I managed to solve the problem. Below are the scripts that i modified to adapt on my project:
AJAX
<script type="text/javascript">
var products;
$ ( function ()
{
$('#categoryFK').on('change', function(){
var queryID = $(this).val();
$.ajax({
url:"fetch.php",
method:"POST",
data: {
category: queryID
},
dataType:"json",
success:function(data)
{
$("#products").val ('');
products = data;
}
});
});
$('#products').typeahead({
source: function ( query, result )
{
result ( $.map(products, function (item)
{
return item;
}
));
}
});
});
</script>
And PHP script (fetch.php)
<?php
include 'dbConfig.php';
if ( isset ( $_POST [ 'category' ] ) ) {
$request = $db->real_escape_string($_POST["category"]);
$query = "
SELECT * FROM products WHERE categoryFK = ".$request."
";
$result = $db->query($query);
$data = array ();
if ( $result->num_rows > 0 )
{
while($row = $result->fetch_assoc ())
{
$data[]=$row["productName"];
}
echo json_encode($data);
}
}
?>
Now, with these modifications, i can select an option into "category" select box and after, type into input text where all valus related with selected option will be load :)

PHP: Fill combobox after choosing one option from another combobox using MySQL database

I have one combobox where I choose one option filled it up with the table 'distrito' where the columns it's 'ID' and 'nome'.
So far, so good. The problem is when I want to fill it up the other combobox depending on the option select in the first combobox. The table 'localidade' that fills this combobox uses the columns 'id', 'nome' and 'id_distrito'.
This is the code to fill the first combobox called 'distrito':
<?php
// Connects to your Database
include "config.php";
$QUERY_LISTAR_DISTRITO = "SELECT id, nome FROM distrito";
$DISTRITO = mysql_query($QUERY_LISTAR_DISTRITO) or die(mysql_error());
$nr_distrito = mysql_num_rows($DISTRITO);
while ($nr_distrito > 0) {
$row = mysql_fetch_row($DISTRITO);
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
$nr_distrito--;
}
?>
This is the code to fill the second combobox called 'localidade':
<?php
// Connects to your Database
include "config.php";
$id_distrito = $_GET['distrito'];
$QUERY_LISTAR_LOCALIDADE = "SELECT * FROM localidade WHERE localidade.id_distrito = $id_distrito";
$LOCALIDADE = mysql_query($QUERY_LISTAR_LOCALIDADE) or die(mysql_error());
$nr_localidade = mysql_num_rows($LOCALIDADE);
while ($nr_localidade > 0) {
$row = mysql_fetch_row($LOCALIDADE);
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
$nr_localidade--;
}
?>
This is the HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Test</title>
</head>
<body>
<form action="registarGestorBD.php" method="post" enctype="multipart/form-data">
Distrito: <select name="distrito" id="distrito">
<?php include 'listarDistritos.php'; ?>
</select> <br> <br>
Localidade: <select name="localidade" id="localidade">
<?php include 'listarLocalidades.php'; ?>
</select> <br> <br>
<input type="submit" name="button1" id="button1" value="Guardar">
</form>
</body>
</html>
Thanks in advance. :)
This will solve your problem. Change your HTML file to this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form action="registarGestorBD.php" method="post" enctype="multipart/form-data">
Distrito: <select name="distrito" id="distrito">
<?php include 'listarDistritos.php'; ?>
</select> <br> <br>
Localidade: <select name="localidade" id="localidade">
</select> <br> <br>
<input type="submit" name="button1" id="button1" value="Guardar">
</form>
<script type="text/javascript">
$(document).on('change','#distrito',function(){
var val = $(this).val();
$.ajax({
url: 'listarLocalidades.php',
data: {distrito:val},
type: 'GET',
dataType: 'html',
success: function(result){
$('#localidade').html();
$('#localidade').html(result);
}
});
});
</script>
</body>
</html>
What you need is basically an ajax call which will fire on the selection of first combo box. The ajax call will sends the value of the first combo box and will query the other table based on id.
this might help you
Combobox items based on selected item in another combobox
You need to be looking at ajax. Consider this example (modified from Wikipedia):
function sendToServer(){
// Initialize the Ajax request
var xhr = new XMLHttpRequest();
xhr.open('post', 'send-ajax-data.php');
// Track the state changes of the request
xhr.onreadystatechange = function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
var options = xhr.responseText.split(",");
populateComboBox(options)
}
}
}
// Send the request to send-ajax-data.php
xhr.send(distrito_id);
}
function populateComboBox(options){
var combo = document.getElementById("localidade");
$(options).each(function(i){
var opt = options[i];
var el = document.createElement("option");
el.textContext = opt;
el.value = opt;
combo.appendChild(el);
})
}
Then of course in your php, get the post variable distrito_id, do your query and return the results in a comma separated list!

make refresh without refreshing the all page

I made 2 dropdownlists which are filled from my database. In the first drop are countries and in the second are cities. When a user selects a country automatically in the second drop down appears all the cities from that country. The problem is that when I select another country all the page is refreshing and I want just that 2 drop down lists to do the refresh. I'm using Javascript and PHP. Here are the codes:
#$cat=$_GET['cat'];
$quer2=mysql_query("SELECT DISTINCT category,cat_id FROM category order by category");
if(isset($cat) and strlen($cat) > 0){
$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory");
}else{$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory order by subcategory"); }
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
while($noticia2 = mysql_fetch_array($quer2)) {
if($noticia2['cat_id']==#$cat){echo "<option selected value='$noticia2[category]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";
echo "&nbsp&nbsp";
echo "<select name='subcat'><option value=''></option>";
while($noticia = mysql_fetch_array($quer)) {
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
and this is the Javascript code:
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='index.php?cat=' + val ;
}
I want that when I change the country the all page doesn't refresh only those 2 drop down lists. Any help will be much appreciated.
U can use Ajax for acheving this.
Pls check this link Populate select list
If U are using jquery use .ajax(). Example of jquery ajax select list populate is Jquery Ajax Select List Populate
You need to use ajax. A very rudimentary suggestion would be:
//self.location = '...' - removed
ajax('index.php?cat=' + val).done(function (result) {
//update select boxes
});
Try this
index.php
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".Select1").change(function()
{
var id=$(this).val();
var dataString = 'your_param='+ your_param;
$.ajax
({
type: "POST",
url: "select_2.php",
data: dataString,
cache: false,
success: function(html)
{
$(".Select2").html(html);
}
});
});
});
</script>
<title>Untitled Document</title>
</head>
<body>
<?php
include("config.php");
$sql="SELECT * FROM your_table";
$result2 = mysql_query($sql);
?>
<select class="Select1">
<option value=""></option>
<?php
while($row2 = mysql_fetch_array($result2))
{
?>
<option value="<?php echo $row2['your_value']?>"><?php echo $row2['your_value']?> </option>
<?php
}
?>
</select><br />
<select class="Select2"></select>
</body>
</html>
And in select_2.php
<?php
include('config.php');
if($_POST['your_param'])
{
$your_param=$_POST['your_param'];
$sql = mysql_query("SELECT * FROM yortable WHERE param = '".$your_param."'") or die(mysql_error());
while($row=mysql_fetch_array($sql))
{
$your_value=$row['your_param'];
echo '<option></option>';
echo '<option value="'.$your_value.'">'.$your_value.'</option>';
}
}
?>
Yep you're going to need to use AJAX in order to just update part of the page. The easiest way to use AJAX is through JQuery. Here's their API for AJAX.

Detect where there are no entries for an HTML menu-submenu system

I have MySQL tables looking like this:
regions table
id | region
-------------------
1 | Region1
2 | Region2
...
and schools table
region_id | school
-------------------
1 | schno1
1 | schno5
1 | schno6
2 | scho120
My page works like this: At first, page populates #regions select menu from db table named "regions". when user selects #region, the JS sends selected region's value to search.php. Server-side PHP script searches db table named "schools" for #region (previously selected menu) value, finds all matches and echoes them.
Now the question is, how can I hide #class and #school select menus, and show only error message "there is no school found in this region" if no matches are found? How to check if there's no result from search.php? I'm a beginner to JS.
My JavaScript looks like this: http://pastie.org/2444922 and the piece of code from form: http://pastie.org/2444929 and finally search.php: http://pastie.org/2444933
Update
I changed my JS but no success.
$(document).ready(function(){
$("#school").hide();
$("#class").hide();
searchSchool = function(regionSelect){
var selectedRegion = $("select[name*='"+regionSelect.name+"'] option:selected").val();
if (selectedRegion!='0'){
$.ajax({
type: "POST",
url : "core/code/includes/search.php",
data: "&region_id="+selectedRegion,
success: function(result, status, xResponse){
if (result!=null){
$("#school").show();
$("#class").show();
$("#school").html(result);
}else{
$("#error").html("There is no school found in this region");
$("#school").html('');
$("#school").hide();
}
},
error: function(e){
alert(e);
}
});
}else{
$("#error").html('Please select a region first');
$("#school").html('');
$("#school").hide();
$("#class").hide();
}
}
});
You could try this
index.php :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Ajax With Jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
searchSchool = function(regionSelect){
var selectedRegion = $("select[name*='"+regionSelect.name+"'] option:selected").val();
if (selectedRegion!='0'){
$.ajax({
type: "POST",
url : "search.php",
data: "&region_id="+selectedRegion,
success: function(result, status, xResponse){
alert(result);
if (result!=''){
$("#school").show();
$("#school").html(result);
}else{
$("#error").html("There is no school found in this region");
$("#school").html('');
$("#school").hide();
}
},
error: function(e){
alert(e);
}
});
}else{
$("#error").html('Please select a region first');
$("#school").html('');
$("#school").hide();
}
}
</script>
</head>
<body>
<?php
$username="root";
$password="";
$database="test";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM regions";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "<b><center>Database Output</center></b><br><br>";
?>
<select name="region" id="region" onchange="searchSchool(this)">
<option value="0">Please select a Region</option>
<?php
while($data = mysql_fetch_array( $result ))
{
?>
<option value="<?php echo $data['id']?>"><?php echo $data['name']?></option>
<?php
}
?>
</select>
<select name="school" id="school"></select>
<span id="error"></span>
</body>
</html>
Search.php:
<?php
$username="root";
$password="";
$database="test";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
if(isset($_POST['region_id'])) {
$query = "SELECT * FROM schools WHERE region_id='".$_POST['region_id']."'";
$result=mysql_query($query);
$num = mysql_numrows($result);
if ($num>0){
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
}
else{
return null;
}
}
mysql_close();
?>
Well i cannot exactly read through your full code but i can give you a mock up of what you might wanna do.
have both the dependant drop downs wrapped in a div.
<div id="dep1"></div>
<div id="dep2"></div>
Now in server side after making the validations if u find elements create a drop down and send it here or just send an error message.
<?
if($num>0) {
?>
<select>
<?
foreach($element as $ele) {
<option><?=$ele?></option>
}
?>
</select>
<?
} else {
?>
<div class="error">No regions found</div>
<? } ?>
Your js would look something like
$("#dep1").html(loadbar).load("mypage.php","region="+regionid);
I think the issue resides in your jQuery code on lines 27-30. There is no element with ID = cl_dropdown and the comma delimited makes it look for cl_dropdown inside of sch_dropdown.
My guess is that the second select used to have the id cl_dropdown at one point. If so, the HTML for it should look like this:
<select id="cl_dropdown" name="class">
You should also have an element for the message. According to the jQuery, you are supposed to have an #no_sch element but I don't see it.
<div id="no_sch"></div>
Then replace lines 27-30 with the following:
if (!results) {
$("#sch_dropdown").hide();
$("#cl_dropdown").hide();
$('#no_sch').show();
$('#no_sch').text('no matches found');
};

Using jQuery in MySQL php

I am new to using Jquery using mysql and PHP.
I am using the following code to pull the data. But there is not data or error displayed.
JQUERY:
<html>
<head>
<script>
function doAjaxPost() {
// get the form values
var field_a = $("#field_a").val();
$.ajax({
type: "POST",
url: "serverscript.php",
data: "ID="+field_a,
success: function(resp){
$("#resposnse").html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<select id="field_a">
<option value="data_1">data_1</option>
<option value="data_2">data_2</option>
</select>
<input type="button" value="Ajax Request" onClick="doAjaxPost()">
Here
<div id="resposnse">
</div>
</body>
and now serverscript.php
<?php
if(isset($_POST['ID'])) {
$nm = $_POST['ID'];
echo $nm;
//insert your code here for the display.
mysql_connect("localhost", "root", "pop") or die(mysql_error());
mysql_select_db("JPro") or die(mysql_error());
$result1 = mysql_query("select Name from results where ID = \"$nm\" ")
or die(mysql_error());
// store the record of the "example" table into $row
while($row1 = mysql_fetch_array( $result1 )) {
$tc = $row1['Name'];
echo $tc;
}
}
?>
Like Mike said, this also worked for me when I put it in the ready function and removed the button onclick. Open up your error console in Firefox and see if it is outputting anything
<?php
if(isset($_POST['ID'])){
echo ($_POST['ID']);
exit;
}
?>
<!DOCTYPE html>
<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> Heather Alexandra </title>
<script type="text/javascript" src="../intranet/include/js/jQuery/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#ajax").click(function(){
$.ajax({
type: "POST",
url: "test.php",
data: "ID="+$("#field_a").val(),
success: function(resp){
$("#resposnse").html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
</head>
<body>
<div style="margin: 0 auto; width: 822px;">
<select id="field_a">
<option value="data_1">data_1</option>
<option value="data_2">data_2</option>
</select>
<input id="ajax" type="button" value="Ajax Request">
<div id="resposnse"></div>
</div>
</body>
</html>
I just did everything you did except changed the serverscript.php to:
<?php
if(isset($_POST['ID'])) {
$nm = $_POST['ID'];
echo $nm;
}
?>
And the script worked fine. I think all you have to do is get back down to the basics and find out what is actually generating the error. Try using firebug for firefox to see if you are generating any script errors. If not try changing the serverscript.php to use $_GET and type the following address to see what you get: http://yourtestserver/serverscript.php?ID=data_1
Debugging can get tricky when you deal with ajax but if you break it down to it's individual pieces it should make it easier.

Categories