Display select query results by using jQuery - javascript

I'm pretty new to jQuery and I'm practicing with it. I've this html simple page:
<html>
<head>
<title> Testing jQuery
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
<link href="mycss.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2 id="myH"> This is a title.</h2>
<br>
<br>
<fieldset>
<legend>Data</legend>
<form name="myForm">
<input type="text" id="firstData" placeholder="Write something in here" \>
<br>
<br>
<input type="text" id="secondData" placeholder="Write something else in here" \>
<br>
</form>
<button id="formButton" value="Confirm">Confirm</button>
</fieldset>
<br><br><br>
<div id="myDiv"></div>
</body>
</html>
This PHP script:
<?php
/* Connection to DB*/
.... CONNECTIONS STUFF.........
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
And finally this js code:
$(function () {
$('#formButton').on('click', function (e) {
var firstData = $('#firstData').val();
var secondData = $('#secondData').val();
var query = 'first=' + firstData + '&second=' + secondData;
// Here I use another php script.
$.get('myData.php', query, function (data) {
$('#myDiv').html(data);
});
});
$('#formButton').on('click', function (e) {
$.ajax({
url: "myquery.php",
type: "POST",
success: function (data) {
$("#myDiv").empty().html(data);
}
});
});
});
Ok , now that I've inserted all the code , the problem is that I can add elements to my database by using myData.php script but I'd like to create a page where in the top you can add elements and when you click on the confirmation button in the bottom (with a query) all the contents of the table are displayed. So I can add elements but I'm not able to display them. I'm new to jQuery and I'm trying to make it work , I've made different researches on the Web but I couldn't find anything that solved my problem. Could please someone help me? Thanks!

You can do both operation by single file myData.php
Put below code right after record inserted in myData.php
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
No need of two ajax call. Remove the second button click jquery code.
On first button click event myData.php file will be called. First record will be inserted in your DB table with your existing code. After it place your code to fetch records from DB. your HTML will be sent in the response and place that HTML in the DIV with your existing jquery code.

you can use jquery load function for it, its very easy for you
http://www.w3schools.com/jquery/jquery_ajax_load.asp
just load a div from there to a div in current page
follow this url for the video tutorial, its very simple, use a div here then enter the id and in the page you are loading, please use another id and load that id into this page div
https://www.youtube.com/watch?v=mtz8MdQXhno
it works in wordpress and will simply work in php
same code

Related

Rerun PHP Script inside HTML file without reloading page

I want to rerun a PHP File which was loaded in a div in my HTML code. On my main page, I have a form and a table. The form adds rows to the MySQL table, and the table on the page outputs that MySQL table. I want the table on the HTML page to update when the new row is added via the form, without refreshing the page. I tried putting the load command in the success part of the ajax function for my form but that didn't work. I looked at many other answers and none worked for me.
This is my code
redeem.php
<h1>Rewards</h1>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required>
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required>
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>
tables.php
<?php
$host = "";
$user = "";
$pass = "";
$db_name = "";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT RewardName, PointsRequired FROM rewards");
$all_reward = array(); //declare an array for saving property
while ($reward = mysqli_fetch_field($result)) {
// echo '<th scope="col">' . $reward->name . '</th>'; //get field name for header
array_push($all_reward, $reward->name); //save those to array
}
// echo ' </tr>
// </thead>'; //end tr tag
echo '<table class="table">
<thead>
<tr>
<th scope="col">Reward</th>
<th scope="col">Points Required</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>';
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tbody>
<tr>";
foreach ($all_reward as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '<td><i class="fas fa-edit"></i></td>';
echo '<td><i class="fas fa-trash"></i></td>';
echo ' </tr>
</tbody>';
}
echo "</table>";
?>
redeem-form.js
$(document).ready(function() {
$("#add-reward-form").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "add_rewards.php",
method: "POST",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$("#add-reward-form")[0].reset();
$("#sql-table").load(" #sql-table > *");
}
});
$("#sql-table").load(" #sql-table > *");
});
});
The form works perfectly fine with ajax, and submits to the database without refreshing. But I would like to update the table on my page as well without reloading.
$("#sql-table").load(" #sql-table > *");
This is what I tried. I placed it inside the success function and the submit function but both did not work.
You are mis-using $.load(). It's a shorthand for $.ajax(). The first argument must be a URL. Optional arguments are data and options.
You are passing it a selector, so the request fails. As-is, $("#sql-table").load(" #sql-table > *"); is attempting an AJAX request to the URL /%20#sql-table%20%3E%20*. (!)
Simply change the selector for the PHP file you want to execute:
$("#sql-table").load("tables.php");
How about forcing redeem.php to re-evaluate the PHP div every time a change happens to the inputs?
<h1>Rewards</h1>
<script>
function redrawSQLTable(){
document.getElementById('sql-table').innerHTML = "<?php include 'tables.php'; ?>"
}
</script>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required onchange="redrawSQLTable()">
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required onchange="redrawSQLTable()">
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>

