While Loop, jQuery and AJAX mysql query - php

I'm working on a message system where users submit one response to another user. The receiver then views all of his messages in a while loop. I created a delete button that will delete the whichever message the delete button is linked to. I have two problems. First, the delete button does not work, and second, when it was working (it no longer is) the while loop was linking all the delete buttons to the first message and not individually to each message the while loop produced. Also, I'm aware that mysql is deprecated. Will be making the transition over soon.
Here is the first code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript" >
function load(thefile, thediv) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile + key, true);
xmlhttp.send();
}
</script>
<?php
while($ergo_data = mysql_fetch_assoc($ergo_query_result)) {
echo 'Message: ' . $ergo_data['ergo'] . '<br>';
echo 'From: ' . username_from_user_id($ergo_data['user_id_seeker']) . '<br>';
echo 'Time submitted: ' . $ergo_data['ergo_time_submitted'] . '<br><br><br><br>';
echo $ergo_data['primary_key'];
?>
<div class="changes">
<input type="button" value="delete" class="<?php echo $ergo_data['primary_key']; ?>"
name="<?php echo $ergo_data['user_id_seeker']; ?>"
onclick="load('ajax_ergo_list.php?key=',
'delete');">
</div>
<script type="text/javascript" >
$(document).ready(function(){
var key = $(".changes :input").attr("class");
alert(key);
});
</script>
<br>
<br>
<br>
<?php
}
?>
<div id="delete"></div>
Here is the second file containing what I want to happen when the button is pressed.
if (isset($_GET['key'])) {
$key = sanitize($_GET['key']);
}
if (!empty($key)) {
$query = "DELETE FROM `ergo` WHERE `primary_key` = '$key'";
$query_run = mysql_query($query);
echo 'Deleted!';
}
?>

Ok, first off, this is all sorts of crazy code you got going on here...
<script type="text/javascript" >
$(document).ready(function(){
var key = $(".changes :input").attr("class");
alert(key);
});
</script>
You have your script inside a while loop. That will alert as many times as the loop is. And that is really all the function does. It's not setting a global variable or anything.
In regards to jQuery, use it:
function load(thefile, thediv) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile + key, true);
xmlhttp.send();
}
Condense that to this:
function load(thefile, thediv) {
$.get(thefile+key,function(responseText){
$('#'+thediv).html(responseText);
});
}
In regards to your question about the delete function:
<div class="changes">
<input type="button" value="delete" class="<?php echo $ergo_data['primary_key']; ?>"
name="<?php echo $ergo_data['user_id_seeker']; ?>"
onclick="load('ajax_ergo_list.php?key=',
'delete');">
</div>
Your onclick is the javascript that is firing. You have the first variable set to the link and the second to the action I am guessing? In your function code, the second variable is supposed to be the div where the info is displayed. The key is no where to be found. Try doing this instead:
<div class="changes">
<input type="button" value="delete" class="<?php echo $ergo_data['primary_key']; ?>"
name="<?php echo $ergo_data['user_id_seeker']; ?>"
onclick="load('ajax_ergo_list.php?key=<?php echo $ergo_data['primary_key'];?>',
'delete');">
</div>
And your load function to this:
function load(thefile, thediv) {
$.get(thefile,function(responseText){
$('#'+thediv).html(responseText);
});
}
Good luck!

Related

Confirm button before running deleting routine from website

