PHP/AJAX stoping jquery from working? - javascript

Having the issue here where my jquery work fine when viewing it as a single page however when I try and include that PHP file in another page either using php include or ajax the jquery doesnt seem to load.
I'm rather new to all this stuff so its very possible I'm doing something silly, any help would be greatly appreciated!
HTML Code
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
//xmlhttp.open("GET","jquery.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" ID="option" onChange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">ID One</option>
<option value="2">ID Two</option>
<option value="3">ID Three</option>
<option value="4">ID Four</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP/Jquery
<html>
<head>
<link href="../../Styles/tablestyles.css" rel="stylesheet" type="text/css" />
<?php include "db.php" ?>
<script type="text/javascript" src="../../JS/tablesorter/jquery-latest.js"></script>
<script type="text/javascript" src="../../JS/tablesorter/jquery.tablesorter.js"></script>
<script type="text/javascript" src="../../JS/sorter.js"></script>
<script>
$(document).ready(function() {
// call the tablesorter plugin
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
});
</script>
<?php
$q = intval($_GET['q']);
$result = mysqli_query($db_connection, "SELECT * FROM student WHERE Student_Id = '".$q."' or Student_Id = 7");
echo "<table id=\"myTable\" class=\"tablesorter\">
<thead>
<tr>
<th>Student ID</th>
<th>B-Code</th>
<th>First Name</th>
<th>Second Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Student_Id'] . "</td>";
echo "<td>" . $row['B-code'] . "</td>";
echo "<td>" . $row['Student_Forename'] . "</td>";
echo "<td>" . $row['Student_Surename'] . "</td>";
echo "<td>" . $row['Student_Email'] . "</td>";
echo "</tr>";
}
echo"</tbody>
</table> ";
mysqli_close($con);
?>

Your AJAX request is going to getuser.php, which is what I'm going to assume your second code block represents? Basically instead of making a call to some PHP code that does your processing and sending you a response, you're actually calling back a PHP script AND an HTML page to boot, then embedding that into an existing page.
I recommend doing the following:
First, remove the HTML from getuser.php so that all you have left is the PHP code.
Then, in the page making the AJAX call, as part of your "success" function, include your sorter function so that it occurs after you've gotten your response and written out the new HTML. Something to the effect of the following:
getuser.php:
<?php include "db.php";
$q = intval($_GET['q']);
$result = mysqli_query($db_connection, "SELECT * FROM student WHERE Student_Id = '".$q."' or Student_Id = 7");
echo "<table id=\"myTable\" class=\"tablesorter\">
<thead>
<tr>
<th>Student ID</th>
<th>B-Code</th>
<th>First Name</th>
<th>Second Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Student_Id'] . "</td>";
echo "<td>" . $row['B-code'] . "</td>";
echo "<td>" . $row['Student_Forename'] . "</td>";
echo "<td>" . $row['Student_Surename'] . "</td>";
echo "<td>" . $row['Student_Email'] . "</td>";
echo "</tr>";
}
echo"</tbody>
</table> ";
mysqli_close($con);
Then, in your calling page success code:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
}
}
Also, move your necessary CSS and JavaScript includes to the calling page as well so that you have your jQuery object available, etc. I would also recommend changing that code to use jQuery contructs and functions instead of raw JavaScript. It'll help keep your code clean, consistent, and easier to read :)
NOTE: I typed this up in a hurry, so anyone feel free to call me out and correct me on any mistakes.

Pretty much what I thnk is the issue is that when your jQuery script fires,the default functionality of the selector statements is select and do this on the current instances of this selector.
So if you do:
$(document).ready(function() {
// call the tablesorter plugin
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
});
That finds all of the table tags on the page, and calls tablesorter on them. But, if additional table tags are added to the page, or the first table tag is added to the page when the page has already loaded, then jquery does not call table sorter onto it because it did not exist previously when it ran the $("table") selector.
This is not tested, but you can try and hook the .tablesorter onto the $("table") selector once everytime ajax finishes loading.
$( document ).ajaxComplete(function() {
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
});
A similiar situation is when you use something like:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
The .click event is only bound to the #target elements that existed on the page when the page first loaded. Any subsequent #target elements added to the page later on will not have the .click event bound to them.
So say. You have header.php, where your script lives. Then you have index.php, and then you have table.php. If you include header.php inside index.php, the scripts inside header.php will effect the elements in index.php. But if you also include table.php inside of index.php, the scripts in header.php will not effect the elements in table.php unless you use the appropriate event binding like the .on() event below. I think...?
To resolve this, you have to use the .on event:
$( "#target" ).on( "click", function() {
alert( $( this ).text() );
});
The .on event will bind itself to all current, and later instances of the selector, in this example the selector is #target.

