How can i know which link I clicked? - javascript

I'm deploying a table where you can edit the columns. For that, in each cell there's an <a> to show a modal to change que value in the database and refresh the page. For now it does well the modal appearing but for the moment the modal appears, the code doesn't know which link was clicked. I need to know it to get the id of the row. The JQuery method that calls the last button of the modal ('Guardar') needs to call a php script by AJAX and send the id of the row (to make the UPDATE statement) and the new value of the column.
I tried to use the methods closest() and find() from JQuery and to set a the id of the row in a data-id attribute.
This is where I deploy the table vía PHP(code is simplified to one column to read and understand it better)
if($resHitos->num_rows>0){
while ($columna = mysqli_fetch_assoc($resHitos)) {
$id=$columna['id'];
echo "<tr data-id='$id'>";
echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito'>".$columna['descripcion']."</a></p></td>";
echo "</tr>";
}
}
This is the modal
<div class="modal fade" id="modalEditarHito" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Editar objetivo</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="newObjetivo">Objetivo</label>
<textarea class="form-control" rows="5" id="editObjetivo"></textarea><br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="editDescripcionHito()">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
The expected result is to see the new value inputed in the exact row that was clicked.

Add listener event on your modal when it is displayed.
$(document).on('show.bs.modal','#modalEditHito', function (e) {
var $invoker = $(e.relatedTarget);
//this may help
//var tr = $invoker.closest('tr');
//var tr_id = tr.attr("data-id");
});

You can use a data attribute to uniquely identify rows. or you can simply add id attribute like this
echo '<tr data-id=".$columnna['id'].">';
You should change this line
echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito'>".$columna['descripcion']."</a></p></td>";
to
echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito".$columnna['id']."'>".$columna['descripcion']."</a></p></td>";

Related

Pass Javascript variable in PHP query

