I have two sheets. The control displays a list of job details that also contains a column that echos the notes on the active job, and the other sheet is where the operator can attach a note.
What I need to do is alert the user on the control page that the note for a job has been changed, which would happen after the operator submits the note.
Currently, I have a cell that highlights red when there is a note present, but want to actively send an alert when there is a new note.
I've tried an onChange() function but it wouldn't alert until I made an input field and changed it myself on the control page. I also tried the .change function but that didn't work either.
The query sent from the operator page to the SQL database is:
UPDATE operations
SET notes=$notes
WHERE jobID=$jobID
AND operation=$operation"
The code to echo the red cell on the control page is this PHP:
$conN = mysqli_connect(DB_HOST, DB_USER);
if (!$conN) {
die('Could not connect: ' . mysqli_error($conN));
} // Check Connection
mysqli_select_db($conN,"jms");
$jid = $row['jobID'];
$opn = $row['operation'];
$highlight = mysqli_query($conN,
"SELECT notes FROM operations WHERE jobID=$jid AND operation=$opn"
);
while ($data = mysqli_fetch_array($highlight))
if (isset($data['notes']) && $data['notes'] != "") {
echo "<td id='notes' style='background-color:red;width:1%;'>" .
"<input class='target' type='text' value='" .
$data["notes"]. "' >" . "</td>";
} else {
echo "<td style='background-color:white;width:1%;'>" . "</td>";
}
echo "</tr>"; // End the row
$index++;
While the cell that is being echo'd as red has an if (isset()) function to display red if there is a note in the database for the specific job and operation.
EDIT:
Here is the Javascript I've been trying to call with the onChange function:
function newNote() {
var jobID = "X";
var operation = "Y";
alert("New note added to Job No. "+jobID+" at Operation No. "+operation);
}
As you can see, its a very simple piece of script, so I ended up just simplifying the process and using a simple alert of text as a test.
you can do it by JQuery or JavaScript , what you need is to immediately detect any change of DB records by sending request and then receiving response .
use ajax function by either jQuery or java script and make the post target your mentioned control page , and alert the response.
one example by jquery :
$(document).ready(function(){
$.ajax({
type: "POST",
url: "yourcontrolpage",
data: { jid: jid ,opn:opn},
success: function(html) {
alert(html);
}
}); });
for example , you can retrieve the number of records or the latest record , so in the next request you can determine whether there is a change so alert will be executed or there is no change so nothing will be happened
Related
I'm working on a project, and I have an issue. First, let me present a few things to you.
Database
An example on what the database structure looks like
ID | NAME
1 | Daniel
2 | David
HTML / PHP script
What the page itself looks like
<?php
$allUsers = mysqli_query($db,"SELECT * FROM users");
echo "<table class=\"table table-hover\" style=\"width: 100%;\">
<thead>
<tr>
<th scope=\"col\">#</th>
<th scope=\"col\">Username</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($allUsers))
{
echo "<tr>";
echo "<th class=\"inner\">" . $row['id'] . "</th>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "
</tbody>
</table>";
?>
Javascript code
The Javascript code as found on this website as well
$(function () {
$(".inner").dblclick(function (e) {
if($(event.target).attr('class')!="thVal")
{
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
}
});
});
function updateVal(currentEle, value) {
$(document).off('click');
$(currentEle).html('<input class="thVal" type="text" value="' + value +
'"
/>');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
}
});
$(document).click(function () {
if($(event.target).attr('class')!="thVal")
{
$(currentEle).html($(".thVal").val());
$(document).off('click');
}
});
}
Now the first thing I'd like to ask: This does not seem to work on my php page. On my html page on the other hand, where I tried this as well, it does work. What am I doing wrong?
When we've fixed that, how could I make sure that when my user double clicks a value, and changes it, that it updates in the database as well. So, for example, if a user of mine double clicks the value "David" and sets it to "Jeremy", the database will be update to Jeremy as well.
First of all, you should distinguish server script and client/ browser script. PHP is server script, when you run this file, it will be compiled to html file. Javascript/ jquery is browser script, it just runs on html file.
If you want when my user double clicks a value, and changes it, that it updates in the database as well. You should add more code in javascript/ query:
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
// add code here
// submit the value to server to update database
}
});
"This does not seem to work on my php page. On my html page on the
other hand, where I tried this as well, it does work"
"if a user of mine double clicks the value "David" and sets it to
"Jeremy", the database will be update to Jeremy as well."
Actually both question are related to the same problem. When changing your value with JS you're changing your HTML (front only) but by reloading you'll get the value you had at first... If you want to change your database you'll have to use AJAX as said Litvak. Could be something like this...
if (event.keyCode == 13) {
var name = $(".thVal").val();
var id = // you need to get the ID to be able to change your database at the right row
$.ajax({
type: 'POST',
data: {
id : id,
name : name
}
url: 'changeName.php',
dataType: 'html',
success:function(data, text) {
// If change in database worked, do this...
$(currentEle).html(name);
}
error : function(request, status, error) {
// There was a problem, couldn't change database, do this...
}
});
}
and your changeName.php would be where you run your sql script to change the database...
function changeName($id, $name) {
// make your checks here and your sql call
}
changeName($_POST['id'], $_POST['name']);
Background Information
I have some PHP / HTML / JavaScript code that loads a web form. For discussion purposes, let's say this form is the "edit widget details" page.
This form contains a table... with a bunch of rows. Each row has one drop down box - the same one for each row - and the selected value of the drop down is determined based on previously saved data in the database.
Problem
The drop down lists are not being populated by the .append() call that I'm making and I don't know why.
Code
Here's the sequence of events in my logic:
PHP logic - loops through each record that needs to be included in the table... and creates an EMPTY box like so:
for ($i=0; $i < count($w_details['tc']); $i++) {
....
//logic to build basic table structure including:
echo "<td><select placeholder='Domain:' name='domain" .$i ."' id=domain" .$i ."'></select></td>";
echo "<input type='hidden' class='domainvals' id='hidden_domain" .$i . "' name='hidden_domain" .$i. "' value='" .$wdetails['tc'][$i]['destdomain'] . "'/>";
...
}
Then once the page is finished rendering, I have this logic in my document.ready section:
//populate domain list.
$.ajax({
url:"<?php echo site_url('domain/domainlist');?>",
type:'POST',
dataType:'json',
success: function(res) {
//loop through results
var htmlstring = "<option value='' disabled selected>Select the Domain</option>";
for (var key in res) {
if (res.hasOwnProperty(key)) {
htmlstring += "<option value=" + res[key]['domain'] + ">" + res[key]['domain'] + "</option>";
}
}
//find every hidden input that is storing a domain value
$('.domainvals').each(function (i, row) {
console.log($(this).val()) ;
$('#domain'+i).append(htmlstring);
//TODO: add logic to select the right value using $this.val();
});
},
error: function(xhr, req, err) {
//var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
What I've Tried so far:
In the F12 debug window, I've verified that I have a "domain0" control like this:
$("#domain0").find('option')
No error messages appear (just the empty array / list) so I definitely have created it. I can also see the controls on the form.
I tried to change my code that appends the html to hard code the name, like so:
$('#domain0').append(htmlstring);
Again, no errors, but it doesn't populate the list.
Any suggestions would be appreciated. I'm sure it's something simple that I'm just missing.
You can append an option using Javascript/Jquery like this:
$('myDropDown').append($('<option>', {
value: optionValue,
text: optionText
}));
If you are adding those domain
$("#domain(n)")
elements dynamically, then you cannot just access them like
$("#domain0")
do
$(document).find("#domain0") or $("body").find("#domain0")
instead.
I have a html table that is generated VIA PHP and data in a database, what I want to do is have a button in the last cell of each row that says edit and when you click that button the text in the other cells becomes textboxes or other types of input fields so that you can edit them and then press submit which would send that form off to be updated in the database. The code I have right now to generate the table is:
<table style="width:100%; " class = "table table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Status</th>
<th>Description</th>
<?php
if($_SESSION['editGroup'] != 0){
echo "<th>Edit</th>";
}
?>
</tr>
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$checkQuery = "SELECT userGiven, userStatus, userDesc FROM user_Status WHERE organization = 'myOrg' ORDER BY userGiven ASC";
$prepared = $dbh->prepare($checkQuery);
$prepared->execute();
$data = $prepared->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row){
echo "<tr>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='10%'>" . $row['userStatus'] . "</td><td width='70%'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
?>
</table>
What I am trying to do is change the cell with userStatus to a drop down field with the current value as the starting value and the other value in/out as the other value to select between.
I also want to change the userDesc to a textarea and I think I know how to do all this but I am running into a problem conceptually when I try to apply it to the dynamic table.
What I was thinking was that I could use jquery/javascript to get the innerhtml of span variable that could surround those two cells and then change the html to the various input fields containing the current text allowing the user editing them to change those values.
How do I do this for this sort of problem though, I would need onClick events for all the buttons and I wouldn't know how many buttons there would be, that's based off of the number of rows in the table.
That would result in hundreds of lines of redundant code so I assume there has to be a much better way. Anyone know what a way to accomplish this? I found this: http://stackoverflow.com/questions/16202723/how-to-edit-data-onclick which is close to what I want but that seems to be static values where I want to be able to do this for any of the rows in the table.
In your for loop, you'll want to put something identifiable in the <tr> and <td> elements. I'd personally go with a data-attribute. For example:
Echo Row Code
foreach($data as $row){
echo "<tr data-row='{$row[id]}'>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%' data-column='name'>" . $row['userGiven'] . "</td><td width='10%' data-column='status'>" . $row['userStatus'] . "</td><td width='70%' data-column='description'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
So, as you can see I've added a data-row attribute to <tr> which should get the value of the database record's ID. Change it as necessary - I made the assumption it'd be named 'id'. Also, I added the data-column attribute to <td> which should identify each column for us. This is all the modification needed in the PHP.
Now, here's what the JQuery for the edit button looks like:
Front-End Event Listener: Part 1
$( function(){
$(document).on("click", ".btn-info", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var name = $(parent).children("[data-column='name']");
var status = $(parent).children("[data-column='status']");
var desc = $(parent).children("[data-column='description']");
var nameTxt = $(name).html();
var statusTxt = $(status).html();
var descTxt = $(desc).html();
$(name).html("<input name='name' data-dc='name' value='" + nameTxt + "'>");
$(status).html("<input name='status' data-dc='status' value='" + statusTxt + "'>");
$(desc).html("<textarea name='desc' data-dc='description'>" + descTxt + "</textarea>");
$(this).replaceWith("<button class='btn-info-save'>Save</button>");
});
}
Finally, we need to define what happens upon hitting save (the above example changes the "edit" button into a "save" button). That could be anything, but we'll assume it'll be an AJAX call:
Front-End Event Listener: Part 2
$( function(){
$(document).on("click", ".btn-info-save", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var data = {id: id};
$("[data-dc]").each( function(){
var col = $(this).attr("data-dc");
var val = $(this).val();
data[col] = val;
});
$.ajax({
url: "/dynamic-edit/edit.php", // Change this to your PHP update script!
type: 'POST',
dataType: 'json',
data: data,
success: function(ret){
//Do Something
console.log(ret.response);
},
error: function(ret){
console.log(ret.response);
}
});
});
}
Now, in your PHP script that handles the AJAX request:
PHP Code for 'edit.php'
$name = $_POST['data_name'];
$status = $_POST['data_status'];
$description = $_POST['data_description'];
// Do whatever with the data
// Output JSON - get the response in JS with ret.response
// either inside the success or error portion of the AJAX
echo json_encode( ["response"=>"Row edited successfully."] );
This is a very simple example, but it gets the point across. Be sure to change the AJAX url from "/dynamic-edit/edit.php" to wherever you'll make your PHP script that will actually make the updates after submitting.
You'll likely want to do cleanup after a successful edit; for example, changing the text boxes back to just text in a <td>. Also, please note that I just changed them to textboxes. I know you said in your post you wanted to make one the status a dropdown and the description a textarea, but this example should be easy enough to change. I don't know what the values of the dropdown should be, so you'll have to do that part.
Notes
I went with $(document).on("click" ... instead of $(".btn-info").on("click" ... because whenever you're dealing with dynamic content, you always want the event listener on the document, not the element. Why? Because if you click the "edit" button, it disappears and a "save" button appears, you now lose that event listener forever. If you were to re-add the "edit" button (say, after a successful save), that button would need the event listener added again. When you go the route of attaching the event listener to the document, however, you can remove/add all you want and it'll still work.
You can add 'data' attribute to each button with the user id that you want to update. For example:
<button data-iduser='<?= $use["id"] ?>' class='btn btn-info'>Edit</button>
$("btn btn-info").click( function() {
var idUser = $(this).attr("data-iduser");
// some ajax if you want with that iD
});
I have a column of buttons in a table, declared like this:
(file index.php)
echo '';
Then this script reads the data in the row of the button clicked and posts it to another php file:
<!-- scripts that gets the lecturer chosen to SHOW functionality-->
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
});
});
</script>
That file (show_lecturer.php) stores the data read in a table (keep_track) in the database:
(file show_lecturer.php)
<?php
ob_start(); //eliminates buffer collisions
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
?>
Then I create an empty dialogbox with jquery, to populate it with the data taken from the database:
(file index.php)
<!-- The following script generates the empty dialog box -->
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" href="/css/jquery-ui.css">
<script src="/js/jquery-ui.min.js"></script>
<script>
$(function() {
//show lecturer dialog
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
</script>
Then these data are taken from the table keep_track and echoed in the above dialog:
(file index.php)
$name; $surname;
require_once('connect_db.php');
$firstname = pg_query(connect(), "SELECT name FROM keep_track");
while($row = pg_fetch_array($firstname)){ $name = $row['path']." ".$row['name']; }
$lastname = pg_query(connect(), "SELECT surname FROM keep_track");
while($row = pg_fetch_array($lastname)){ $surname = $row['path']." ".$row['name']; }
echo '<div id="show_dialog" class="ui-dialog-content ui-widget-content">';
echo $name."".$surname;
echo '</div>';
?>
So when I click the button of row x, a dialogbox opens with the data from the row x.
The only thing that is not working correctly is this:
The moment I click button x, it opens a dialog but displays a value, but not that of row x. However, when i see the database, the row x is stored there. The value in the checkbox is that of the button clicked before the latest refresh on the page. Its as if there is some mistake in my chain of calls or something (that I cant figure out, thats why Im asking).
To illustrate the data I get:
(Initially the table keep_track is empty)
Press button 1 -> row 1 stored, dialogbox has no content
Press button 2 -> row 2 stored, dialogbox has no content
Press button 3 -> row 3 stored, dialogbox has no content
Refresh page manually
Press button 4 -> row 4 stored, dialogbox has content from row 3
Press button 5 -> row 5 stored, dialogbox has content from row 3
Refresh page manually
Press button 6 -> row 6 stored, dialogbox has content from row 6
Press button 7 -> row 7 stored, dialogbox has content from row 3
I suggest you return your data from the POST via JSON. And please be aware that an AJAX Call is asynchronous. So you won't know when the reply is coming.
So you need to process your results using the ajax Success callback function.
</script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
do_post_and_show_info(names, surname);
});
});
function do_post_and_show_info(names, surname){
request= $.ajax({
type: "post",
cache: false,
url: "show_lecturer.php",
data: { x: names, y: surname} ,
dataType: "json",
});
request.done(function(json){
if (json.status =="ok"){
// DO YOUR THING!
Alert(json.data.names + " " + json.data.surnames);
}
else {
alert("Error! " + json.error + " : " + json.remarks);
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus + ":" + jqXHR.responseJSON);
});
}//do_post_and_show_info
</script>
I usually return a datastructure like this in PHP (so in your show_lecturer.php)
<?
// get your data before this in the variable $data
// put your status "OK" or "ERROR" in $status
// put some error info in $extraInfo
// of course some processing is involved, but here's a simple example
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
// obviously you need to do some error checking, but here's the happy flow
$status = "OK";
$error = "";
$data['names'] = $name;
$data['surnames'] = $surname;
echo json_encode(array(
"status" => $status,
"error" => $error,
"remark" => $extraInfo,
"data" => $data
));
?>
Please be aware this is an example that I have created here in the editor and not in a real working setup. SO please try to understand it instead of copy-pasting it and giving it a run.
I wrote the content of the dialog (div) in another file and used
$("#div").load("content.php", {x:parameter_1, y:parameter_2, ......});
instead of
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
This did the trick.
Now the div is initially invisible and empty, but once the button is clicked, it requests the content.php page to load. Since I'm passing the search parameters when I request the content, I get the data that I wanted.
The problem from before was that when the page loaded, the div was created with the data (even though I hadn't clicked any button). Therefore, when I 'd click a button, it would show me the div with the content from the last page load (last refresh).
There were also other minor changes I had to do to make it work, but this is the main idea.
I am using a PHP function to format any 2D PHP array to HTML table, In that table I need to add a delete button in each row, So when the user clicks the delete button jQuery should take particular fields ( 3 fields ) and submit in a php file and it should give the response without reloading the page, I have several dynamic tables in same PHP files, So i have used $table_name as the form ID to differentiate the FORMS, and In the del.php ( Where my form get submitted ) I decide which table should I look up to delete the row using the PRIMARY KEY. My Problem is Do I have to create Forms Within each table to do this task? or can I simply put some fields and submit the form using jQuery?
Any help would be much appreciable .
function formatArrayToTable($foo, $deletable = 0, $restaurant_id ='', $table_name = '') {
//open table
echo '<table class="imagetable">';
// our control variable
$first = true;
foreach($foo as $key1 => $val1) {
//if first time through, we need a header row
if($first){
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<th>'.$key2.'</th>';
}
if($deletable) {
echo "<th>'Delete'</th>";
}
echo '</tr>';
//set control to false
$first = false;
}
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<td>'.$value2.'</td>';
}
if($deletable) {
$primary = $val1["id"];
echo "<input type='hidden' name='table_name' value='{$table_name}' />";
echo "<input type='hidden' name='restaurant_id' value='{$restaurant_id}' />";
echo "<td><input class='delete_class' type=\"button\" name=\"delete_id\" value={$primary} onclick='SubmitForm($table_name)'/></td>" ;
}
echo '</tr>';
}
echo '</table>';
}
My Javascript Function
function SubmitForm(formId){
var message = "";
$("#"+formId+" input").each(function() {
message += $(this).attr("name");
});
$.ajax({
type: "POST",
url: "del.php",
data: message,
success:
function() {
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide()
}
});
}
-Regards
Your question seems to ask if you can remove items from a DB using just jQuery. Conventionally, as far as I know, this is not doable, because your DB is server-side and your jQuery is client-side. That being said, I am sure some kook has created a library for it. Despite that, to answer your actual question:
You need to know how you can use jQuery to simulate direct removal of a table row from a DB table. Here is a rough example of your needed jQuery, a sample output of your current php function, and something that should live in del.php to handle the actual delete.
Example Table
Quick notes. Add thead and tbody tags to help browsers with the displaying. Remove the onclick="" bit, you are using jQuery, so just add your callbacks with a JavaScript block. Make sure your code adds the `.submittable' class (or other descriptive name) to your table. You could wrap the whole table in a form, then use a plugin like jquery form to handle submissions of each form, but that seems like overkill for only handful of fields, so I will explain how to do it with the raw materials.
<table class="imagetable submittable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>file</th>
<th>meta</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type='hidden' name='table_name' value='secret_image_table' />
<input type='hidden' name='restaurant_id' value='123' />
<input class='delete_class' type='button' name='delete_id' value="Delete" />
</td>
<td>Silly Cat Image</td>
<td>yarny-cat.jpg</td>
<td>{"submitter":"De Zéro Toxin"}</td>
</tr>
</tbody>
</table>
jQuery code block
It is a terrible idea to submit your table name from any client-side form, ajax or otherwise. That is super sensitive information, and any programmer/hacker could use that knowledge to their advantage when trying to attack your site. Despite that, I don't know the usage of this, so it may be fine in your setting. Still bad practice though.
// any time any element with the 'delete_class' on it is clicked, then
$(document).on('click', '.delete_class', function(e) {
var row = $(this).closest('tr');
var data = {
table: $('[name="table_name"]').val(),
id: $('[name="restaurant_id"]').val()
};
$.post('del.php', data, function(r) {
// do some special stuff with your json response 'r' (javascript object)
...
// do what you showed us you are doing, displaying a message
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide();
// remove the row, since it is gone from the DB
row.remove();
}, 'json');
});
del.php
Again, table_name on submission = bad-idea. Horse beaten.
// define a delete function that accepts a table name an id
// define some functions to sanitize your $_POST data, to prevent SQL Injection.
// run said functions before you get to this point
// json response function, since you said you want a response from your js
function respond($data) {
echo #json_encode($data);
exit;
}
if (empty($_POST)) respond(array('error' => 'Invalid request'));
$table_name = $_POST['table_name'];
$id = $_POST['id'];
$response = deleteRecord($table_name, $id);
if ($response == $what_you_expect_on_a_successful_delete) {
// create a response message, in associative array form
$message = array('success' => true);
// add some other information to your message as needed
$message['sideNote'] = 'I like waffles.';
// respond with your message
respond($message);
}
// if we got this far your delete failed
respond(array('error' => 'Request Failed'));
Hope this helps.
If you really want to use jQuery to delete a row in a DB directly, you will need to establish a DB connection from jQuery. Not such a bright idea. Instead, you should have a server side function to do the job and call that function using an AJAX call from jQuery.