I am dynamically creating html content with PHP and I am creating a button and when that button is clicked It should invoke a PHP script that will update the values of a column of a specific row in the database
Here is my code:
<?php
session_start();
if(!isset($_SESSION['id'])){
header("Location: login.php");
}else{
require_once("mysqli_connect.php");
$query = "SELECT * FROM markeri WHERE odobreno ='F'";
$response = #mysqli_query($dbc,$query);
if($response){
echo "<hr>";
while($row = mysqli_fetch_assoc($response)){
echo "<div align='center' id='markeri'><h3>Naziv: " . $row['naziv'] . "</h3>";
echo "<h3>Ulica: " . $row['ulica'] . "</h3>";
echo "<h3>Opis:</h3>" . "<p>" . $row['opis'] . "</p>";
echo "<h4>Email: " . $row['email'] . "</h4>";
echo "<img src='" . $row['link_slike'] . "' width='300px' /></br>";
echo "<form action='update.php' method='POST'>";
echo "<textarea rows='10' cols='30' maxlength='500' placeholder='Komentar' name='" . $row['marker_id'] . "'></textarea></br>";
echo "<input type='button' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
}
}
}
?>
I tried something like making the name of the textarea equal to the marker_id in my database and making the name of the button the value of marker_id + the string "b" but I don't know how to call them on my update.php script. Usually when it is a normal case and when there is no dynamic content I know how to do it with $_POST['name'];
EDIT:
I used AJAX to dynamically create the HTML as you told me but I've encountered another problem
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'><a href='odobri_prijavu.php?id=" + m.marker_id + "'>Odobri</a>" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>IzbriĆĄi</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
</script>
I tried to use buttons but I couldn't figure how to add event handlers to dynamically created buttons that will post a request via AJAX to some php script with the proper id as the value and the value of the textarea. So I used the anchor tag and I was able to send the id, but I can't send the value of the textarea because I don't know how to reference it and even if I referenced it, it will be NULL because its value is set to the anchor tag at the very beginning and I want to type in text in the textarea.
try this
$(".btn_class_nm").click(function(){
$.ajax({
type: "POST",
url: "http://domain.com/phpscript_filenm.php",
data: {
val1:"val1",
val2:"val1",
},
success: function(msg){
alert( "record updated"); //Anything you want
}
});
});
First of all give a Class Name to the Button as it is being generated dynamically and the number of them can vary based on the number of records the query returns. Something like this:-
echo "<input type='button' class='btn btn-primary btn-xs btn-block active view_data' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
Note that I have add view_data in the class definition. This will help is trapping the onclick event through jquery.
the jquery will be something like
$('.view_data').click(function(){
var yourvariable = JSON.stringify($(this).val()); //Gets Clicked button value
$.ajax({
url:"workstatus.php",
method:"post",
data:{yourvariable:yourvariable, anymoreyourvariables:anymoreyourvariables, , },
success:function(data){
$('#htmldivID').html(data);//If you want result there.
alert( "record updated"); //Anything you want
}
});
I hope this helps you.
Related
I am having trouble getting my button to click after an ajax call. It works fine before the call. However, when i perform a search and return the data from php, the click event stops working.
I have tried the .on event but this just display the form and not the values. I would be grateful if someone could check my code and see where I am going wrong.
I am aware that the element needs to be in the page and I assumed that after he ajax call the dom would contain the element. Obvously i was wrong.
Many thanks
Order of clicks.
1) page load, .edit click works fine.
2) perform search from #btn-search. Pagintes the table but .edit click is no longer firing.
js code
Get inital values from row. works fine on first click. Not after ajax call to display search results
$(function() {
$('.edit').click(function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
service = currentRow.find("td:eq(1)").html();
activity = currentRow.find("td:eq(2)").html();
dept = currentRow.find("td:eq(3)").html();
company = currentRow.find("td:eq(4)").html();
address = currentRow.find("td:eq(5)").html();
user = currentRow.find("td:eq(6)").html();
item = currentRow.find("td:eq(7)").html();
date = currentRow.find("td:eq(8)").html();
var data = id + "\n" + service + "\n" + activity + "\n" + dept + "\n" + company + "\n" + address + "\n" + user + "\n" + item + "\n" + date;
$("#editForm").dialog("open");
$("#id").val(id);
$("#service").val(service);
$("#activity").val(activity);
$("#dept").val(dept);
$("#company").val(company);
$("#address").val(address);
$("#user").val(user);
$("#item").val(item);
$("#datetimepicker").val(date);
});
});
php backend
<?php
if ($_POST['search1'] == '') {
echo 'enter a search term';
exit;
} else {
$search = $_POST['search1'];
$sqlsrch = mysqli_query($conn, "select * from act where item like '%$search%'");
$numsrch = mysqli_num_rows($sqlsrch);
if ($numsrch == 0) {
// what to do if no results found
echo 'No Results Found';
} else {
while ($rowsrch = mysqli_fetch_array($sqlsrch)) {
$id = $rowsrch['id'];
$service = $rowsrch['service'];
$activity = $rowsrch['activity'];
$dept = $rowsrch['department'];
$company = $rowsrch['company'];
$address = $rowsrch['address'];
$user = $rowsrch['user'];
$box = $rowsrch['item'];
$date = $rowsrch['date'];
$date = date('d/m/Y h:i:s', strtotime($date));
$edit = "<button type='button' class='btn btn-primary edit'>Edit</button>";
$action = "<button type='button' class='btn btn-success action'>Action</button>";
$delete = "<button type='button' class='btn btn-danger delete'>Delete</button>";
// Now for each looped row
echo "<tr><td>" . $id . "</td><td>" . $service . "</td><td>" . $activity . "</td><td>" . $dept . "</td><td>" . $company . "</td><td>" . $address . "</td><td>" . $user . "</td><td>" . $box . "</td><td>" . $date . "</td><td>" . $edit . ' ' . $action . ' ' . $delete . "</td></tr>";
} // End our scale while loop
}
}
?>
jquery search click event
$(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
var search = $("#search").val();
$.ajax({
url: "tabletestajax.php",
method: 'POST',
data: {
search1: search
},
success: function(data) {
$("#search").val('');
$(".paginated tbody").empty();
var result = $.trim(data);
if (result === "enter a search term") {
$("input[name='search']").val(result).css({
'color': 'red'
});
return false;
} else if (result === "No Results Found") {
$(".paginated tbody").html('<div>' + result + '</div>');
return false;
} else {
$(".paginated tbody").html(result);
}
}
});
});
});
Probably you need event delegation
$(document).on('click', '.edit', function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
.
.
}
Resource
Event delegation .on()
I'm trying to create a sign up page for people to select open time slots for an event booth. I've hijacked code from "phpmyreservation" but I need specific dates. So I've created two arrays. One for "Day" and One for "Time". The combination of these two values are the id of the each table cell and are values stored in the MySQL table with the person/group that has chosen to man the booth on that date and time.
Assuming I need code to replace "void(0)" and a script that would put the $Aday and $Atime into one or two php variables.
How do I pass the HTML TABLE CELL ID to PHP variables?
<?php
echo '<table><tr><td></td> ';
foreach($global_days as $Aday) {
echo '<th>'.$Aday.'</th>';
}
echo '</tr>';
foreach($global_times as $Atime) {
echo '<tr><th class="reservation_time_th">' . $Atime . '</th>';
foreach($global_days as $Aday) {
echo '<td><div id="div:' . $Aday . ':' . $Atime . '" onclick="void(0)">' . read_reservation($Aday, $Atime) . '</div></div></td>';
}
echo '</tr>';
}
echo '</table>';
?>
This may be useful:
https://github.com/olejon/phpmyreservation
I think I've made progress, but I'm still stumped
I changed:
onclick="void(0)"
to
onclick="process(\'' . $Aday . '\',\'' . $Atime . '\')"
and
created the js file:
function process() {
var theDay = Aday;
var theTime = Atime;
var request = $.ajax({
type: 'post',
url: 'reservation.php',
dataType: "html",
data: { Aday: theDay, Atime: theTime }
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
and added to php file:
if(isset($_GET['theDay']))
{
$day = $_POST[$theDay];
$time = $_POST[$theTime];
}
The page appears to work to some extent but not... $day & $time are null
According to your if statement, a blank response is expected.
You need to check $_POST instead of $_GET since you are making a POST request and of course output something.
if(isset($_POST['theDay']))
{
$day = $_POST[$theDay];
$time = $_POST[$theTime];
echo $day . " " . $time;
}
Also, you have to make process() accept parameters. So your code would look like:
function process(Aday, Atime) {
var theDay = Aday;
var theTime = Atime;
var request = $.ajax({
type: 'post',
url: 'reservation.php',
dataType: "html",
data: { Aday: theDay, Atime: theTime }
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
And your onclick attribute would look like onclick="process($Aday, $Atime)".
I have a database with some record which i output on my page using php. This all works fine but i want to be able to edit the outputted information using the toggle functionality. So basicly i output text when a button edit is clicked i want to toggle that specific table and show the information once more but then in an input form.
foreach( $result as $row2 )
$div = $row2['id'] ;
echo "<div id='d$div; '><table ><tr><td>" . 'Categorie: ' . '</td><td> ' . $row2['name'] . '</td></tr>'
. '<tr><td>' . 'Omschrijving: ' . '</td><td>' . $row2['comments'] . '</td></tr> . '<tr><td>' . '<button id="e1">' . 'Edit' . '</button>' . '</td></tr>' . ' </table><hr>'; } ?></p>
If I would then would then echo everything out again using <form> input fields and use as div id f$div every record would get its unique id.
foreach( $result as $row2 )
$di = $row2['id'] ;
echo "<div id='f$di; '><table ><tr><td>" . 'Categorie: ' . '</td><td> ' . $row2['name'] . '</td></tr>'
. '<tr><td>' . 'Omschrijving: ' . '</td><td>' . $row2['comments'] . '</td></tr> . '<tr><td>' . '<button id="e2">' . 'Safe' . '</button>' . '</td></tr>' . ' </table><hr>'; } ?></p>
Then I would toggle it but I don't have the ids as they still have to be generated. How would I go about this...same would go for the click function but I can generate an id for these in the same way.
<script>
$('#e1,#e2').click(function () {
$('#d?,#f?').toggle();
})
</script>
You can do this with javascript, too. This is one example. You can even use AJAX to update, otherwise you can update the data in database and come back to the same page.
<?php
foreach($result as $row2) {
$div = $row2['id'];
echo "<div id='d$div'><table ><tr><td>" . "Categorie: " . "</td><td> " . $row2["name"] . "</td></tr>" . "<tr><td>" . "Omschrijving: " . "</td><td>" . $row2["comments"] . "</td></tr>" . "<tr><td>" . "<button id=e$div onclick='makeForm(\"$div\",\"d$div\",\"$row2[name]\",\"$row2[comments]\")';>" . "Edit" . "</button>" . "</td></tr>" . "</table><hr></div>\n";
}
?>
<script>
function makeForm(id,mydiv,category,comment){
var div = document.getElementById(mydiv);
var divHTML = "<form action='update.php' method='POST'><table> <tr><td>Categorie: </td> <td><input type='text' name='cat_" +id+ "' value='"+category + "' /></td></tr> <tr> <td>Omschrijving:</td> <td><input type='text' name='comment_" +id+ "' value='"+comment+"' /></td></tr> <tr><td> <input type='submit' value='Safe'></td><td><button onclick='removeForm(\""+id+"\",\""+mydiv+"\",\""+category +"\",\" "+comment+"\" ); return false;'>Cancel</button></td></tr></table> </form><hr>";
div.innerHTML = divHTML;
}
function removeForm(id,mydiv,category,comment){
var div = document.getElementById(mydiv);
var divHTML = "<table> <tr><td>Categorie: </td> <td>"+category + "</td></tr> <tr> <td>Omschrijving:</td> <td>"+comment+"</td></tr> <tr><td><button onclick='makeForm(\""+id+"\",\""+mydiv+"\",\""+category +"\",\" "+comment+"\" ); '>Edit</button></td></tr></table><hr>";
div.innerHTML = divHTML;
}
</script>
Hope this helps...
Background
I am using PHP to created a list of voting sections. Each section is the same except for a unique number, which increases by 1 each time the PHP loops.
I use the PHP variable $n as a counter, and place that in the id attributes in several places in each section.
Current PHP/HTML:
echo "<div id='votesection'>";
echo "<h3 id='rating " . $n . "' style='display:block;'>" .
echo "<h3 id='ratingup " . $n . "' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 id='ratingdown " . $n . "' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote($n)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote($n)'></div>";
echo "</div>";
Goal
When a user clicks on an arrow down or arrow up, certain divs are hidden or displayed. Example, when the up arrow in my second section is clicked, my <h3 id='ratingup2'></h3> would change to visible.
Current JS
function upvote() {
// Script to hide rating, and rating down and display:block ratingup
// Will also need to execture php sql query to increment event rating by one for event by one
}
function downvote(){
// Same script but to show rating down and decrement rating
}
Should I pass every rating id to the script or is there an easier way to do this that I'm missing?
Passing the ID is the easiest way to do it with plain Javascript.
function upvote(n) {
document.getElementById('ratingup ' + n).style.display="block";
document.getElementById('ratingdown ' + n).style.display="none";
}
function downvote(n) {
document.getElementById('ratingup ' + n).style.display="none";
document.getElementById('ratingdown ' + n).style.display="block";
}
A way to do it without passing the ID would be to put classes on the rating DIVs, and pass this instead.
HTML:
echo "<div id='votesection'>";
echo "<h3 id='rating " . $n . "' style='display:block;'>" .
echo "<h3 class='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 class='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote(this)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote(this)'></div>";
JS:
function upvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "block";
parent.querySelector(".ratingdown").style.display = "none";
}
function downvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "none";
parent.querySelector(".ratingdown").style.display = "block";
}
You can create only one wrapper with the id votesection_id and then do everything else with js/ajax
echo "<div id='votesection_" . $n . "'>";
echo "<h3 id='rating' style='display:block;'>" .
echo "<h3 id='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 id='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote($n)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote($n)'></div>";
echo "</div>";
<script>
function upvote(id){
// 1. Go To the server with ajax do your stuff 2. return the current upvotes 3.replace the upvotes h3 text
}
function downvote(id){
// 1. Go To the server with ajax do your stuff 2. return the current downvotes 3.replace the downvotes h3 text
}
</script>
As #idioteque says in their comment, spaces in element IDs are not allowed. The best way to get this information into the document is probably with data attributes.
Also, multiple elements with the same id are not allowed, what you probably need in this case are classes. (I'm assuming this chunk of HTML will be repeated multiple times per page.)
Borrowing #Barmar's idea of passing this into the event handler, here's how I'd change the server code:
echo "<div class='votesection' data-rating-id=" . $n . ">";
echo "<h3 class='rating' style='display:block;'>" .
echo "<h3 class='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 class='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote(this)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote(this)'></div>";
echo "</div>";
And the JS:
function upvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "block";
parent.querySelector(".ratingdown").style.display = "none";
var id = parent.dataset.ratingId;
// do your AJAX or whatever with id
}
function downvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "none";
parent.querySelector(".ratingdown").style.display = "block";
var id = parent.dataset.ratingId;
// do your AJAX or whatever with id
}
I have a form with the option to add another row at the click of a button.
This new row will have a select list as it's input type.
The select list needs to process information from a database that was retrieved on page load.
How can I have the new select list perform a while loop on the data from the database once it is created via the add button.
Here is the code I have so far.
PHP:
echo "<div id=\"FieldGroup\">";
echo "<select name=\"add_project_service_1\" class=\"project_details_service\" value=\"\" required >";
while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}
echo "</select> ";
echo "<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_1\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"\" /> ";
echo "<label>Value: </label><input type=\"text\" name=\"add_project_value\" class=\"project_details_value\" placeholder=\"Value\" value=\"\" /><br>";
echo "</div>";
echo "<input type=\"button\" value=\"Add Button\" id=\"addField\"><input type=\"button\" value=\"Remove Button\" id=\"removeField\">";
Javascript:
<script>
$(document).ready(function() {
var counter = 2;
$("#addField").click(function () {
if(counter>50){
alert("Only 50 extra fields allowed.");
return false;
}
var newFieldDiv = $(document.createElement('div'))
.attr("id", 'FieldDiv' + counter);
newFieldDiv.after().html('<select name="add_project_service_' + counter + '" class="project_details_service" value="" required >' +
'while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}</select> ' +
'<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_' + counter + '\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"".$quantity."\" /> ' +
'<label>Value: </label><input type=\"text\" name=\"add_project_value_' + counter + '\" class=\"project_details_value\" placeholder=\"Value\" value=\"".$value."\" /><br>');
newFieldDiv.appendTo("#FieldGroup");
counter++;
});
$("#removeField").click(function () {
if(counter==2){
alert("No more fields to remove.");
return false;
}
counter--;
$("#FieldDiv" + counter).remove();
});
});
</script>
Inserting the while loop into the javascript doesn't work.
How can this be accomplished so when I add a field the options are listed and fields are populated?
javascript is exectued on client side while php interpreted on the server side.
Once you've send the page to the client, the only way to edit the page without reloading a new one is with javascript and ajax call (xmlhttprequest). The client doesn't use php neither download php page from the server.
You could do an ajax call to your page with jquery
$.ajax{
url: "mypage.php",
type: "GET",
dataType: "jsonp",
success: function( myObject ) {
console.dir( myObject );
}
}
// mypage.php
header('Content-type: application/json');
echo json_encode( $myObject );
// for you it will be
echo json_encode( $result->fetch() );