I have a page on my website that is dynamically created with information from an SQL database. As well as the data being displayed a delete link is also created for each record which links to a php file called deleteRecord.php that deletes that record from the database.
Is there any way I can incorporate a confirmation message so that when the Delete link is clicked it will only run the deleteRecord.php file if the response is Yes?
You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
Delete
In a function:
Delete
and then put this in <head>:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
Delete
And put this in <head>:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"] is set.
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
You can do it with an confirm() message using Javascript.
Try this one :
<script type="text/javascript">
var baseUrl='http://example.com';
function ConfirmDelete()
{
if (confirm("Delete Account?"))
location.href=baseUrl+'/deleteRecord.php';
}
</script>
echo '<a type="button" onclick="ConfirmDelete()">DELETE ACCOUNT</a>';
<?php
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));
if(isset($_POST[add]))
{
$sno = mysqli_real_escape_string($con,$_POST[sno]);
$name = mysqli_real_escape_string($con,$_POST[sname]);
$course = mysqli_real_escape_string($con,$_POST[course]);
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";
//echo $query;
$result = mysqli_query($con,$query);
printf ("New Record has id %d.\n", mysqli_insert_id($con));
mysqli_close($con);
}
?>
<html>
<head>
<title>mysql_insert_id Example</title>
</head>
<body>
<form action="" method="POST">
Enter S.NO: <input type="text" name="sno"/><br/>
Enter Student Name: <input type="text" name="sname"/><br/>
Enter Course: <input type="text" name="course"/><br/>
<input type="submit" name="add" value="Add Student"/>
</form>
</body>
</html>
Another method using both onlcick & form submit button with php record id value (record to be delete).
Use php code to get the record ID to be deleted. This is working for me.
<form action="deleteRecord.php" method="POST">
<button onclick="return confirm('Are you sure! want to delete?')" type="submit" name="id" value="<?=$record['id'];?>" >Delete</button>
</form>
deleteRecord.php example file
<?php
$con=mysqli_connect("localhost","root","","dbname") or die(mysqli_error($con));
if(isset($_POST['id']))
{
$id = mysqli_real_escape_string($conn, $_POST['id']);
$query = "DELETE FROM table_name WHERE id='$id' ";
$query_run = mysqli_query($conn, $query);
}
mysqli_close($con);
if($query_run)
{
echo "Deleted Successfully";
exit(0);
}
else
{
echo "Not Deleted";
exit(0);
}
?>

I am using ajax to show the output after entering some data on textfield ,it is not showing proper output?

Here is html program... here I am using ajax to show the output after entering some data on textfield ,it is giving only first response when food='' ,after that it is not showing another response like we don't have . or we do have .
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h1>choose your favorite food</h1>
<input type="text" id="inputuser">
<div id="usererror"></div>
</body>
</html>
here is foodstore.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food=$_GET['food'];
$foodArray=array('shahi paneer','matar paneer','matar alu','raita');
if(in_array($food,$foodArray))
{
echo 'we do have '.$food.'!';
}
elseif($food=='')
{
echo 'please enter any dish';
}
else
{
echo 'we dont have '.$food.'!';
}
echo '</response>';
?>
here is foodstore.js
var xmlHttp=createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if (window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlHttp)
alert("cant create that object");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState==0 ||xmlHttp.readystate==4)
{
dish=encodeURIComponent(document.getElementById("inputuser").value);
xmlHttp.open("GET","foodstore.php?food="+dish, true);
xmlHttp.onreadystatechange=handleServerResponse;
xmlHttp.send(null);
}
else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse=xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById("usererror").innerHTML='<span style ="color:red">'+message+'</span>';
setTimeout('process()',1000);
}
else
{
alert('something went wrong');
}
}
}
The approach should be
Write onchange event (onchange of textbox content call the process() function) for the text box.
or
To add a button to triggering the function. => user enters the dish and clicks on button.
Approach one (Using jQuery)
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<!--<script type="text/javascript" src="foodstore.js"></script>-->
<script>
$(document).on("keyup","#inputuser", function(){
var dish = $(this).val();
$.ajax({
type: "GET",
url: 'foodstore.php',
data : {food:dish},
success: function(data){alert(data);
$('#usererror').html(data);
}
});
});
</script>
</head>
<body>
<h1>choose your favorite food</h1>
<input type="text" id="inputuser" value="" />
<div id="usererror"></div>
</body>
</html>
foodstore.php
<?php
$food=$_GET['food'];
$foodArray=array('shahi paneer','matar paneer','matar alu','raita');
if(in_array($food,$foodArray)) {
echo 'we do have '.$food.'!';
}
elseif($food=='') {
echo 'please enter any dish';
} else {
echo 'we dont have '.$food.'!';
}
?>
change your onload on onBlur and remove from the onload and place in input:
<input type="text" id="inputuser" onblur="process()">