Related

Update db data without losing collapsed rows

Sorry for being dumb, I'm quite new to PHP.
I have a table filled with data from a database:
machine.php
<?php require "database.php"; // here the connection stuff
const DOT_ONLINE = "🟢";
const DOT_OFFLINE = "🔴";
?>
<table id="tableMachines" class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Online</th>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Address</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $db->prepare("SELECT * FROM machines ORDER BY address;");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_OBJ);
foreach ($stmt->fetchAll() as $row) {
$rowId = "row" . $row->name;
$output = "<tr data-bs-toggle='collapse' data-bs-target='#$rowId'>"
. "<td>" . ($row->online ? DOT_ONLINE : DOT_OFFLINE) . "</td>"
. "<td>" . $row->name . "</td>"
. "<td>" . $row->type . "</td>"
. "<td>" . $row->address . "</td>"
."</tr>";
echo $output;
$output = "<tr id='" . $rowId . "' class='collapse fade'>"
."<td colspan='4'>"
."<table class='table table-borderless'>"
."<tr><td>Order: " . $row->job . "</td></tr>"
."<tr><td>Length: " . $row->length . "</td></tr>"
."</table>"
."</td>"
."</tr>";
echo $output;
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</tbody>
</table>
<?php
$db = null;
As you can see, the user can click on each row to show some further details.
In the main page I put the above file inside a div:
<div id="tableMachines">
<?php require 'machines.php' ?>
</div>
Periodically I fetch new data:
$(document).ready(function() {
setInterval(function () {
$('#tableMachines').load('machines.php');
}, 5000);
});
It works fine, the problem is when the div reloads I lose the rows that were shown by the user.
It's true I can keep track of which rows were expanded and manually trigger them again after reloading the PHP code, but I don't think this is the correct approach.
Would you mind to help me to understand how to update the data without interfere with the UI?
If this were me, I would track which last machine ID is pulled through and then send that on your load() call. You can then call $('#tableMachines').prepend(data) rather than reloading the whole table - you only reload the latest rows. That way your users choices will be unaffected however you may need to re-bind click/triggers so the new rows expand/hide as well.
Before loading machine.php, you can create a cookie named "expanded_set" in your jquery code that loads machine.php. Each time visitor toggles, you can populate the cookie. In machine.php file, your cookie will be accessible by $_COOKIE['user_expandeds']. Then you can customize machine.php to handle the already-toggled ones to show them also.
I'm not sure of this method for timing issues however, you may also send the "expanded_set" to PHP via a POST type form with a hidden input field with a name which is submitted by jquery automatically also. You can access the posted field with its name as $_POST['expanded_set'].
cookie method may fail if cookies are not allowed by the visitor but using a form method can not be disallowed.

Using AJAX from another page to manipulate a database

I am building a warranty product website as a side project for a small business I work at (We deal with batteries for cars, heavy equipment...). There is a lot going on here.
Basically, when an item gets returned for a warranty inspection the user can input the customer's information and the product information for it to be tracked and managed. I began with making a database in PHP (It is only one table and not fully normalized since it really does not need to be unless there is expansion later on) with only one table that manages transactions.
Each transaction when submitted defaults to ACTIVE status meaning it can be manipulated (Deleted, resolved, or to add a comment) via buttons in the table. To be able to do this I have been using AJAX to be able to use buttons in a table and change the Status to DELETED or RESOLVED.
Now, there are four pages of tables (Like ALL, ACTIVE, DELETED, and RESOLVED) and each ran a very similar code (While loop that displayed the table) with the expectation of the SQL statement. For example the ALL inspections table has nowhere clause in the SQL statement, while the ACTIVE Inspections table would have a where Status = "ACTIVE", as so on for resolved and deleted. Since displaying the data seemed repetitive to have a while loop, I decided to make one table.php page with a function call GetTableData and on each page (ACTIVE, ALL, DELETED...) I would include the PHP file, and then call and pass through the SQL statement, like so...
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Battery Wholesale Inspection Database</title>
</head>
<?php include 'headernNavbar.html'; include 'Actions/connection.php'; include 'Actions/table.php'?>
<body>
<h1 id="title">Active Inspection Database</h1>
</body>
</html>
<?php
$sql = "SELECT TransactionID, CustomerName, PhoneNumber, ReceivedDate, Item, DATE_FORMAT(ManufactureDate, '%m-%y') as Age , InitalVoltage, InitalCCA, Comments, WarrStatus FROM inspection.product WHERE product.WarrStatus = 'ACTIVE' ORDER BY ReceivedDate DESC";
GetTableData($sql, $conn);
?>
Here is what the table.php file looks like...
<html>
<head>
<title></title>
</head>
<?php
include 'Actions/connection.php';
function GetTableData($sql, $conn){
$result = mysqli_query($conn, $sql);
echo "<table id='inspectTable' class='inspectTable'>";
echo "<thead><tr>";
echo "<th>Customer</th>";
echo "<th>Phone</th>";
echo "<th>Received</th>";
echo "<th>Item</th>";
echo "<th>Age</th>";
echo "<th>Voltage</th>";
echo "<th>CCA/AH</th>";
echo "<th>Comments</th>";
echo "<th>Status</th>";
echo "<th colspan=3 >Tools</th>";
echo "</thead></tr>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
echo "<tbody class='dbTable'>";
while($row = mysqli_fetch_assoc($result)) {
$id= $row['TransactionID'];
echo "
<tr><td>" . $row['CustomerName'] ."</td>
<td>" . $row['PhoneNumber'] . "</td>
<td>" . $row['ReceivedDate'] . "</td>
<td>" . $row['Item'] . "</td>
<td>" . $row['Age'] . "</td>
<td>" . $row['InitalVoltage'] . "</td>
<td>" . $row['InitalCCA'] . "</td>
<td>" . $row['Comments'] ."</td>
<td>" . $row['WarrStatus'] ."</td>";
if ($row['WarrStatus'] == 'ACTIVE'){
echo "<td><button class='deleteRow' id='".$id."' >Delete</button></td>
<td><button class='updateRow' id='".$id."' >Update</button></td>
<td><button class='resolveRow' id='".$id."' >Resolve</button></td>";
}
else{
echo "<td><button class='deleteRow' id='".$id."' disabled >Delete</button></td>
<td><button class='updateRow' id='".$id."'disabled >Update</button></td>
<td><button class='resolveRow' id='".$id."'disabled>Resolve</button></td>";
}
}
echo "</tbody>";
} else {
echo "Not Data Avaibable.";
}
}
?>
<script>
$(".deleteRow").click(function()
{
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'Action/deleteAction.php',
data:'id='+del_id,
success: function(data)
{
location.reload();
}
});
});
$(".resolveRow").click(function()
{
var del_id = $(this).attr('id');2
$.ajax({
type:'POST',
url:'resolveAction.php',
data:'id='+del_id,
success: function(data)
{
location.reload();
}
});
});
</script>
</html>
So, as an example when the user is on the ACTIVE inspections page, and the list gets called it is displayed. When the user wants to delete an entery and clicked delete, the deleteAction.php should be called and changes the status from ACTIVE to DELETE. Here is the php for that...
<html>
<head>
<title>delete action</title>
</head>
<?php include 'connection.php'?>
<?php
$id = $_POST['id'];
$sql = "UPDATE inspection.product
SET DeletedDate = now(), WarrStatus = 'DELETED'
WHERE TransactionID = $id";
mysqli_query($conn,$sql);
?>
</html>
Now here is the problem I am facing. When a button (For example the delete button) is clicked nothing changes. Unlike when I first had the while loop (in the table.php) on each page with the AJAX js stuff it worked like a charm. I am just not sure if I am missing something. Here are the things I have tried:
Had each while loop and SQL statement in each PHP page with the AJAX
Created a separate js file and referenced that in the table.php, as well as each PHP page
Only had the AJAX js stuff in the other pages but still called the GetTableData
I have also not accomplished the updating comment button as of yet
Could anyone let a hand here? I would greatly appreciate it! If you see any other things I should do to improve I would also appreciate that. This is my first web project out of the first year!
EDIT:
I also forgot to include that reference to ajax in the table.php, it is there on my system, but I was playing around and forgot to add it in the post! This didn't fix the issue.
EDIT:
So after playing around with it, it does work when putting the ajax js in each php file, however it does not work when I have a separate js file and including that into each php file. Is there a different way to do this for it is a little cleaner?

