Single Hardware Modification
Mulitple Hardware Modifications
I am trying to set up an equipment log using MySQL, PHP, and JavaScript. I have been trying to teach myself over the past 3 months. A lot of what I have is from code I have found here or on other forums.
I have a page dedicated to inputting hardware changes on our equipment. The Subsystem and Component dropdowns are set to pull the subsystem list from the database, and the component list is populated based off subsystem selection. I have not gotten that far into JavaScript, so I do not fully understand some of what this code means.
I have the page set up to input one modification, then after submitting, there is a link to return to the page to add another modification. This option is working as expected. My dropdowns work and my data is input into my database as expected.
I am trying to set up a page so that if there are multiple modifications, they can be added on one page. All of my text input fields on the form work as expected. I am able to create the first dropdown for the subsystem and populate it with my table data, but the component dropdown does not populate. I have been following this tutorial from webslesson.com. In it he uses 1 table. I have been trying to adapt it for the 2 tables that I am using, but I am getting some of the functions wrong.
Would anyone be able to point me in the right direction of where I can learn where my code is going off track? I am trying to learn, but at this point I am not exactly sure how to phrase what I am looking for.
I appreciate you taking a look at this. Please do not be too harsh on my poor code. I am working to make it better as I learn.
Above are links to my CodePen.io and repl.it for the 2 versions of my page. I had to
This is my table setup:
lu_subsystem
|id|subsystem_name|
|--|--------------|
lu_component
|component_id|subsystem_id|component_name|
|------------|------------|--------------|
<?php
//index.php
include('database_connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h3 align="center">Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</h3>
<br />
<h4 align="center">Enter Item Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-responsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<thead>
<tr>
<th>Enter Item Name</th>
<th>Subsystem</th>
<th>Component</th>
<th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</thead>
<tbody></tbody>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><select name="subsystem_id[]" class="form-control subsystem_id" data-subsystem_id="'+count+'"><option value="">Select Subsystem</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_component_id[]" class="form-control item_component_id" id="item_component_id'+count+'"><option value="">Select Component</option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$(document).on('change', '.subsystem_id', function(){
var id = $(this).val();
var component_id = $(this).data('component_id');
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{subsystem_id:subsystem_id},
success:function(data)
{
var html = '<option value="">Select Component</option>';
html += data;
$('#item_component_id'+component_id).html(html);
}
})
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Enter Item name at '+count+' Row</p>';
return false;
}
count = count + 1;
});
$('.item_category').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Category at '+count+' row</p>';
return false;
}
count = count + 1;
});
$('.item_component_id').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Sub category '+count+' Row</p> ';
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find('tr:gt(0)').remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost; dbname=bunker_logs;", "root", "");
function fill_select_box($connect, $id)
{
$query = "
SELECT * FROM lu_subsystem
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '<option value="'.$row["id"].'">'.$row["subsystem_name"].'</option>';
}
return $output;
}
function fill_component_box($connect, $component_id)
{
$query = "
SELECT * FROM lu_component
WHERE component_id ='".$id."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '<option value="'.$row["component_id"].'">'.$row["component_name"].'</option>';
}
return $output;
}
?>
<?php
//fill_component.php
include('database_connection.php');
echo fill_component_box($connect, $_POST["subsystem_id"]);
?>
I have been looking into your code, and to be honest, I haven't done much in jQuery. However, I still want to give you an example on how you can implement the information on your page from my experience:
You can either pull the information directly from the database with PHP without using JavaScript. If you use PDO for this, you get a muldimension array.
You can then "walk" through the array with a foreach loop
$select ='<select id='yourChoice'>';
foreach($array as $component){
$name = component['name'];
$select.="<option value='$name'> $name </option>;
};
$select.='</select>';
In this case the $array is the full printout from the database, and goes through each row ( $component)
It then selects the column name, and fills it in.
If you want to do the same thing with JavaScript, you can do it with JSON, walking through that array.
Unfortunately, I don't have an example ready for that one at the moment.
Related
I have a code which inserts data from a modal form into two related tables, namely inventory_order table and inventory_order_product table. That code is working fine but my problem comes when I want to fetch the same data back into the modal form for editing. The code for fetch single is only retrieving data for the first line in the selectpicker while the remaining are not retrieved. Please if my question is not clear refer to the image below and please bear with me I'm a novice in php, ajax and mysql.
$(document).on('click', '.update', function(){
var inventory_order_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:"order_action.php",
method:"POST",
data:{inventory_order_id:inventory_order_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#orderModal').modal('show');
$('#inventory_order_name').val(data.inventory_order_name);
$('#inventory_order_date').val(data.inventory_order_date);
$('#inventory_order_address').val(data.inventory_order_address);
$('#span_product_details').html(data.product_details);
$('#payment_status').val(data.payment_status);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit Order");
$('#inventory_order_id').val(inventory_order_id);
$('#action').val('Edit');
$('#btn_action').val('Edit');
}
})
});
if($_POST['btn_action'] == 'fetch_single')
{
$query = "
SELECT * FROM inventory_order WHERE inventory_order_id = :inventory_order_id
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':inventory_order_id' => $_POST["inventory_order_id"]
)
);
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$output['inventory_order_name'] = $row['inventory_order_name'];
$output['inventory_order_date'] = $row['inventory_order_date'];
$output['inventory_order_address'] = $row['inventory_order_address'];
$output['payment_status'] = $row['payment_status'];
}
$sub_query = "
SELECT * FROM inventory_order_product
WHERE inventory_order_id = '".$_POST["inventory_order_id"]."'
";
$statement = $connect->prepare($sub_query);
$statement->execute();
$sub_result = $statement->fetchAll();
$product_details = '';
$count = '';
$count = $count++;
foreach($sub_result as $sub_row)
{
$product_details .= '
<script>
$(document).ready(function(){
$("#product_id'.$count.'").selectpicker("val", '.$sub_row["product_id"].');
$(".selectpicker").selectpicker();
});
</script>
<span id="row'.$count.'">
<div class="row">
<div class="col-md-8">
<select name="product_id[]" id="product_id'.$count.'" class="form-control selectpicker" data-live-search="true" required>
'.fill_product_list($connect).'
</select>
<input type="hidden" name="hidden_product_id[]" value="'.$sub_row["product_id"].'" />
</div>
<div class="col-md-3">
<input type="text" name="quantity[]" class="form-control" value="'.$sub_row["quantity"].'" required />
</div>
<div class="col-md-1">
';
if($count == '')
{
$product_details .= '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
}
else
{
$product_details .= '<button type="button" name="remove" id="'.$count.'" class="btn btn-danger btn-xs remove">-</button>';
}
$product_details .= '
</div>
</div>
</div><br />
</span>
';
}
$output['product_details'] = $product_details;
echo json_encode($output);
}
Problem in your code is with variable $count.As in your backend code this is declare outside your foreach.. loop so when first time your loop will run it will have correct value i.e : 0 but you never increment it that's why it is only giving correct value for first selectpicker. Instead you need to increment its value to set value for second value ,third and so on. i.e :
foreach($sub_result as $sub_row)
{
//you code html and jquery
$count = $count++;//add this inside for loop
}
Also, i don't why you have given $count = ''; . Instead , it should be $count = 0;
I got a small problem.
I want to look up the name by entering the website. Now, all records are displayed. What I want is that he shows it after something has been entered in the input. I don't want him to show everything immediately.
Here some code to know how it looks like.
FETCH.PHP
Get everything from database
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM tbl_customer
WHERE website LIKE '%".$search."%'
OR naam LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM test ORDER BY id
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>Website</th>
<th>Naam</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["website"].'</td>
<td>'.$row["naam"].'</td>
</tr>
';
}
echo $output;
}
INDEX.PHP
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Jquery PHP MySql</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Zoek door website" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
why do u call function load_data(); on load.
this might be the issue
also remove it from else condition
So I am trying to get create a HTML that uses javascript, PHP, and CSS. I am having issues figuring out how to get the PHP that pulls in my database to post on the website with a click of a button using a javascript function. I have tried to setup jquery and ajax but I just can't seem to get it to work. Everything is connected as it should be. I have googled and googled and tried many things so figured I would post and see if someone can help me out. If I post the PHP file into my HTML it works properly but I have multiple querys that I want associated with a button. If I can just get one button to work I should be good to go. Thank you.
JS
function mad_hosp(str) {
if(str == 0){
document.getElementById("output").innerHTML = "Error.";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "madison_narc.php?", true);
xmlhttp.send();
}
}
Here are my buttons in HTML
<div class="navbar">
Home
News
<div class="dropdown">
<button class="dropbtn">Dropdown
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<button onclick="main_hosp()">
Huntsville Hospital
</button>
<button onclick="W&C_hosp()">
Womens and Childrens Hospital
</button>
<button onclick="mad_hosp()">
Madison Hospital
</button>
</div>
</div>
</div>
<p>Waiting for the location to be selected... <id="output"></p>
PHP
<?php
$sql = "SELECT
currentinventoryaudit.MedId as MedID,
(currentinventoryaudit.MedDescription) as MedicationDescription,
sum(currentinventoryaudit.CurrentCount) as TotalOnHand,
'MadisonNarcVault' as StationName
FROM
currentinventoryaudit
where
currentinventoryaudit.StationName like ('%CW101296%') and
currentinventoryaudit.MedDescription not like ('key%') and
currentinventoryaudit.MedDescription not like ('%zz-%') and
currentinventoryaudit.MedDescription not like ('%alp%')
group by
2
order by
2 asc;";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
echo "<table>
<tr>
<th>MedID</th>
<th>Medication Description</th>
<th>Total On Hand</th>
<th>Station Name</th>
</tr>";
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)){
echo"<tr>";
echo "<td>" . $row['MedID']."</td>";
echo "<td>" . $row ['MedicationDescription']."</td>";
echo "<td>" . $row ['TotalOnHand']."</td>";
echo "<td>" . $row ['StationName']."</td>";
echo "</tr>";
}
echo "</table>";
}
?>
This doesn't look like valid markup.
<p>Waiting for the location to be selected... <id="output"></p>
Use this instead:
<div id="output">
<p>Waiting for the location to be selected... </p>
</div>
document.getElementById("output") is looking for an element with an id attribute with a value of "output", not an id element.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have three buttons(role, department, search). When role is clicked, div will show the role informations. The div code is:
<div id="role_div" class="role" name="role" >
<?php
...
$sql = "select distinct role from hpc_user ;";
echo '<table>';
$sel=$conn->query($sql);
while($row=$sel->fetch(PDO::FETCH_NUM))
{
echo '<tr>';
echo '<td style="word-break:break-all;">'.$row[0].'</td>';
echo '</tr>';
}
echo '</table>';
?>
</div>`
When department button is clicked, I wish the whole div content is
<div id="role_div" class="role" name="role" >
<?php
$conn = new PDO('');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
$sql = "select distinct department from hpc_user ;";
echo '<table >';
$sel=$conn->query($sql);
while($row=$sel->fetch(PDO::FETCH_NUM))
{
echo '<tr>';
echo '<td style="word-break:break-all;">'.$row[0].'</td>';
echo '</tr>';
}
?>
</div>
I try to use
innerhtml.document.getElementById('role_div').innerHTML='<?php>....</php>',
but it does not work. Who can help me ?
You can simply put your role/department data in two hidden divs and than you can change data using Jquery
another solution as you mentioned you can't add three divs
html:
<div id="ajax_exchange"></div>
<input type="button" id="role" onclick="change_data(this.id);" value="role">
<input type="button" id="department" onclick="change_data(this.id);" value="department">
<input type="button" id="search" onclick="change_data(this.id);" value="search">
script :
<script type="text/javascript">
function change_data(id){
var data_to_fetch = $('#'+id).val();
$.ajax({
type: "post",
url: "<?php echo SFURI::SEFURL('index.php?itemtype=skus&layout=ajax_call',array('call'=>'ajax')); ?>",
dataType: 'html',
cache: false,
data: {get_this: data_to_fetch},
success: function(data){
$('#ajax_exchange').html("");
$('#ajax_exchange').html(data);
},
error: function(){
alert('Error while request..! try again');
}
});
}
</script>
ajax_call.php :
<?php
if(isset($_POST['get_this']) && $_POST['get_this']=="role"){
echo "role data";
// here you can put your role data to be sent to div
}
if(isset($_POST['get_this']) && $_POST['get_this']=="department"){
echo "department data";
// here you can put your department data to be sent to div
}
if(isset($_POST['get_this']) && $_POST['get_this']=="search"){
echo "search data";
// here you can put your search data to be sent to div
}
?>
I hope this will help you.
I think following code will help you.
var dt = '<table>';
var sql = "select distinct role from hpc_user ;";
for(var i = 0; i <= 5; i++)
{
dt = dt + '<tr>';
dt = dt + '<td style="word-break:break-all;">'+ i +'</td>';
dt = dt + '</tr>';
}
dt = dt + '</table>';
document.getElementById('role_div').innerHTML = dt;
You can create three divs with unique ids. And then display none style to two of them. And then you can use jquery to show/hide them on button click. For example :
HTML:
<!--Buttons-->
<div class="btnsContainer">
<button class="showHideDiv" id="role">Show Role Div</button>
<button class="showHideDiv" id="department">Show DepartmentDiv</button>
<button class="showHideDiv" id="search">Show Search Div</button>
</div>
<!--Role Container -->
<div id="role_div" class="role" name="role">
<!--Your role script here-->
</div>
<!--Department Container -->
<div id="dept_div" class="role" name="role" style="display:none;">
<!--Your department script here-->
</div>
<!--Search Container -->
<div id="search_div" class="role" name="role" style="display:none;">
<!--Your search script here-->
</div>
Jquery:
<!--latest jquery Library file-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".showHideDiv").click(function(){
var clickedBtnId = $(this).attr('id');
if(clickedBtnId === 'role') {
$('#role_div').show();
$('#dept_div').hide();
$('#search_div').hide();
} else if(clickedBtnId === 'department') {
$('#role_div').hide();
$('#dept_div').show();
$('#search_div').hide();
} else if(clickedBtnId === 'search') {
$('#role_div').hide();
$('#dept_div').hide();
$('#search_div').show();
}
});
});
</script>
I'm interested in having a search form on the left side of a webpage, and the main content being the rows returned from the database.
Example : www.kijiji.ca
What I want to avoid, is reloading the whole page. Kijiji is not a good example of this, updating the query or changing the results page, updates the entire browser window. Ideally when search parameters are changed, the container with the search results will update, and nothing else. This way the outside information is preserved, and page loading time is reduced.
Would an Iframe be ideal for this? Or perhaps Jquery/ajax can handle this somehow ??
Thanks for the advice.
AJAX is your answer. It stands for Asynchronous Javascript and XML...depending on your development framework, requirements, skill/knowledge and a variety of other factors you'll be implementing it in a variety of fashions.
AJAX is not a language, it is a concept. The idea is to allow asynchronous updates to portions of (or whole) pages on a website/web application. Here's a few resources to start you off:
http://learn.jquery.com/ajax/
http://www.w3schools.com/ajax/
http://www.tutorialspoint.com/ajax/
With a bit more information on your choice of IDE and/or requirements (are you building an ASP/PHP application or a CMS-based website?) we can offer some more pointed help.
You can achieve this easily with AJAX and without any (deprecated) frames.
Look at JQuery for example. It provides all you need to refresh/populate certain areas of your page, without the need to reload the whole page.
Try searching for jquery and ajax.
Further to what has been mentioned here about using AJAX, you'll need to have a server-side back-end that gets the required data from your db and uses a HTTP response to send data back to the client. This could be stored as JSON for instance and you can use that response to populate your search field.
I have python and wsgi set up on an apache server right now for a back-end for instance, but this sort of thing could be implemented through something like php as well.
Ajax is the best bet. try going through http://api.jquery.com/jQuery.ajax/ to learn more.
This is the basic template code:
$.ajax({
type: "GET",
url: "",//type your url
data: {
searchdata: searchdata
},
success: function (response) {
$('#Content').html(response);
}
});
as you see if your content page has a div with id as Content. it would just update that div alone.
You don't even need Ajax for this.
Here is some (admittedly sloppy) code from a recent project. Should get you started. You can add the Ajax later for neat stuff like a reset button, or chained select boxes. Good luck.
This code assumes your page is named index.php (the data is submitted to the same page) Also, the commented out echos are for testing your database connection and that the form data made it to your query. And you probably don't need this query, but there it is anyway. Make a fast test database and give it a try.
HTML:
<div id="formarea">
<form method="post" action="index.php">
Note: All fields are not required for searching<br>
First Name:
<input type="text" name="first"><br>
Last Name:
<input type="text" name="last"><br>
School:
<input type="text" name="edu"><br>
City:
<input type="text" name="cit"><br>
State:
<input type="text" name="st"><br>
<input class="submit" name="submit" type="submit" value="Find">
</form>
</div>
<div id="listarea">
<?php
mysql_connect('database', 'username', 'password') or die(mysql_error());
//echo "Connected to MySQL <br>";
mysql_select_db("hair1") or die(mysql_error());
//echo "Connected to Database <br>";
$first = mysql_real_escape_string($_POST['first']);
$last = mysql_real_escape_string($_POST['last']);
$edu = mysql_real_escape_string($_POST['edu']);
$cit = mysql_real_escape_string($_POST['cit']);
$st = mysql_real_escape_string($_POST['st']);
//echo $first; echo "<br>";
//echo $last; echo "<br>";
//echo $edu; echo "<br>";
//echo $cit; echo "<br>";
//echo $st; echo "<br>";
?>
<?php
if(isset($_POST['submit'])){
$query = "SELECT * FROM hair1 WHERE 1=1 ";
if($first) $query .= "AND fname=\"$first\" ";
if($last) $query .= "AND lname=\"$last\" ";
if($edu) $query .= "AND school=\"$edu\" ";
if($cit) $query .= "AND city=\"$cit\" ";
if($st) $query .= "AND state=\"$st\" ";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<div class='resultbox'><div class='infobox'>";
echo $row['fname'];
echo "</div><div class='infobox'>";
echo $row['lname'];
echo "</div><div class='infobox'>";
echo $row['school'];
echo "</div><div class='infobox'>";
echo $row['city'];
echo "</div><div class='infobox'>";
echo $row['state'];
echo "</div><div class='infobox'>";
echo $row['phone'];
echo "</div><div class='infobox'>";
echo $row['email'];
echo "</div></div>";
}
if ( mysql_num_rows( $result ) > 0 ){
}
else{ echo "<p>Sorry, that search didn't turn up anything. Please check your spelling and try again.</p>";
}}
else{
echo "<p>No Results Found</p>";
}
?>
</div>
CSS:
#formarea {
height: 235px;
width: 280px;
float: left;
clear: left;
text-align: right;
margin-right: 10px;
}
#listarea {
height: 235px;
width: 650px;
overflow-x: hidden;
overflow-y: auto;
float: left;
}
.resultbox {
height: 18px;
width: 100%;
padding-top: 3px;
}
.infobox {
float: left;
padding-right: 5px;
padding-left: 5px;
}
As others have mentioned, AJAX is the best solution for what you requested.
Here is a full example that does what you want. Values in a database will be updated via AJAX, with a response appearing on the page without the page refreshing.
jsFiddle (all working except AJAX)
While jsFiddle cannot demonstrate the AJAX, you can see that in action if you copy/paste the following into two files (three if you break out the javascript into its own file), and edit it to match your own database structure.
Two files are required:
One: index.php (or whatever you wish to call it)
Two: my_php_processor_file.php (if change this name, must also change in the AJAX code block in the javascript
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
//Global var goes here:
editRow = 0;
$(document).ready(function() {
$('#msgbox').dialog({
autoOpen:false,
width:400,
modal:true,
buttons: {
Submit: function() {
var mfn = $('#mfn').val();
var mln = $('#mln').val();
var mem = $('#mem').val();
$('table').find('tr').eq(editRow).find('.fname').val(mfn);
$('table').find('tr').eq(editRow).find('.lname').val(mln);
$('table').find('tr').eq(editRow).find('.email').val(mem);
/*
//Now do the ajax transfer to the server
$.ajax({
type: 'POST',
url: 'my_php_processor_file.php',
data: 'user_id=' +editRow+ '&first_name=' +mfn+ '&last_name=' +mln+ '&email_addy=' +mem,
success:function(recd){
$('#alert').html(recd);
$('#alert').dialog('open');
}
}); //END ajax code block
*/ //Now, close the dialog -- doesn't happen automatically!
$(this).dialog('close');
}, //END Submit button
Cancel: function() {
$(this).dialog('close');
} //END Cancel button
} //END all buttons
}); //END msgbox div (dialog)
$('.editbutt').click(function() {
editRow = $(this).parents('tr').index();
//alert(editRow);
var fn = $(this).parents('tr').find('td').eq(0).find('.fname').val();
var ln = $(this).parents('tr').find('td').eq(1).find('.lname').val();
var em = $(this).parents('tr').find('td').eq(2).find('.email').val();
$('#mfn').val(fn);
$('#mln').val(ln);
$('#mem').val(em);
$('#msgbox').dialog('open');
}); //END editbutt
$('#alert').dialog({
autoOpen:false,
modal:true
});
}); //END document.ready
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
First Name
</td>
<td>
Last Name
</td>
<td>
Email
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" id="fn1">
</td>
<td>
<input type="text" class="lname" id="ln1">
</td>
<td>
<input type="text" class="email" id="em1">
</td>
<td>
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
<tr id="tr2">
<td id="td2a">
<input type="text" class="fname" id="fn2">
</td>
<td id="td2b">
<input type="text" class="lname" id="ln2">
</td>
<td id="td2c">
<input type="text" class="email" id="em2">
</td>
<td id="td2d">
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
</table>
<div id="msgbox">
<h2>Edit User</h2>
First Name: <input id="mfn" type="text"><br/>
Last Name : <input id="mln" type="text"><br/>
Email Addy: <input id="mem" type="text"><br/>
</div>
<div id="alert"></div>
</body>
</html>
PHP Processor File: my_php_processor_file.php
<?php
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$em = $_POST['email_addy'];
$uid = $_POST['user_id'];
/*
//This is where you use the security features of PHP to strip_slashes, and
//protect html_entities, etc. to guard your database against SQL injection
//attacks, etc. SEE THESE POSTS:
https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
http://blogs.msdn.com/b/brian_swan/archive/2010/03/04/what_2700_s-the-right-way-to-avoid-sql-injection-in-php-scripts_3f00_.aspx
*/
//Now, update the database:
$success = mysql_query("UPDATE `users` SET `email`='$em', `first`='$fn', `last`='$ln' WHERE `user_id` = '$uid'");
//Now, return a message or something
if (mysql_affected_rows() == -1) {
$output = '<h2>Sorry, database update failed</h2>';
}else{
$output = '<h2>Update successful</h2>';
}
echo $output;
Here are some other simple examples of how AJAX works:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
I think you should go with JQuery ajax
It's as simple as:
var request = $.ajax({
url: //here goes url,
type: "GET",
data: { param : value}, //pass your parameters here
dataType: "html"
});
request.done(function( data ) {
//here you update your main container
$( "#main_container" ).html( data);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});