I'm trying to edit the profile of each user by the admin using bootstrap modal in php.
Here is the summary what I'm doing.
An anchor tag in admin.php page :
Modal at admin.php page.
<div id="theModal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
And javascript in the same page i.e admin.php
$('.li-modal').on('click', function(e){
e.preventDefault();
$('#theModal').modal('show').find('.modal-content').load($(this).attr('href'));
});
here is editprofile.php.
In this page I've selected that user's information who has been clicked to edit, on that above anchor tag.
<?php
$connect = mysqli_connect('localhost','root','','db');
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT * FROM user where id = '$id'";
$run = mysqli_query($connect,$query);
}
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading text-center">
User Information
</div>
<form action="edit.php" method="POST" id = 'myform'>
<!-- body of the bootstrap modal -->
<?php
while($row = mysqli_fetch_assoc($run)){
?>
<label for="name">First Name</label>
<input type="text" name = 'fname' value = '<?php echo $row['fname'] ?>' class = 'form-control'>
<?php
}
?>
<div class="modal-footer">
<input type="button" name="save" class="btn btn-primary" data-dismiss="modal" value="Save Changes" form = 'myform'>
</div>
Here is I want to do:
I want to submit a form (which is there in modal) with updated data by clicking on button that says Save Changes
And I want to redirect the user back to the admin.php page when the admin click outside the modal or when s/he click on the close icon at the top right of the modal.
Also want to show the success message when the admin successfully update the data.
How would I do that?
I don't know how to use a form with in a modal and then how to submit that , there may be some non standard approach , bare me with that.
I never used bootstrap, but I have noticed that you have PHP syntax error in Your 'inline php' or mixed html/php portion inside while loop.
This:
<?php echo $row['fname'] ?>
Should look like this:
<?php echo $row['fname']; ?>
semicolon is missing in Your example.
Other than that, when You just want to echo something in mixed html/php, You don't need php open tag.
Although one should avoid mixing html/php directly as it is very old PHP fashion,
something like this is recommended (semicolon at the end is not needed in this case):
<?=$row['fname']?>
// wrapped in "()" is ok as well, kinda more readable
<?=($row['fname'])?>
And not only that..
You cannot write html tag argument values separated with blank space everywhere. Won't work.
Not like this:
name = 'fname' value =
But like this:
<tagname attribute='value' otherattribute='value'> ...
Try to fix those first.
Related
I have a page where I make a table from php deploying the result of a previous query. It shows the ID in the first column. I want to have some colums clickable to edit the value, changing it in the database and refreshing the page. For that it appears a Bootstrap modal when you click the link columns (the ones with ). When you fill the modal it sends the information to a JQuery script that calls a php page via AJAX. That php page can be called asynchronously to edit the value in the database and it requires the new value and the ID of the row to make the UPDATE SQL statement.
I need to send the ID of the row you click to the JQuery method that uses AJAX. But in the moment i call the function, i don't know how to send the ID as parameter.
I have tried to find the ID of the row you click by touching the DOM vía JQuery adding ids to the rows but it's just too complicate for my level.
This is where php deploys the table with the information.
$resISDEFE = mysqli_query($conexion,"SELECT * FROM personal_isdefe WHERE proyecto=".$idProyecto);
if($resISDEFE->num_rows>0){
$index=0;
while($isdefe = mysqli_fetch_assoc($resISDEFE)){
$resCategoria = mysqli_query($conexion,"SELECT * FROM categoria_isdefe WHERE id=".$isdefe['categoria']);
$categoria = $resCategoria->fetch_row();
$idISDEFE = $isdefe['id']; <-- I save the row's ID here -->
echo "<tr id='isdefe'>";
echo "<td><p>".$idISDEFE."</p></td>";
echo "<td><p>".$categoria[1]."</p></td>";
echo "<td><p>".$isdefe['edg']."</p></td>";
echo "<td><p><a data-toggle='modal' data-target='#modalConcepto'>".$isdefe['porcentaje']."%</a></p></td>";
echo "<td><p>".$isdefe['horas_contratadas']."</p></td>";
$importe_prestacion = $isdefe['horas_contratadas'] * $categoria[2];
echo "<td><p>".number_format($importe_prestacion,2,",",".")." €</p></td>";
echo "<td><p>".number_format(($isdefe['importe_variable']+$importe_prestacion),2,",",".")." €</p></td>";
echo "</tr>";
}
This is the modal it appears.
<div class="modal fade" id="modalConcepto" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Editar concepto</h4>
</div>
<div class="modal-body">
<div class="form-group">
<textarea class="form-control" rows="10" id="newConcepto"></textarea><br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick='editConcepto(<?php $idISDEFE ?>)'>Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
And this is the JQuery method that is called when you click "Guardar".
function newConcepto(id, newConcepto){
if(newConcepto!=""){
$.get("ajax/editarConceptoISDEFE.php?id="+id+"&con="+newConcepto, function(data){
if(data=="1"){
var time = setTimeout(function(){
location.reload();
},500);
}
else alert("Error al actualizar el concepto");
});
}
}
function editConcepto(id){
var newConcepto = $('#newConcepto').val();
newConcepto(id,newConcepto);
}
}
The expected result is that when the page is reloaded, you could see the changed value exactly in the row you clicked before.
There's a lot going on in this question, but I'm going to give it a shot and you can steer me in a different direction if this isn't what you're looking for.
How to get the value of another cell in a row with jQuery
Wrap the cell you want to get in some sort of identifier span or div (in my example it's .span-of-other-cell). Use the jQuery .closest function to get the "row," and then use .find to locate your identifier and its value:
$(document).on('click', '.some-cell', function () {
var id = $(this).closest('.table-row').find('.span-of-other-cell').val();
});
Some helpful links:
.closest: https://api.jquery.com/closest/
.find: https://api.jquery.com/find/
How I personally store IDs for later use
I use html's data- prefix for element attributes.
<div data-id="12345"></div>
If you add a data- attribute to your row, the javascript above is simplified, and the ID visually hidden (though easy to access for anybody with basic browser skills, so this is not meant to obfuscate or be secure if needed):
$(document).on('click', '.some-cell', function () {
var id = $(this).closest('.table-row').attr('data-id');
});
Let me know if this helps, or if I misunderstood and need to go a different direction with my answer.
As for passing the ID back as a parameter...
This really depends upon your goals. If the ID doesn't need to be secure (and it sounds like it's displayed in a table, so in no need of being secured), then you could just pass it back to PHP with AJAX using the GET protocol:
// assume that var "id" is accessible from this ajax function
$.ajax({
url: "script.php?id=" + id
});
Basically i want whoever creates a note on my website to be the "author" of that note.
So whoever is logged in when they create the note should be the author.
At the moment in login_form.php i have created a session which is the "included" in my general_notes.php. In general_notes.php i have the following code for when the user clicks to add a note:
<p class="fa fa-plus hover-cursor icon-spin noSelect" data-toggle="modal" data-target="#addGeneralNote" style="font-size: 16pt;"></p>
which runs:
<!-- Modal -->
<div id="addGeneralNote" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header header-notes">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add General Note</h4>
</div>
<!-- Form submission data -->
<form action="addNewNote.php" method="POST">
<div class="modal-body">
<p>Please enter the note you wish to create.</p>
<textarea id="addGeneralNoteName" placeholder="Enter a note name..." name="title" maxlength="100"></textarea>
<textarea id="addGeneralNoteText" placeholder="Enter note here..." name="content"></textarea>
<input type="checkbox" name="pinned"> Pin Note to your homepage
</div>
<div class="modal-footer footer-notes">
<button type="submit" class="btn btn-success">Create</button>
</div>
</form>
</div>
</div>
</div>
You'll see in the form there is addNewNote.php which runs:
<?php
if (isset($_POST['title'], $_POST['content'], $_SESSION['username']))
{
$title = $_POST['title'];
$content = $_POST['content'];
$author = $_SESSION['username'];
$stmt = "INSERT INTO Notes (NoteName, Note, Author, DateCreated) VALUES (?, ?, ?, GETDATE())";
$params = array($title, $content, $author);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
header('location: general_notes.php');
}
else
{
echo "No Data";
}
?>
Before i added to the isset $_SESSION['username'] it ran fine.
At the moment it hits this part:
else
{
echo "No Data";
}
of the isset function
So how how do i pass through the session username into my addNewNote.php script?
The simple answer is that you didn't call session_start() in addNewNote.php. But I'd also like to elaborate on a comment you made above, hopefully to help future readers:
i for some reason presumed it would get the session from the previosu page
The "previous page" was a separate HTTP request entirely, and the two have no connection to one another. Much in the same way that a JavaScript application re-starts with each page load, so does a PHP application start anew with each page load.
Consider each individual HTTP request to be its own separate instance of the application. While these instances can share data via external data stores, such as a database or session state, the application itself retains nothing in-memory about any other running or previous instance.
So while the data may indeed be in the session data store (which is external to the application itself), each instance of the application needs needs to connect to that data store in order to use it. Just as one must connect to a database in order to use it, one must also invoke session_start() in order to use the session.
I have two php page.I'm using Bootstrap, php and mysql. In the first page I load three objects into div from mysql database of the user logged. To do this I'm using the next code:
<div class="container">
<div class="row">
<?php
require_once('function.php');
conectar('localhost', 'root', '', 'mydb');
$consulta1 = mysql_query('SELECT id FROM user WHERE username="'.$_SESSION["name"].'"');
$result = mysql_query('SELECT * FROM finc WHERE Usuario_idUsuario="'.$_SESSION["idUser"].'"');
if ($row = mysql_fetch_array($result)){
do{
echo '<div class="col-lg-4">' ;
echo '<img class="center-block img-circle" src="data:image/gif;base64,R0lGODlhOw=="
alt="Generic placeholder image" style="width: 140px; height: 140px;">';
echo '<h2 class="text-center">'.$row['name'].'</h2>';
echo '<p align="center">'.$row['data'].'</p>';
echo '<p align="center">'.$row['tao'].'</p>';
echo '
<a type="button" class="btn btn-success" href="secondPage.php" role="button">Entrar »</a>
';
echo'</div>';
}while ($row = mysql_fetch_array($result));
} else {
echo "¡ No data for this user!";
<a}
?>
<!-- /.col-lg-4 -->
</div>
<!-- /.row -->
</div>
I need send the id value depending of the button clicked for load the data associated in the next php page. For example, If I click in the second button created in the do-while loop I need send the id=2 to the sencondPage.php. I have searched how to do this, but only find how to send var into url like sencondPage.php?var=2, And I hate this because user can change url... And adding value into session, but on click I haven't get this.
So, how can I pass the corresponding id value when user click in the link??
Thanks!
You could use an html <form>:
<form method="post" action="[URL FOR NEXT PAGE]">
...
<input type="submit" name="value1" value="Button 1" />
<input type="submit" name="value2" value="Button 2" />
</form>
Now if someone clicks the first button it will send them to the next page with the post data: value1=Button%201, and if they click the second button the it will instead be value2=Button%202. In either case any other form elements inside the form will also be submitted via post. With PHP you can retrieve these values using something like:
if ($_POST['value1']) {
...
elseif ($_POST['value2']) {
...
}
First of all, jEditable works for me - I can enter a value, hit enter and enjoy the sight of the new value in the table. However, this value is never inserted into the database.
As far as I understand, the jQuery code from the jEditable website
$(document).ready(function() {
$('.edit').editable('http://www.example.com/save.php');
});
which I have changed to link to my update.php script
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "database";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['value'];
$id = $_POST['id'];
echo $value;
$updateTest=$conn->query("UPDATE table SET column='".$value."' WHERE ID='".$id."'");
should update the database, but nothing happens. When I look at the network log function of Firefox, I can see that there is no ID submitted (I do not know where this ID is supposed to come from in the first place, there is nothing in the example), but the value is there. There does not seem to be a response from the server, however.
Maybe the table itself is the problem:
while($row = $results->fetch_assoc()) {
$ID = $row["ID"];
print '<tr>';
print '<td><div class="edit" data-pk="'.$ID.'">'.$row["column"].'</div></td>';
print '</tr>';
(I left out the SELECT statement because everything else is displayed correctly)
Sadly, there is no explanation why the div should have an id - it's apparently not what is submitted in the POST request.
I have googled around a bit, but I could not find an answer to this. It's probably obvious, but I just can't find it. Ever since I changed my original prepared statement to this I don't get errors anymore, either.
I would be very grateful for any help, especially if you could explain my mistake to me so I won't repeat it in the future.
If there is any place on the internet with an actual complete (mysqli) example of what the save.php file mentioned in the Jeditable documentation looks like and you have the link (I certainly didn't find it...), I'd take that too.
This is incorrect:
print '<td><div class="edit" data-pk="'.ID.'">'.$row["column"].'</div></td>';
^^
There's no $, so ID is an undefined constant. PHP will probably try to be polite and assume you meant 'ID' isntead (a string containing the letters I and D), which means ALL of your rows are going to show up in the client as data-pk=ID, and not data-pk=1, data-pk=2, etc...
As there seems to be no solution to this (or, more precisely, I'm running out of time for this project), I switched to modals. If anyone comes across this and considers modals a viable option, here's what I've done:
I'm using a GET form and an update page that updates different tables depending on which page the request comes from - that's what "ref" is for.
update.php:
$updateID=$_GET['id'];
$updateRef=$_GET['ref'];
$col1=$_GET['col1'];
$col2=$_GET['col2'];
if($updateRef == "refpage"){
$updateTable=$conn->query("UPDATE my_table SET col1='".$col1."', col2='".$col2."' WHERE ID='".$updateID."'");
header("Location: refpage.php");
die();
}
My modals are generated with the table rows, which is probably the ugliest solution anyone ever used for anything, but it works... (Can't display the form in a table, though, because tables within divs within tables are a terrible idea.)
$results = $conn->query("SELECT col1, col2 ID FROM my_table");
while($row = $results->fetch_assoc()) {
$ID = $row["ID"];
$modalID = $modalID + 1;
print '<tr>';
print '<td>'.$row["col1"].'</td>';
print '<td>'.$row["col2"].'</td>';
print '<td><span class="glyphicon glyphicon-pencil" style="float: right !important"></span></td>';
print '</tr>';
echo '<div class="modal fade" id="editModal'.$modalID.'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Delete</h2>
</div>
<div class="modal-body">
<form action="update.php" method="get">
<div class="row">
<div class="col-xs-6">
col1:
</div>
<div class="col-xs-6">
<input type="text" value="'.$row["col1"].'" id="col1" name="col1" />
</div>
</div>
<div class="row">
<div class="col-xs-6">
col2:
</div>
<div class="col-xs-6">
<input type="text" value="'.$row["col2"].'" id="col2" name="col2" />
</div>
</div>
<input type="hidden" id="ref" name="ref" value="refpage" />
<input type="hidden" name="id" value="'.$ID.'" />
<input class="btn btn-md" type="submit" id="update" name="update" value="Update" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-md" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>';}
Hope this helps someone. And in case anyone has an idea what was wrong with my original idea, I'd be happy to read the answer. I still think in place updates would be much cooler.
I have a page called service.php that uses a modal window to open a form. The action on the form was service.php.
<div class="modal hide fade" id="myServiceModal" tabindex="-1" role="dialog" aria-labelleby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Service Failure Form</h3>
</div>
<div class="modal-body">
<p>
<form class="well-small" action="service.php" method="POST" id="serviceModalForm" name="serviceModalForm">
<label>Container Selected</label>
<input type="text" name="containerNumber" id="containerNumber" />
<label>Bol Selected</label>
<input type="text" name="bolNumber" id="bolNumber" />
<input type="submit" id="modal-form-submit" name="submit" class="btn btn-success btn-small" href="#" value="Save" />
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Added New Service Failure')
</script>");
}
?>
</form>
This form worked, and it saved to the appropriate table.
Here is my problem: I had to move that form to another page, called dispatch.php. All I did was copy the code, and put it on dispatch.php.
I changed the action of the form to dispatch.php, and that's where I think the problem starts. When I change the action back to service.php, it works for whatever reason.
When I remove the form completely from service.php, the form on dispatch.php no longer works.
I've tried everything to make this work. I removed all of the code from service.php. I even removed the whole file from the folder.
Any insight would be helpful.
You tell the script what to do but you don't tell it to do it.
In order to excecute a your SLQ-query you have to use mysql_query($sql_query_string);
You will also want to connect to your database. Take a look at http://php.net/manual/de/function.mysql-connect.php for more information.
so.. you change the action in service.php:
<form class="well-small" action="dispatch.php" method="POST" id="serviceModalForm" name="serviceModalForm">
Move to dispatch.php
<?php
if(isset($_POST['submit']))
{
$bol = (isset($_POST['bolNumber'])) ? $_POST['bolNumber'] : '';
$container = (isset($_POST['containerNumber'])) ? $_POST['containerNumber'] : '';
if (!empty($bol) && !empty($container))
{
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
// run the query here
print "<br/><br/>".$sql_query_string."<br/><br/>";
}
else { print "<br/><br/>empty values;<br/>"; }
}
else { print "<br/><br/>\$_POST info not received;<br/>"; }
?>
prints (after submit):
INSERT INTO import_view_svc_fail (bol, container_num) VALUES ('input one value', 'input two value');
you probably should check and make sure you got all your post values inside the if(isset($_POST['submit'])) statement, too. or re-work the logic as a whole... it depends if you want to allow blank values, too.
Also, read up on sql injection and why you should learn to use mysqli_ or pdo.