let's say i'm generating some sort of html table (from mysql queried data) with a checkbox at each row with something like
$display_string = "<form action=\"delete.php\" method=\"post\">";
$display_string .= "<div><input type=\"button\" VALUE=\"Button1\"></div>";
$display_string .= "<div><input type=\"button\" VALUE=\"Button2\"></div>";
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr onmouseover=\"this.className = 'hlt';\" onmouseout=\"this.className = '';\">";
$display_string .= "<td class='blank'><input type=\"checkbox\" /></td>";
$display_string .= "<td class='data'>" . $row['first_name'] . "</td>";
$display_string .= "<td class='data'>" . $row['last_name'] . "</td>";
$display_string .= "<td class='data'><a href='" . $row['email'] . "'>" . $row['email'] . "</a></td>";
etc...
etc...
$display_string .= "</form>";
what i'd like to happen now, after various checkboxes are selected are two things:
1) for example, call delete.php when Button1 is clicked to delete the selected rows.
2) some other php file called when Button2 is clicked
I have access to $row['ID'] which I can use to name each checkbox, i'm just not sure how to incorporate it since i'm new to php
UPDATE
The following seems to work for my purposes
I've got the following html-
<form name='myForm' method=\"post\" >
<input type=\"submit\" onClick=\"deleterow(document.myForm)\" VALUE=\"Delete ROWs\">
while($row = mysql_fetch_array($qry_result)){
<input type=\"checkbox\" name='rows' value=" .$row['ID']. "/>
Javascript is as follows-
<script language=\"javascript\" type=\"text/javascript\">
function deleterow(form){
if (!confirm(\"Are you sure you want to delete?\")) return false;
var queryString = \"?ID=\";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += \"-\";
}
}
queryString = queryString.slice(0, -1);
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");
} catch (e) {
try{
ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");
} catch (e){
// Something went wrong
alert(\"Your browser broke!\");
return false;
}
}
}
var ajaxRequest; // The variable that makes Ajax possible!
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open(\"GET\", \"delete_row.php\" + queryString, true);
ajaxRequest.send(null);
confirm('Delete successful!');
}
then with delete_row.php you can do all you need to with a mysql query, and new data can be sent back and displayed with
<div id='ajaxDiv'></div>
To get a clear code I suggest you to avoid two buttons firing two several actions. Instead use a simple javascript method to append a parameter to the submitted form to get rid of what button has been pushed.
<script type="text/javascript">
function submitForm( act ){
$('#act').val(act);
$('#myForm').submit();
}
</script>
<form id="myForm" ... >
<input type="hidden" id="act" value="" />
<button onClick="submitForm(1)">1</button>
<button onClick="submitForm(2)">2</button>
</form>
this is just an example (using jquery).
About your second answer (checkboxes):
<input type="checkbox" name="selectedboxes[]" value="someIdHere" />
when the form is submitted you'll receive an array "selectedboxes" as a param in which you get checked checkboxes.
You can do it changing the Form action, for example if you click BUTTON 1 it will change the action to DELETE.PHP, take a look to this post:
Changing the action of a form with javascript/jquery
They use JQuery and they have multiples answer how to do it
Related
I have a table for a sports day where there are 4 columns name, house, event, result. I have no problem creating and displaying the database but i want to be able to search in a bar and to use AJAX to automatically search all 4 columns for whats in the search bar. I am using PHPmyadmin to store the database with mySQLI. i am able to display the database on the page that i want. I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search. I have never used Ajax before so sorry for my bad code as it is all from w3schools site. the DB is called sports_day and the table is called full_results. here is my current code.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
and on a page called results_query.php is this code
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql="SELECT * FROM full_results WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
at the moment what happens is none of the table is shown and when i type anything in the search box the whole table appears along with in plain text at the bottom the title and all the contents of the table in a long line.
any suggestion to get my code to work would be greatly appreciated!
thanks!
The solution would be like this:
Keep your HTML search form as it is.
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
... I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search.
See this <div> section here,
<div class="col-sm-12">
...
</div>
You didn't put anything in this <div> section. First of all, you have to display your entire table in this section, which you can later filter out using the AJAX request. Also, assign an id to this <div> section so that it could be easier for you put the AJAX response in this <div> section. So the code for this <div> section would be like this:
<div class="col-sm-12" id="pupil-info">
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
Change your Javascript/AJAX code in the following way,
<script>
function showUser(str){
var str = str.trim();
var xmlhttp;
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("pupil-info").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
Please note that you should encode the user inputted str value using encodeURIComponent() function before passing it to the results_query.php page.
Finally, on results_query.php page process your AJAX request like this:
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
if(isset($_GET['q']) && !empty($_GET['q'])){
$sql .= " WHERE CONCAT(id, NAME, HOUSE, EVENT, RESULT) LIKE '%".$_GET['q']."%'";
}
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
}else{
echo "<tr>";
echo "<td colspan='4' style='text-align:center;'>No records found</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
If you use your 'results_query.php' file only for getting the data from database, then you don't need to create a <body> tag. If you use only PHP then you can easily skip any plane HTML. That's just a digression :)
But to the point.
You can change the way you return your data from database. I think, instead of doing a lot of echo's it is better to add result to the variable and echoing the variable at the end.
$data = '<tr>' . '<th>NAME</th>' . '<th>HOUSE</th>' . '<th>EVENT</th>' . '<th>RESULT</th>' . '</tr>';
while($row = mysqli_fetch_array($result)) {
$data .= '<tr>';
$data .= '<td>' . $row['NAME'] . '</td>';
$data .= '<td>' . $row['HOUSE'] . '</td>';
$data .= '<td>' . $row['EVENT'] . '</td>';
$data .= '<td>' . $row['RESULT'] . '</td>';
$data .= '</tr>';
}
$data .= '</table>';
mysqli_close($con);
echo $data;
See if this changes something.
What about showing entire table after the page's loaded, you will have to change both PHP and JavaScript code a little bit.
You can change your JS so it gets everything from your full_results table after page is loaded.
There are several ways to do this and you can read about them here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The easiest way would be to do this this way:
<script>
function showUser(str) {
var url;
var xmlhttp;
if (str == "") { //if empty string - get all data
url = "results_query.php";
} else { //get particular data otherwise
url = "results_query.php?q="+str;
}
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
<script>
//calling your function with empty string because we want to get all data
showUser("");
</script>
and in the PHP file you can do something like this:
<?php
$q = 0;
//check if 'q' parameter was passed
if(isset($_GET['q'])) {
$q = intval($_GET['q']);
}
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";
Now your JavaScript function will be called after loading your page.
It will call your PHP script with AJAX and this script should return all data from your table.
In line ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results"; there is a simple check if $q is different from 0. Our variable will be set to 0 if no argument was passed, so whenever $q is equal to '0', we just want to get all the data from full_results and specific data otherwise.
I also added var xmlhttp because it is only local variable.
You can read more about that in here:
https://stackoverflow.com/a/1471738/7301294
I hope it will help you.
Let me know if you have any other problems and never be afraid to ask.
Good luck!
##ajax function in the php file i need to send id,and two input field values to my updateReq.php file ##
function updateFunction(del,inp1,inp2){
var ajaxRequest;
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!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?del=" + del;
queryString += "&inp1=" +inp1;
queryString += "$inp2=" +inp2;
ajaxRequest.open("GET", "updateReq.php" + queryString, true);
ajaxRequest.send(null);
}
in my file i use this part to access ajax function
The ajax function and the bleow code on the same php file
<?php
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<td><input type='text' id='inp1' name='inp1' value='$row[cname]' /></td>";
$display_string .= "<td><input type='number' id='inp2' name='inp2' value='$row[rank]'/></td>";
$display_string .= "<td><a href='#' onclick='deleteFunction($row[id])'>Delete?</a></td>";
$display_string .= "<td><a href='#' onclick='updateFunction( $row[id], $row[cname] ,$row[rank])'>Update?</a></td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
?>
This is my updateReq.php
<?php
// Retrieve data from Query String
include 'config.php';
$id = $_GET['del'];
$inp1 = $_GET['inp1'];
$inp2 = $_GET['inp2'];
// Escape User Input to help prevent SQL Injection
$id = mysql_real_escape_string($id);
$query=mysql_query("update rcategories set cname='$inp1' rank='$inp2' where id='$id'") or die("can not update");
?>
You have a bug in your code..
queryString += "$inp2=" +inp2; change it to queryString += "&inp2=" +inp2;
HTH
Please check your queryString you are using $ instead of &
I have an php generated table/form with checkboxes like this:
if ($query) {
if (!mysqli_num_rows($query)) {
//Empty storage
echo "There are no items in '$storage'.";
exit();
} else {
//form
echo "<form name='send_parts_form' action='../includes/generatetab.php' method='post'>";
//Table header
echo "
<table>
<tr>
<th>Part</th>
<th>PN</th>
<th>Manufactured</th>
<th>Serial</th>
<th>Site</th>
<th>Date replaced</th>
<th>By user</th>
<th>Faulty</th>
<th>Send</th>
<th>Select</th>
</tr>";
//Retrieved data
while ($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['part_type'] . "</td>";
echo "<td>" . $row['pn'] . "</td>";
echo "<td>" . $row['manufactured'] . "</td>";
echo "<td>" . $row['serial'] . "</td>";
echo "<td>" . $row['site_id'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['user'] . "</td>";
echo "<td>" . $row['faulty'] . "</td>";
echo "<td><input type='checkbox' name='send_parts[]' class='checkclass' value=" . $row['id'] . "></td>";
echo "</tr>";};
echo "</table>";
echo "</br>";
echo "</br>";
echo "<input type='button' onclick='sendToZG()' value='Send'/>";
echo "</br>";
echo "<input type='submit' name='submit' value='Generate tab' />";
echo "</form>";
exit();
}
} else {
die("Query failed");
}
User then checks option they want and upon submiting (Generate tab) they get tab delimited text with values they selected.
I now want when they click "Send" to have values posted to another php page and results returned on the same page (under SentList div). I have js like this:
//Browser Support Code
function sendToZG(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
var ajaxDisplay = document.getElementById('SentList');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("send_parts=" + formData);
}
Edited: ajaxRequest.send("send_part=" + formData); to ajaxRequest.send("send_parts=" + formData);
Now it returns:
Invalid argument supplied for foreach() on line 53 (That is where I fetch my data in sendtozg.php).
I'll add sendtozg.php at the end of the post.
If instead of:
<form name='send_parts_form' action='../includes/generatetab.php' method='post'>
I echo:
<form name='send_parts_form' action='../includes/sendtozg.php' method='post'>
Upon submit, script sendtozg.php gets executed fine but on a different page.
So basically what I'm trying to do is to have 2 options for the php generated form:
Generate tab delimited txt file
Execute sendtozg.php and return results on same page
I already have both scripts (generatetab.php and sendtozg.php) and they work fine.
sendtozg.php:
if (!empty($_POST['send_parts'])){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
while ($row = mysqli_fetch_array($getchecked)) {
$copypart = mysqli_query($con, "INSERT INTO sent_parts (part_type, pn, manufactured, serial, site_id, date, user, faulty, log)
SELECT part_type, pn, manufactured, serial, site_id, date, user, faulty, log
FROM $storage WHERE id=$send_parts");
// check to see if it copied
$getserial = mysqli_query($con, "SELECT serial FROM $storage WHERE id=$send_parts");
$getserial_row = mysqli_fetch_array($getserial, MYSQLI_NUM);
$foundserial = $getserial_row[0];
$checkcopy = mysqli_query($con, "SELECT id FROM sent_parts WHERE serial = '$foundserial'");
// add user info and date
$addinfo = mysqli_query($con, "UPDATE sent_parts SET sent2zg='$user', date2zg='$strdate' WHERE serial = '$foundserial'");
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
};
//delete from storage
if($checkcopy > 0) {
$getpart = mysqli_query($con, "SELECT part_type FROM sent_parts WHERE serial='$foundserial'");
$getpart_row = mysqli_fetch_array($getpart, MYSQLI_NUM);
$deletedpart = $getpart_row[0];
$removepart = mysqli_query($con, "DELETE FROM $storage WHERE id = '$send_parts'");
echo "Part " . $deletedpart . " has been transfered";
} else {
echo "Part " . $row['part_type'] . "was NOT transfered";
};
};
} exit ();
} else {
echo "Nothing was selected, please try again!";
}
Your <form> doesn't have an id attribute on it so you'll either need to add id="send_parts" to the <form> or you'll need to change your code from getElementById to getElementsByName like this:
// Now get the value from page and pass it to server script.
// Serialize the data
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.send(formData);
Then inside sendtozg.php you'll need to change the first two lines to:
if (!empty($_POST)){
foreach ($_POST as $send_parts){
This is the final code for the sendtozg.js:
// Get get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
ajaxRequest.send(formData);
}
and sendtozg.php should be:
if (!empty($_POST)){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
By the way:
print_r ($some_array)
and
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
};
Are great tools for troubleshooting.
SCROLL TO FIND WORKING CODE
I am working on a AJAX editing platform, and I am having trouble with setting up the text field for editing.
My code so far:
The Javascript below handles the initial submission:
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function edit()
{
var doc_id = document.getElementById("doc_id").value;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
document.getElementById('content').innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
The SQL below handles the initial select query and display of that information:
$query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured`, ';
$query.= 'FROM `primary_physicians` AS pp ';
$query.= 'ORDER BY pp.`physician_id` ';
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
echo "<td><div id='content'><input id='doc_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' value='Edit' onclick='edit();'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
</html>
And the 'ajax.php' file handles the request when the user clicks the 'Edit' button within the 'content' div.
$client_id = $_GET['doc_id'];
$client_query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured` ';
$client_query.= 'FROM `primary_physicians` AS pp WHERE pp.`physician_id`=' . $client_id . '';
$client_result = mysql_unbuffered_query( $client_query );
while ($client_row = mysql_fetch_assoc($client_result))
{
echo "<input type='text' value='$client_row[physician_first_name]' />";
}
What shows is below:
Initial page load:
Pressing the 'edit' button (any of the available buttons, not just the one associated with the client/ID):
Pressing any edit button shows client ID #2 within client ID #1's table row (not in the row with client ID #2):
I'm guessing I have to set up something within the content div and somehow associate it with the 'edit()' function, however I can't figure out how to do that without setting the script within the while loop (which I really don't want to do).
WORKING CODE BELOW
Javascript (initial submission and display):
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function hello(e)
{
/* this was once document.getElementById("doc_id").value;*/
var doc_id = e.currentTarget.id;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
/*this was without the '+doc_id' document.getElementById('content').innerHTML = ajax.responseText; */
document.getElementById('content'+doc_id).innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
PHP/MySQL:
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
//note change to the 'content' div (addition of $physician_id to make it truly unique; this ties into the javascript above.
echo "<td><div id='content$physician_id'>";
//note changes to input id and button id, as well as the 'onclick' function.
echo "<input id='doc_id_$physician_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' id='$physician_id' value='Edit' onclick='hello(event);'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
No changes to or initial MySQL query or to ajax.php
There is a problem with the elements' ids. Remeber that the id attribute should be unique inside a document. You are using the same id for numerous elements:
td><div id='content'><input id='doc_id' type='hidden' ...
inside a loop.
Then you use the Javascript document.getElementById('doc_id'). JS supposes there is only one element with this id on the page so it will always return the first element it finds.
EDIT:
You will have to also change your JS function to retrieve the proper value:
for the edit buttons use: onclick="edit(event)"
And then in the JS:
function edit(e) {
buttonId = e.currentTarget.id;
//use the button id to find the proper value
}
Of course you will have to set the id on the "edit" buttons and have it correspond with id of you inputs. E.g. use $i for the button id and doc_id_$i for the input id.
I also recommend having a look at jQuery, as it will help facilitate many of the things you're trying to achieve here.
I have a very simple form, containing a textbox and a submit button. When the user enters something into the form, then clicks submit, I would like to use PHP and Ajax (with jQuery) to insert the result of the form into a MySQL database. this result should be displayed on the same page in the form of a table which is updated after every insert.
Can anyone please help?
The code I have used that isn’t working:
ajax.html:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "&name=" +name+ "&age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='name' /><br/>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()'
value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
ajax-example.php:
<?php
$dbhost = "localhost";
$dbuser = "demo";
$dbpass = "demo";
$dbname = "test_db";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($test_db) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "INSERT INTO form2 (name,age,sex,wpm) VALUES ('$name','$age','$sex','$wpm')";;
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
$result1=mysql_query("SELECT * FROM form2 WHERE name='$name'");
while($row = mysql_fetch_array($result1))
{
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
?>
$("button_id").click(function () {
$.ajax({
url:"where you should post the data",
type: "POST",
data: the string you should post,
success: function (result) {
//display your result in some DOM element
}
});
});
When you receive the data in the php script make query to the database and get your result
hope this would help
There are many tutorials available on internet for ajax with PHP and Jquery. You can go through any of these and get the desired result.
See an example here http://www.tutorialspoint.com/ajax/ajax_database.htm