jQuery action on Ajax ResponseText object

Alright, I'm completely new to jQuery, and I'm probably missing something obvious here...
What I am trying to do is:
1) use JavaScript + Ajax + PHP to pull a table via ResponseText from a MySQL database (currently working)
2) use jQuery to perform actions on the table (not working)
The first part (1) of the code looks like this:
<script>
function displayPeople(String) {
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) {
document.getElementById("People").innerHTML=xmlhttp.responseText;
}
}
var Query = "?String=" + String;
xmlhttp.open("GET","library/display_people.php"+Query,true);
xmlhttp.send();
}
window.onload = displayPeople("");
</script>
<input id="Search_People" placeholder="Search People by Name" size="50" onkeyup="displayTable(this.value)">
<div id="People" style="width:900px; height:200px; overflow-y:scroll;">
The table is dynamically updated while the user types a name in the input field.
The PHP file assembles the Query and returns:
$display_string = "<table>";
while($row = mysqli_fetch_array($Results)){
$display_string .= "<tr>";
$display_string .= "<td>" . $row['FirstName'] . "</td>";
$display_string .= "<td>" . $row['LastName'] . "</td>";
$display_string .= "<td>" . "<button class='editbtn'>edit</button>" . "</td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
NOW, part (2), I would like to perform some action using jQuery on the table entries (the ultimate goal being this: http://www.9lessons.info/2011/04/live-table-edit-delete-with-pagination.html).
To start with, I added this jQuery script to the .html taken from another tutorial (http://jsfiddle.net/tXS6w/) which works great on any "static" table, but has no effect whatsoever on the table above! That is, nothing happens if I click on the button which should instead change label...
$(document).ready(function () {
$('.editbtn').click(function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
How can I make this work?
My knowledge of JavaScript/Ajax/PHP is quite limited, so the simplest solution is the most welcomed!
Thanks!!!
The edit button is generated dynamically so click event wont work as it is a delegated event, so use .on instead of .click
Instead of
$(document).ready(function () {
$('.editbtn').click(function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
use this way
$(document).ready(function () {
$(document).on.('click','.editbtn',function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
now this should work as you intend it to.
for more info on delegated events refer: http://api.jquery.com/on/
I have modified your jsfiddle to showcase delegated events, you can check it.
LIVE DEMO:
http://jsfiddle.net/dreamweiver/tXS6w/291/
Happy Coding :)
try something like this
$('#People').on('click','.editbtn',function () {
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
Reason :
you fiddle code correctly because table is already present in DOM so click event work on it.
But it will not work on element which is dynamically added to DOM for that you have to use jQuery Delegate or On function.
delegate() http://api.jquery.com/on/
On() http://api.jquery.com/delegate/
The buttons with class .editbtn are not yet in the DOM on document.ready because you load the table contents later. You have to add your click event to the buttons after the ajax request is complete.

Access php variable using javascript

Hi I struggling to find the solution for hours and wonder if you guys could help me out
I have index.php that look like this
<?php include_once"connect.php";?>
<!DOCTYPE HTML>
<html>
<head>
....
<style>
....
</style>
<!--- AJAX --->
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getData.php?q="+str,true);
xmlhttp.send();
}
</script>
<body>
<form>
<select name="users" onchange="showData(this.value)">
<option value="">---Select Project---</option>
<?php
// query projects
$query_pr=mysql_query("SELECT * FROM GeneralInfo");
// get project names and its corresponding revision number
while($pr=mysql_fetch_assoc($query_pr)){
echo '<option value="'.$pr['pRevNum'].'">'.$pr['pName'].'</option>';
}
?>
</select>
</form>
<br>
<div id="container" align="right"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.4.min.js"></script>
<script defer="defer">
// FUTURE USE php variable within KineticJS HERE
....
</script>
</body>
The my code work great to calling getData.php after select one of the option value according to the my database. Also I using ajax to get the corresponding data of each option value. Below is the getData.php
<?php
// get the data corresponding with the selected option
$q=intval($_GET['q']);
// establish connection
...
// select the database
// query here
$query ="SELECT DISTINCT BranchInfo.bName, BranchInfo.bRevNum, GeneralInfo.pName, GeneralInfo.pRevNum,BranchItemInfo.bIName, BranchItemInfo.bIRevNum
FROM `GeneralInfo`
INNER JOIN `BranchInfo`
ON GeneralInfo.bName=BranchInfo.bName
AND GeneralInfo.bRevNum=BranchInfo.bRevNum
INNER JOIN `BranchItemInfo`
ON BranchInfo.bIName=BranchItemInfo.bIName
AND BranchInfo.bIRevNum=BranchItemInfo.bIRevNum
AND GeneralInfo.pRevNum= '".$q."'";
// initialize variable with the query
$result = mysqli_query($connection,$query);
echo "<table border='1'>
<tr>
<th>bName</th>
<th>bRevNum</th>
<th>bIName</th>
<th>bIRevNum</th>
<th>pName</th>
<th>pRevNum</th>
</tr>";
$my_arr=array();
// fectching data into array
while($info = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum']."</td>";
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
}
// close connection
...
?>
At this point all the data that I need is display as a table on my page. I want to access the variables in getData.php (e.g $info['bIRevName']) and use it in a javascript within my index.php. I tried this in my index.php
<script>
var myvar= <?php echo $info[bIRevNum];?>";
</script>
and this is not working. Is there sufficient way to do that ?
Appreciate all your helps !!
Thanks a lot !!
I realized that when I create a php variable within my index.php, the script is works. But if I create a php variable within getData.php, the script could not access that variable. Is there any solution for this?
Try something like this:
<div class="hidden"><?php echo $info[bIRevNum];?></div>
And then take info with:
$("div.hidden").text();
Or without jQuery...
document.querySelector("div.hidden").innerText;
What returns that PHP code? returns the expected data?
Easy peasy
<script type="text/javascript">
.....
var some_variable = <?php echo $phpVar; ?>;
.....
</script>
There is a syntax error in your code which you tried. Assuming the value held in the variable is a number, I suggest you try this:
<script>
var myvar = <?php echo $info[bIRevNum];?>;
</script>
If your are taking the variable name as "$info" it wont work.
Change $info to $somethingelse...
Hope it works for you...

Send data from javascript to a mysql database

I have this little click counter. I would like to include each click in a mysql table. Can anybody help?
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
document.write('<p>');
document.write('Count');
document.write('</p>');
document.write('<p id="p1">0</p>');
Just in case anybody wants to see what I did:
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
function doAjax()
$.ajax({
type: "POST",
url: "phpfile.php",
data: "name=name&location=location",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
document.write('</p>');
document.write('Count');
document.write('</p>');
document.write('<p id="p1">0</p>');
This is phpfile.php which for testing purposes writes the data to a txt file
<?php
$name = $_POST['name'];
$location = $_POST['location'];
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $name);
fwrite($fh, $location);
fclose($fh);
?>
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
In particular, pay attention to these bits of code from that article.
Bits of Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
The code from the article
HTML/Javascript code:
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".
The other posters are correct you cannot connect to MySQL directly from javascript.
This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
http://api.jquery.com/jQuery.ajax/

Categories

Resources