When I try to send id value of row via POST to another page, this page will always GET id value 1

I started learning webdeveloping and i tried to send "id" of one of the rows generated from database to another page. The rows are clickable thanks to the javascript code, so i can choose whichever row i want. The problem is, that even though the POST method seems right:
<form id="send" method="POST" action=<?php echo "secondpage.php?id=". $row['id']; ?> ></form>
// In inspect of the main page it gets the value.
However
second page always receive id value of 1. Doesn't matter if i click on the row with id=18 or any other. It will always recieve value of 1...
I heard that this could be a problem with javascript code which i put under PHP code.
Here is a code with PHP:
<div id="content">
<table id="usersTable" class="table table-bordered table-hover table-sm ">
<form action=http://localhost/dodawanie.php>
<input class="btn btn-primary" type="submit" value="Dodawanie">
</form>
<?php if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {?>
<tr>
<td><?php echo "id: ". $row['id']; ?> </td>
<td><?php echo "Name: ". $row["first_name"]; ?> </td>
<td><?php echo "Last: ". $row["last_name"];?> </td>
<form id="send" method="POST" action=<?php echo "secondpage.php?id=". $row['id']; ?> >
</form>
</tr>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</table>
</div>
Here is javascript:
<script type = "text/javascript">
$(document).ready(function(){
$('#usersTable').find('tr').click( function(){
// alert('You clicked row ' + ($(this).index()+1) );
$('#send').submit();
});
});
</script>
I would gladly accept any help to find an error here.
Change the <form id="send" id value as unique
or use a class some thing like below:
<form class="form_send" then in your javascript search for the form_class inside the clicked tr:
$(document).ready(function(){
$('#usersTable').find('tr').click( function(){
$(this).find('form.form_send').submit();
});
});
Ids have to be unique. $('#send').submit() only finds and submits the first form with that id.
You could add your row id to the form's id attribute to make them unique for example.

How can I update a specific record in a sql database based on a selection made in a dropdown select box?

Ok, I have spent days on this, and I am out of my depth. I admit I am completely new to sql, jquery, and ajax. I apologize in advance for this.
I am trying to build an application where an admin can see a users performance over time, averaging the last 2 weeks of input scores. Using a dropdown box a member should be selected from the DB (this part seems to work), then a form below can be filled out and an "update" button pressed to update the record in the DB (this is completely broken).
The select box is populated from the DB with ajax, and I can return values from the selection with an onchange function, but when I try to then update the database with my form, nothing is updated.
The insert button and associated code work properly, and information is stored correctly in the DB. (I will break the data off into more accurate tables when I have the code correct as I did not want to deal with joins and multiple tables while struggling.)
When selecting a name from the select menu $_POST['memberID'] shows the correct number.
Once information is entered into the form and "update" is pressed, $_POST['memberID'] is blank and the DB is not updated.
Controller.php:
<?php require 'php/dbconnect.php';
$records = array();
if(!empty($_POST)) {
switch (true) {
case isset($_POST['insert']):
if(isset($_POST['name'], $_POST['designation'], $_POST['rank'], $_POST['currentScore'])) {
// The following trim functions followed by !empty ensures that a series of spaces is not accepted from users as input.
$name = trim($_POST['name']);
$designation = trim($_POST['designation']);
$rank = trim($_POST['rank']);
$currentScore = trim($_POST['currentScore']);
if(!empty($name) && !empty($designation) && !empty($rank) && !empty($currentScore)) {
$insert = $conn->prepare("INSERT INTO members (name, designation, rank, currentScore) VALUES (?,?,?,?)");
$insert->bind_param('ssii' , $name, $designation, $rank, $currentScore);
if($insert->execute()) {
$insert->free(); //Remove Query Data from memory since it is no longer needed.
header('location: index.php');
die();
}
}
}
break;
case isset($_POST['update']):
$name = trim($_POST['name']);
if(!empty($name)) {
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
$update->bind_param('s', $name);
if($update->execute()) {
header('location: index.php');
die();
}
}
break;
// case isset($_POST['delete']):
// // Delete statement goes here
// break;
// else
}
}
if($results = $conn->query("SELECT *, ((previousScore + currentScore) / 2) AS avgScore FROM members")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row; //Appending value to array
}
$results->free();
}
}
?>
Index.php:
<?php include 'header.php' ?>
<?php if(!count($records)) {
echo 'No Records' ;
} else {
?>
<form id="memberSelect" method="post">
<select name="memberID" id="members" onchange="change()">
<!-- Populated with function members in footer.php -->
</select>
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Rank</th>
<th>Previous Score</th>
<th>Current Score</th>
<th>Average Score</th>
</tr>
</thead>
<tbody>
<?php
foreach($records as $r) {
?>
<tr>
<td><?php echo escape($r->name); ?></td>
<td><?php echo escape($r->designation); ?></td>
<td><?php echo escape($r->rank); ?></td>
<td><?php echo escape($r->previousScore); ?></td>
<td><?php echo escape($r->currentScore); ?></td>
<td><?php echo escape($r->avgScore); ?></td>
<!-- Remember when putting data in that current score needs to be moved to previous score's
position and the NEW score will take the place of current score(which will be the old score until updated) -->
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
<hr>
<form action="" method="post">
<div class="field">
<label for="name">Member name</label>
<input type="text" name="name" id="name" autocomplete="off">
</div>
<div class="field">
<label for="designation">Designation</label>
<input type="text" name="designation" id="designation" autocomplete="off">
</div>
<div class="field">
<label for="rank">Rank</label>
<input type="text" name="rank" id="charLevel" autocomplete="off">
</div>
<div class="field">
<label for="currentScore">Current Score</label>
<input type="text" name="currentScore" id="currentScore" autocomplete="off">
</div>
<div id="submit">
<!-- Add a comment section to be input into DB -->
<input type="submit" name="insert" value="Insert">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<!-- <input type="hidden" name="id" value="<?php //echo $?>"> -->
</div>
</form>
<?php include 'footer.php' ?>
Footer.php:
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script>
//How do you explain something you barely understand? The following function uses JQUERY
//json, and ajax to fill a select dropdown with items populated from a linked database.
//See the jsonData.php for the json data being referenced here, it is imperitive to the operation of
//this function that json data be available.
function members(){
$('#members').empty();//Removes all content of the associated ID 'members' to ensure a clean default value
$('#members').append("<option>Loading</option>");//fill them with a default message
$.ajax({
type:"POST",
url:"php/jsonData.php",//the location of the json data, for this it is required to be in its own file
contentType:"application/json; charset=utf-8",
dataType: "json",
success: function(records){ //only fires if the json data is found
$('#members').empty();//If everything is ok, removes previous default value
$('#members').append("<option value='0'>--Select Member--</option>");
$.each(records,function(i,memberID){//Uses a foreach loop to fire a function for every memberID, assigning the value to i
$('#members').append('<option value="'+ records[i].memberID +'">'+ records[i].name +'</option>');
//^ The workhorse. Grabs the select value by the ID, appends the option value by looking within the records array
//(which is defined and assigned values in the jsonData.php file) and assigns the member id as the value and the 'name'
//as the option. This populates the dropdown with the names and gives them the value 'memberID' from the database.
});
},
complete: function(){
}
});
}
$(document).ready(function(){
members();
});
</script>
<script>
function change(){
$('#memberSelect').submit();//Submits the page to the server when called
}
</script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
I think the problem is in this line of the Update Block:
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
I am assuming the primary key of your member table is: member_id
Then this code will be:
$update = $conn->prepare("UPDATE members SET name = ? WHERE member_id = ?");
$update->bind_param('si', $name, $memberID);
Try this. Hope it helps.

How to use toggle() in php in table while fetching the data from database?

I want to use toggle() in table when i am fetching data from database, but its not working.
The issue is loop which i am using in "id name" because if i remove the loop and give a unique id name, then it works properly, but i am fetching the data and data is more than hundreds and so it is not possible to give unique id name so i have given the id name in loop.
Code is :
<?php
mysql_connect("localhost","root","");
mysql_select_db('new game')or die('database not found');
?>
<!DOCTYPE>
<html>
<head>
<title>Gaming Zone</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#$aa").click(function(){
$("#$bb").toggle(700);
});
});
</script>
</head>
<body>
<div align="right">Add</div>
<table width="735" border="1" align="center">
<tr>
<td width="568">Name</td>
</tr>
<tr>
<?php
$abc=mysql_query("select * from games order by game ASC");
$aa=0;
$bb=0;
while($row=mysql_fetch_array($abc))
{
$aa=$aa+1;
$bb=$bb+1;
?>
<td>
<?php echo $row['game']; ?> <sub>Requirements</sub><br>
<div id="$bb" style="background-color:#FF3; display:none"><?php echo $row['min']; ?><span style="padding-left:50px"><?php echo $row['rec']; ?></span><span style="padding-left:100px"><?php echo $row['max']; ?></span></div>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
Need for Help for how to give unique id name when data is huge in amount ? Thanks in Advance

How to populate a database list without refreshing webpage

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 );
});

Categories

Resources