I've created a table with data and auto-generated buttons. When i click in 1 button .add_task, a modal opens, which display another table according to retrieved key: user_id of button.
The functionallity of button is shown below:
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"actions/fetch_jobs.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
$('#jobModal').modal('show');
$('.modal-title').text("Jobs");
`$('#vis_id')`.val(user_id);
$('#show_inseredjobs').html(data);
}
})
});
The problem is that i want to take value $('#vis_id') or user_id and put it in a php query of opened modal.
<div id="jobModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" />
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
</div>
More specifically, i want to do that: $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
How can i pass that js variable in php?
I tried different combinations of expressing variable, but the code crashes. If i try to give manually numbers, the code works. To conclude, how can i pass value $('#vis_id') or user_id in $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
Your modal is static and you can't run PHP code in the modal.
I think you must do this.
First change:
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
To:
<div id="job_desc"></div>
And then, in the actions/fetch_jobs.php file when you return data:
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = '".$_POST["user_id"]."' AND job_desc='Fumes'");
if ($result->num_rows == 1) {
$response = "";
foreach ($result as $row) {
$response .= '<span class="glyphicon glyphicon-print"></span>print button';
}
}
return json_encode([YOUREPREVIOUSRETRUN,$response]);
And then in ajax part you must parse json data first variable [YOUREPREVIOUSRETRUN] your previous data and second data you must put it on $("#job_desc").html(second data).
Or, you can use an iframe for this part but I don't suggest that.
From what I can tell by looking at the structure of your modal, you seem to be using Bootstrap, though I am unclear on the version. If it's Bootstrap 5, read on. If not, please add that information to your question, and let me know.
Here's how you can do it all in one call.
First, change the page from which you are opening the modal, so that the modal isn't a part of it. You need to make a separate file to hold the modal contents. Let's call that file remote-file.php. This would be inside that file.
<?php
// your PHP logic goes here - parse the received $_POST parameters, prepare your query - if needed, query your database
// retrieve the data, and place it in variables for later display
require 'conn.php';
$jvid = isset($_POST['jvid'] ? (int)$_POST['jvid'] : 0;
$result = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$result->bind_param("i",$jvid);
$result->execute();
if($result && $result->num_rows == 1) {
// row found, do stuff
$output = '<span class="glyphicon glyphicon-print"></span>print button';
} else {
$output = "Nothing found";
}
?>
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" value="<?=$jvid?>">
<?php
echo $output;
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
Some notes about previous code:
it is assumed that jvid in your database is an INT type colum. Because of that, we could do (int)$_POST['jvid']
if jvid is not an INT but another type of column, we wouldn't do the (int)$_POST['jvid'] bit, and our binding would be slightly different
// prepare the query
$jvid = $_POST["jvid"];
$results = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$results = $conn->bind_param("s",$jvid);
$result->execute();
Next, in the original page, where your buttons are (and where your modal's HTML was), you would need this line of code for the modal.
<div class="modal fade" id="jobModal"></div>
This is going to be a wrapper for your modal content. All the rest will be going inside the remote-file.php. Also, your button element, the one that's opening the modal on click? That button doesn't need to have a data-bs-target attribute, because the following code will work (since you're using jQuery and all).
<button class="btn btn-lg btn-success add-task" id="btn" data-id="1234">Open modal</button>
<div class="modal fade" id="jobModal"></div>
<script>
$(document).ready(function() {
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$('#jobModal').load('remote-file.php',{'jvid':user_id },function(){
var jobModal = new bootstrap.Modal($('#jobModal')[0], {
backdrop:"static",
show:true
});
jobModal.show();
});
});
});
</script>
Final notes:
jQuery version: 3.6.3
Bootstrap version: 5.3.0

Bootstrap Model Window Not Showing by Calling Through JQuery

What I am trying to do is that pop up a bootstrap js model by using jquery call that is
$("#id").modal("show")
but it's not working in any case, there are several cases mentioned in this link but none is working in my case.
also I have gone through the following links
bootstrap model is not working
Bootstrap modal window not showing
calling to bootstrap model for a link
Bootstrap modal - popup window not showing
https://getbootstrap.com/docs/4.0/components/modal/
but I am not able to get any help, I can trigger the model by having an extra button and calling click() function of button by jquery, this works fine but not modal case.
My Modal code is here
<div class="modal fade" id="addLocationTagModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabelLocation">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" id="idButtonCloseLocation" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabelLocation">Enter Location</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-9 col-md-9 col-sm-12 col-xs-12">
<div class="form-group">
<?php
$preferredLocation = "";
if (strtolower(getUserPreferredLocation($row_user, $conn)) !== "no") {
$preferredLocation = getUserPreferredLocation($row_user, $conn);
}
?>
<input type="text" class="form-control" value="<?php echo $preferredLocation; ?>" placeholder="Location" id ="locationSuggested" name="locationSuggested" />
<span>
<span id="suggesstionBoxLocation" ></span>
</span>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<div class="pLace-order">
<button type="button" name="buttonLocation" onclick="getTagSelected();" class="btn btn-success" value="submit">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
Jquery call is here
<script>
function detachStore(url){
//alert(url);
//document.getElementById("buttonDeleteStore").click(); // Click on the checkbox
// For Testing Purpose to set the data-target
jQuery.noConflict();
$(document).ready(function () {
$("#addLocationTagModel").modal("toggle");
alert("Hello");
//$("#buttonDeleteStore").click();
// $('#addLocationTagModel').appendTo("body").modal('show');
});
}
And HTML and mixed PHP code is here below, I have onclick function on the element call that is working perfectly.
<td>
<?php
$i = 1;
foreach (unserialize($row['store_id']) as $store_id) {
$stores = $conn->query("select * from tb_stores where ID = " . $store_id);
while ($stores_row = $stores->fetch_assoc()) {
$store_price = $conn->query("select * from tb_add_price_of_products where product_id=" . $row["ID"] . " and store_id=" . $stores_row["ID"]);
$store_price_row = $store_price->fetch_assoc();
//echo $store_price_row["price"];
if ($i == 1) {
echo "<a href='#' data-toggle='modal' title='$"
. $store_price_row["price"] . "-" . $stores_row["location"] . "'"
. " onclick=\"detachStore('" . $url . "product-registry?action=delete-store&product_id=". $row["ID"] . "&store_id=" . $stores_row["ID"] . "');\" >"
. $stores_row['name'] . "</a>";
} else {
echo ", <a href='#' data-toggle='modal' title='$"
. $store_price_row["price"] . "-" . $stores_row["location"] . "'"
. " onclick=\"detachStore('" . $url . "product-registry?action=delete-store&product_id=". $row["ID"] . "&store_id=" . $stores_row["ID"] . "');\" >"
. $stores_row['name'] . "</a>";
}
$i++;
}
}
?>
<button type="button" id="buttonDeleteStore" data-toggle="modal" data-target="#add_price_modal">Button</button>
</td>
I have spent hours on it, even no JavaScript error, May be I am doing something wrong at some place, if anybody can pull it out that would be appreciated.
I was going through some other post
TypeError: $(...).modal is not a function with bootstrap Modal
and I replaced
$("#id").modal("show")
with
jQuery("#id").modal("show")
and this trick worked here and it started working. Still I don't know the reason like why it wasn't working with $.
One more thing, we need to include the jQuery.noConflict(); above then the statement to avoid repetitions.

How to send href value in tablesorter to dialog modal?

Problem
I have problem in sending/passing href value in tablesorter to my dialog modal.
It's become complicated when the target location is the dialog modal.
Example (table.php)
This is a partial of my code since above it is a PDO PHP query to get my data from database. Important point is at the href code inside foreach
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-dropbox' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr style='text-align: center;'>";
echo "<th style='text-align: center;'>No.</th>";
echo "<th style='text-align: center;'>Conference Name</th>";
echo "<th style='text-align: center;'>Conference Sponsor</th>";
echo "<th style='text-align: center;'>Date (Start)</th>";
echo "<th style='text-align: center;'>Date (End)</th>";
echo "<th style='text-align: center;'>Budget</th>";
echo "<th style='text-align: center;'>Status</th>";
echo "<th style='text-align: center;'>Approve</th>";
echo "<th style='text-align: center;'>Reject</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
//echo "<td><a href='reject.php?idstudent=".$row['matricno']."&idbook=".$row['serialno']."'><img src='pic/remove-icon-png-15.png' width=15px></a></td>";
foreach ($r as $row){
echo "<tr align='center'><td>".$row['id']."</td><td>". $row['conf_name'] ."</td><td>". $row['conf_sponsor'] ."</td><td>". $row['conf_fDate'] ."</td><td>". $row['conf_lDate'] ."</td><td>RM ". $row['conf_budget'] ."</td><td>". $row['conf_status'] ."</td><td><a href='#' onclick='this.href='indexSuperUser.php?idconf=".$row['id']."' role='button' data-toggle='modal' data-target='#login-modal3?idconf=".$row['id']."'><img src='images/good.png' width=15px></a></td><td><a href='#?idconf=".$row['id']."' role='button' data-toggle='modal' data-target='#login-modal4'><img src='pic/remove-icon-png-15.png' width=15px></a></td></tr>";
//$startrow++;
}
echo "</tbody>";
echo "</table>";
}
else{
echo "<p align='center'>Nothing to show you :( I am really sorry for this T_T </p>";
}
Example #2 (dialogmodal.php)
Now here is where i want to display the variable from the table. Just for testing purpose i am trying to display the idconf to see if the id displayed successfully.
<!-- BEGIN # MODAL LOGIN -->
<div class="modal fade" id="login-modal3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" align="center">
<img style="position:relative; LEFT:20px; WIDTH:100px; HEIGHT:100px" id="img_logo" src="images/logofpeNEW2.png">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</div>
<!-- Begin # DIV Form -->
<div id="div-forms">
<!-- Begin # Register Super User Form -->
<form id="approved-form">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Approve this event?.</span>
</div>
<input type="text" id="idconf" class="form-control" value="<?php echo $_GET['idconf']; ?>">
</div>
<div class="modal-footer">
<div>
<button type="submit" class="btn btn-primary btn-lg btn-block" style="background-color: green">Approve</button>
</div>
</div>
</form>
<!-- End # Register Super User Form -->
</div>
<!-- End # DIV Form -->
</div>
</div>
</div>
<!-- END # MODAL LOGIN -->
<!--END LOGIN AREAD--------------------------------->
Result
The result? Its either undefined index: idconf or nothing. Means that im trying to send variable like this #?idconf=".$row['id']."....... since if i put like this dialogmodal.php?idconf=".$row['id'].".. my dialog ends up opening another dialog that is weird to say.
Flow
The flow is simple. Start from the table.php where it will grab the data from my database and display using tablesorter plugins. Then it will open at the dialog modal. Right side of the table have approved and rejected. So this two things comes from the href itself. Just like on the picture.
Duplicated?
Maybe yes. but its a little bit different. I give here two link almost the same problem as me:
Dynamically load information to Twitter Bootstrap modal
Send parameter to Bootstrap modal window?
However. My problem a bit slightly difficult i think. Mine is not about show the data when button clicked. But instead, i need to click the button to open the modal dialog first then clicked href button to open each row with unique id.
my stackoverflow account could be blocked at any time since i got many downvoted question. I dont know what happen to people nowadays. So i try to do proper and detailed here. If still downvoted, it will be my last here.. :)
Oh never mind. I got it work out by using from someone. I can't remember the link but credit to him for mentioning about using "data-your variable" and call it using jquery and send it back to the modal dialog id. Like this
<a id='approved' href='#' role='button' data-toggle='modal' data-target='#login-modal3' data-id='".$row['idconf']."' data-confname='".$row['conf_name']."' data-confsponsor='".$row['conf_sponsor']."' data-conffdate='".$row['conf_fDate']."' data-confldate='".$row['conf_lDate']."' data-confbudget='".$row['conf_budget']."' data-confstatus='".$row['conf_status']."' data-useremail='".$row['email']."' data-username='".$row['name']."' data-balanceuser='".$row['balance']."' data-m='".$row['matricNo_fk']."'><img src='images/good.png' width=15px></a>
See how many data i send? Then call it using jquery like this..
$(document).on("click", "#approved", function () {
var idconf = $(this).data('id');
var confname = $(this).data('confname');
var confsponsor = $(this).data('confsponsor');
var conffdate = $(this).data('conffdate');
var confldate = $(this).data('confldate');
var confbudget = $(this).data('confbudget');
var confstatus = $(this).data('confstatus');
var useremail = $(this).data('useremail');
var username = $(this).data('username');
var balanceuser = $(this).data('balanceuser');
var m = $(this).data('m');
After declare this variable, then on the next line of this code, send it to the modal dialog id such as this.
$(".modal-body #idconf").val( idconf );
$(".modal-body #nameconf").val( confname );
$(".modal-body #sponsorconf").val( confsponsor );
$(".modal-body #dateSconf").val( conffdate );
$(".modal-body #dateEconf").val( confldate );
$(".modal-body #budgetconf").val( confbudget );
$(".modal-body #statusconf").val( confstatus );
$(".modal-body #emailuser").val( useremail );
$(".modal-body #nameuser").val( username );
$(".modal-body #balanceuser").val( balanceuser );
$(".modal-body #m").val( m );
$('#addBookDialog').modal('show');
On the modal dialog, use the id mentioned.
<form id="approved-form">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Approve this event?.</span>
</div>
<input type="hidden" id="idconf" class="form-control" value="" disabled>
<input type="text" id="nameconf" class="form-control" value="" disabled>
<input type="text" id="sponsorconf" class="form-control" value="" disabled>
<input type="text" id="dateSconf" class="form-control" value="" disabled>
<input type="text" id="dateEconf" class="form-control" value="" disabled>
<input type="text" id="balanceuser" class="form-control" value="" disabled>
<input type="text" id="budgetconf" class="form-control" value="" disabled>
<input type="text" id="statusconf" class="form-control" value="" disabled>
<input type="text" id="emailuser" class="form-control" value="" disabled>
<input type="text" id="nameuser" class="form-control" value="" disabled>
<input type="hidden" id="m" class="form-control" value="" disabled>
</div>
I am not saying this is efficient in terms of speed or whatever. but it solved my problem and user problem. Case solved

php get input value without clicking a button or submitting it

I have an html code where the value is stored in an input with hidden as its type. I want to use that value and put it in a php variable without clicking button or anything. Just plainly get the value (because I need it when I am going to get a value from sql). MY AJAX CODE DOESN'T WORK... The value i'm trying to get is the number 45, which can be found inside the code below.
Here is my html code (it's inside a modal and the php code is there also):
<div id="CalenderModalEdit" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel2">Case Details</h4>
</div>
<div class="modal-body">
<form id="antoform2" class="form-horizontal calender" role="form">
<div class="form-group">
<label class="col-sm-3 control-label">Hearing #</label>
<div class="col-sm-9">
<p style="margin-top: 8px; text-align: justify" id="title_disp"></p>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Case #</label>
<div class="col-sm-9">
<p style="margin-top: 8px; text-align: justify" id="case_id"></p>
<input type="text" class="form-control" id="id_case" value="45">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Complainant (s)</label>
<div class="col-sm-9">
<?php
include ("config.php");
if(isset($_POST['userID'])) {
$uid = $_POST['userID'];
echo $uid;
// Do whatever you want with the $uid
$view = mysqli_query ($conn, "SELECT idCase, lastName, firstName, Case_idcase, Person_idPerson
FROM complainant, person, bar_case
WHERE Person_idPerson = idPerson AND Case_idCase = idCase AND idCase = '$uid';");
//mysqli_close($conn);
while ($line = mysqli_fetch_array($view)) {
?>
?>
<p style="margin-top: 8px; text-align: justify" id="comp"><?php echo $line['firstName'].' '.$line['lastName']?></p>
<?php }} mysqli_close($conn); ?>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default antoclose2" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
AJAX SCRIPT:
<script>
$(document).ready(function() {
var userID = $("id_case").attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: "../1-secretary/calendar-hearing.php",
data: { userID : userID },
success: function(data)
{
alert("success!");
}
});
});
</script>
I want to use it in the same page. How can I do it? Please help me. Your help will be much appreciated. Thank you.
Your (and any other) php script just generates HTML on a server where the script runs and then sends this HTML to a browser which runs on a different machine. To read something from an HTML page (which as you remember is in a browser on a different machine) you need to send some data back to the server where your script can intercept it.
The fact that HTML, php and SQL code are in the same file on the server doesn't mean that generated HTML page and php/SQL code are run on the same machine.
So you can't get the value without sending data back to the server where your script is. People were right - you need either AJAX or form submission to get the value.

Update mysql table with php using ajax

Here I create a table http://jsbin.com/OJAnaji/13/edit and DEMO: http://jsbin.com/OJAnaji/13
So when users click on some row on table automaticly populate input fields with values from table into modal window. Modal window user open when click on button "Edit row". Now I need to know how I can update mysql table with columns: Name,Gender,Age,Donuts eaten.
I create js ajax:
$("#edit").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#name").val()!="") {
$.ajax({
url: "update.php",
type: "POST",
async: true,
data: { Name:$("#name").val(), Gender:$("#gender").val(), Age:$("#age").val(), Donuts_eaten:$("#donuts_eaten").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
}
});
HTML - modal window and button:
<!-- Button trigger modal -->
<button id="edit" class="btn btn-success disabled" type="button" data-toggle="modal" data-target="#myModal">
Edit selected row</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
<div class="input-group">
<span class="input-group-addon">Name</span>
<input type="text" value="" id="name" class="form-control" placeholder="Type name">
</div></br>
<div class="input-group">
<span class="input-group-addon">Gender</span>
<input type="text" id="gender" class="form-control" placeholder="Gender?">
</div></br>
<div class="input-group">
<span class="input-group-addon">Age</span>
<input type="text" id="age" class="form-control" placeholder="Number of age">
</div></br>
<div class="input-group">
<span class="input-group-addon">Donuts eaten</span>
<input type="text" id="donuts_eaten" class="form-control" placeholder="Number of donuts eaten">
</div></br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
So how I can now update MySql database with php:
so file update.php how must looks like:
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
//HOW I CAN UPDATE MYSQL DATABASE, WHAT I NEED TO ADD HERE?
?>
You should have a column in the table which is an auto-increment column, such as "id" or like the example below uses "index_id". This should be used when creating your form, and sent along with the $_POST array to reference the row you are updating. This is a simple example, which you can use to get you started.
$_POST = stripslashes_deep($_POST); # you will want to better filtering for security.
if(isset($_POST['Name']) && $_POST('Name') !=''){
$query = "UPDATE stat
SET Name ='". $_POST['Name'] . "',
Gender ='". $_POST['Gender'] . "',
Age ='". $_POST['Age'] . "',
Donuts_eaten ='" .$_POST['Donuts_eaten'] . "'
WHERE
index_id = '". $_POST['index_id'] . "'";
$result = mysql_query($query) or die(mysql_error());
exit(json_encode($_POST));
}
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
For your MYSQL table you can run this in your MYSQL PhpMyAdmin:
ALTER TABLE `stats` ADD `index_id` INT( 3 ) NOT NULL AUTO_INCREMENT FIRST ,
ADD PRIMARY KEY ( `index_id` )
In your update.php, do like this,
$name = $_POST['Name'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$donuts = $_POST['Donuts_eaten'];
$query = "UPDATE `your_table_name` SET name ='".$name."', gender ='".$gender."',
age='".$age."', donuts_eaten ='".$donuts."' ";
mysql_query($query, $con);
Just a basic to basic structure on what you need to do in update.php its up to you to kick it a notch and you've used POST in your ajax that why its $_POST.
note: Dont use reserved word as your field name in the database.

Categories