submit a form via Ajax and update a result div

I was using a self submitting form to process the data but I now need to process it separately so now I need to submit a form, return the results and place it in a div. It seems using AJAX is a good way to do this to have the data return to the original page where the form is. I have had a look at alot of examples and I don't really understand how to do it or really how its working.
Say I wanted to send this form data from index.php to my process page twitterprocess.php what do I need to do and get it to return to display the data processed.
<form method="POST" action="twitterprocess.php">
Hashtag:<input type="text" name="hashtag" /><br />
<input type="submit" value="Submit hashtag!" />
</form>
This is what I have been using to display the results.
<?php foreach($results as $result) {
$tweet_time = strtotime($result->created_at);?>
<div>
<div class="tweet"> <?php echo displayTweet($result->text),"\r\n"; ?>
<div class="user"><?php echo "<strong>Posted </strong>" . date('j/n/y H:i:s ',$tweet_time) ?><strong> By </strong><a rel="nofollow" href="http://twitter.com/<?php echo $result->from_user ?>"><?php echo $result->from_user ?></a></div>
</div>
<br />
<? } ?>
I'm new to AJAX but any guidance would be greatly appreciated
*When you use AJAX the output generated on other page is the result for this page.
*Now when you want to post data and retrieve results through the use of AJAX then in form part of your html don't use type="submit" for button, but simply go for type="button".
*action attribute should be left blank as you are going to trigger the action through your AJAX code.
*Well rest all your solution in the code snippet below:
Below is the HTML code along with AJAX
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Form Handling Through AJAX</title>
<script type="text/javascript">
function loadXmlDoc(fname, lname){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=" + fname + "&" + "lname=" + lname);
}
</script>
</head>
<body>
<p>
<span id="ajaxify"> </span>
</p>
<form id="frm" action="#">
<input type="text" name="fn" />
<input type="text" name="ln" />
<input type="button" name="submit" value="submit" onclick="loadXmlDoc(fn.value, ln.value)" />
</form>
</body>
</html>
Below is the PHP code that is used in above code
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
echo "Hello " . $fname . " " . $lname;
?>
Assign some id to your submit button, i'd use id="submit" and some id for your text field (i use id="text");
Client-side js:
$("#submit").click(function () {
var postData = new Object(); //for complex-form
postData.hashTag = $("#text").val();
$.ajax({
type: 'POST', //or 'GET' if you need
contentType: "application/json; charset=UTF-8", //i use json here
dataType: "json",
url: "some_url",
data: JSON.stringify(postData), //or smth like param1=...&param2=... etc... if you don't want json
success: function (response) {
//handle response here, do all page updates or show error message due to server-side validation
},
error: function () {
//handle http errors here
}
});
return false; //we don't want browser to do submit
});
So, if user has js enabled = your code will do ajax request, otherwise - regular post request will be made;
On a server-side you have to handle ajax and regular submit different to make it work correct in both cases. I'm not good in php so can't do any advise here
You can use jQuery, for example,
function doPost(formdata){
var url="/twitterprocess.php";
var senddata={'data':formdata};
$.post(url,senddata,function(receiveddata){
dosomethingwithreceiveddata(receiveddata);
}
your php will get senddata in JSON form. You can process and send appropriate response. That response can be handled by dosomethingwithreceiveddata.
I find the Ajax Form plugin a good tool for the job.
http://www.malsup.com/jquery/form/#tab4
A basic code example could be:
$(document).ready(function() { // On Document Ready
var options = {
target: '#output1', // ID of the DOM elment where you want to show the results
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
// the callback function
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
All your PHP file have to do is echo the html (or text) back that you want to show in your DIV after the form has been submitted.
If you do not want to use jquery try this in pure javascript
function SendData(Arg) {
xmlhttp=null;
var uri = "/twitterprocess.php";
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null) {
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
if(xmlhttp.status==200) {
var xmlDoc = xmlhttp.responseXML;
var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue;
var Xml2String;
if(xmlDoc.xml) {
Xml2String = xmlDoc.xml
} else {
Xml2String = new XMLSerializer().serializeToString(xmlDoc);
}
document.getElementById("CellData").value=Xml2String;
} else {
alert("statusText: " + xmlhttp.statusText + "\nHTTP status code: " + xmlhttp.status);
}
}
}
}

how to catch post variable when i post my submit form php ajax

I'm posting on this forum because I don't manage to received my information that I posted by my submit form into my showidz.php page. I don't know how to catch my $_POST["numversion"] which generated my ajax script in my docversion.php.
to sum up, I have a form page docversion.php where I enter the document name and I catch on the same page the "linked" versions which are possible for this document entered by using an ajax script. This works fine.
My problem is when I click on the submit to throw information from docversion.php to showidz.php I cannot catch the numversion.
Here's my source code :
docversion.php
<script type='text/javascript'>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) // Firefox
xhr = new XMLHttpRequest();
else
if(window.ActiveXObject) { // Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else { // XMLHttpRequest non supporté par le navigateur
alert("Browser not compatible with XMLHTTPRequest...");
xhr = false;
}
return xhr;
}
/**
* catch on click
*/
function go(){
var xhr = getXhr();
// do when we have the answer
xhr.onreadystatechange = function(){
// do if the server answer is OK
if(xhr.readyState == 4 && xhr.status == 200){
leselect = xhr.responseText;
// use innerHTML
document.getElementById('numeroversion').innerHTML = leselect;
}
}
// post to rep_PhpAjax.php to have version
xhr.open("POST","rep_PhpAjax.php",true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sel = document.getElementById('course');
iddocument = sel.value;
xhr.send("idDoc="+iddocument);
}
</script>
<form name="test1" method="post" action="showidz.php" >
Nom du document <label>:</label><br>
<input type="text" name="course" id="course" size="40" onclick='go()'/><br/>
<label>Version</label>
<div id='numeroversion' style='display:inline'>
<select name='numeroversion'>
<option value='-1'>Choose a version</option>
</select>
</div>
<input type="submit" name="OK" value="OK">
</form>
rep_PhpAjax.php
<?php
echo "<select name='numeroversion'>";
if(isset($_POST["idDoc"])){
$res = mysql_query("SELECT `NumeroVersion`
FROM `version`, document
WHERE document.idversion = version.idversion
and document.NomDocument ='".$_POST["idDoc"]."'");
while($row = mysql_fetch_assoc($res)){
echo "<option value='".$row["idversion"]."'>".$row["NumeroVersion"]."</option>";
}
}
echo "</select>";
?>
showidz.php : The page with the problem where i cannot have the numeroversion which has been posted for docversion.php:
<?php
$docname = $_POST["course"];
$idversion = $_POST["numeroversion"];
echo "$docname</br>";
echo $idversion;
?>
Hope that someone could help me on my problem.
there seems to be nothing wrong with the form data that gets sent to showidz.php
but a problem might be the fact that you are calling that ajax on click. maybe you should chnage
onclick="go();"
to
onkeyup="go();"
in docversion.php at line 54 so that the ajax is called every time you type a letter
I rewrited what you want to do using jQuery. You can see it in action here.
Folder Structure:
site -+- displayDocument.php
|- ajaxGetVersions.php
|- ajaxGetVDocument.php
|- queries.php
displayDocument.php:
<?php
require_once 'queries.php';
$documents = getDocuments();
?>
<form id="myform" method="post" action="" >
<label for="documents">Choose a document</label>
<select id="documents" name='documents[]'>
<option value='0'>Choose a document</option>
<?php foreach ($documents as $document) : ?>
<option value='<?php echo $document ?>'><?php echo $document ?></option>
<?php endforeach; ?>
</select>
<br/>
<label for="versions">Version </label><span id="refreshVersions"></span>
<select id="versions" name='versions[]'>
</select>
<br/>
<input type="submit" name="OK" value="OK">
</form>
<div id="refreshDocument"></div>
<div id="document"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$("#documents").change(function() {
$("#refreshVersions").text("refreshing...");
$.post("ajaxGetVersions.php", { documentId: $(this).val() },
function(data) {
$("#versions").html(data);
$("#refreshVersions").text("");
});
});
$("#myform").submit(function(e) {
$("#refreshDocument").text("refreshing...");
$.post("ajaxGetDocument.php", { documentId: $("#documents").val(), version: $("#versions").val() },
function(data) {
$("#document").html(data);
$("#refreshDocument").text("");
});
e.preventDefault();
});
</script>
ajaxGetVersions:
<?php
require_once 'queries.php';
if (!isset($_POST['documentId'])) {
die('missing post parameter: documentId');
}
$versions = getVersionsOfDocument($_POST['documentId']);
?>
<?php foreach ($versions as $version): ?>
<option value='<?php echo $version ?>'><?php echo $version ?></option>
<?php endforeach; ?>
ajaxGetDocument:
if (!isset($_POST['documentId']) || !isset($_POST['version'])) {
die('missing post parameter: documentId or version');
}
$doc = getDocument($_POST['documentId'], $_POST['version']);
?>
<h1><?php echo $doc["documentId"] ?></h1>
<h2><?php echo $doc["version"] ?></h2>
<h3><?php echo $doc["author"] ?></h3>
<p>
<?php echo $doc["content"] ?>
</p>
queries.php:
<?php
// little database replace
$documents = array("Book1" => array("beta", "1.0", "1.1", "2.0"), "Book2" => array("1.0", "1.1"), "Book3" => array("beta"));
function getVersionsOfDocument($documentId) {
// replace with database fetch
global $documents;
return $documents[$documentId];
}
function getDocuments() {
// replace with database fetch
global $documents;
return array_keys($documents);
}
// get a document by id and version
function getDocument($documentId, $version) {
//implement your own
return array("documentId" => $documentId,
"version" => $version,
"author" => "...",
"content" => "bla bla");
}

jQuery and JavaScript AJAX Database Queries

I seem to have no luck with these darn AJAX MySQL queries...
I'm trying to query the database when a selection from a drop-down menu is made, and fill a div with the results from the script. I've tried two different ways, with no luck either time.
METHOD 1
Javascript
var ajaxRequest;
var create_url = "create_script.php";
var process_url = "process.php";
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
}
}
}
function races(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('race_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=race&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
function classes(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('class_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=classes&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
the page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="races('.$row['race_id'].');" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="classes('.$row['race_id'].');" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<br />
<div id="race_info"></div>
<br />
<hr />
<br />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
METHOD 2
AJAX
$(document).ready(function() {
$("#race_select").change(function() {
var race = $("#race").val();
$.ajax({
url: 'create_script.php',
data: 'mode=race&id=' + race,
dataType: 'json',
success: function(data)
{
$("#race_info").html(data);
}
});
});
$("#class_select").change(function() {
var class = $("#class").val();
$.post("create_script.php", { mode: "class", id: class }, function(data) {
$("#class_info").html(data);
});
});
});
The page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="race" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="class" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<div id="race_info"></div>
<hr />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
None of the attempts have worked at all. I'm not sure what I'm doing wrong. There's not even a POST request being made on the select option change, according to firebug.
well for starters, in method two, all of your select options have the same ids. therefore, when querying:
var race = $("#race").val();
you will always get the first option.
instead, within the change function, this will refer to the selected element. so:
var race = $(this).val();
will get what you want
EDIT
Here is a simplified example using your code demonstrating your desired behavior in jsfiddle form: http://jsfiddle.net/7Xtqv/1/
hope that helps
In your jQuery AJAX request, you're setting dataType to JSON. So jQuery attempts to parse the JSON once received. If it fails, nothing happens. Not even the request shown in Firebug.
If you're using html in your AJAX return, you should set the dataType to HTML.
EDIT
Oh and in the second request in your jQuery file, you're doing var class = $("#class").val();. You might want to avoid naming your vars with reserved names: http://www.quackit.com/javascript/javascript_reserved_words.cfm
EDIT2
As #pthurlow noticed, there's a big fail with your IDs names. You're trying to get #race select, but there's no race ID in your HTML. There's a #race_select but it's different from #race.
It also fails with your #class stuff.

Categories