Output from database use toggle to edit data - javascript

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...

Related

How do I add an onClick event to a link generated on PHP?

I am trying to add an onclick event on a link in a PHP file.
$body2 .= '<td class="sampling-list-td download-link">' . '<a ' . 'class="sampling-list-download" ' . 'href="#" ' . 'data-id="' . $assetId . '" ' . 'data-type="' . $assetType . '" ' . 'data-event="LogFileElaboration" ' . 'data-file="' . $fileName . '" ' . 'data-enterprise="' . $provisionedBuId . '"' . '>'
. '<i class="glyphicon glyphicon-download-alt" style="color: rgb(109, 110, 113); zoom: 1.3;"></i>'
. '</a>' . '</td>';
This is what I'm trying to do:
$body2 .= '<td class="sampling-list-download" ' . 'onClick="ga('send', 'event', { eventCategory: 'download', eventAction: 'click', eventLabel: 'Files Download'});" ' . 'href="#" ' . 'data-id="' . $assetId . '" ' . 'data-type="' . $assetType . '" ' . 'data-event="LogFileElaboration" ' . 'data-file="' . $fileName . '" ' . 'data-enterprise="' . $provisionedBuId . '"' . '>'
. '<i class="glyphicon glyphicon-download-alt" style="color: rgb(109, 110, 113); zoom: 1.3;"></i>'
. '</a>' . '</td>';
But I am getting the following errors:
ParseError: syntax error, unexpected 'send' (T_STRING)
I don't know what i'm doing wrong? I'm trying to add the event tracking code for google analytics T_T
the quote in 'send' ends the string you started right before onClick. When the string is terminated it will interpret as PHP again and send is not a valid keyword here.
To prevent this you can escape the ' like this: 'onClick="ga(\'send\', \'event\', { e...
Its a Quote problem .change like this add\ before ' in onclick.Otherwise each time ' .is break the string and after the text are execute like php statement or variable .If the php send is invalid one so you got error
$body2 .= '<td class="sampling-list-download" ' . 'onClick="ga(\'send\', \'event\', { eventCategory: \'download\', eventAction: \'click\', eventLabel: \'Files Download\'});" ' . 'href="#" ' . 'data-id="' . $assetId . '" ' . 'data-type="' . $assetType . '" ' . 'data-event="LogFileElaboration" ' . 'data-file="' . $fileName . '" ' . 'data-enterprise="' . $provisionedBuId . '"' . '>'
. '<i class="glyphicon glyphicon-download-alt" style="color: rgb(109, 110, 113); zoom: 1.3;"></i>'
. '</a>' . '</td>';

Uncaught Syntax error on onClick function javascript

I need to output some strings in the onclick anchor function.I have used proper escaping but anyhow its returning error.
My code is:
$output .= '<a title="Minus this" href="#" onclick = removefromCart("' . $item . '", "' . $nonce . '", ' . $deductQty . ');></a>';
And also used this :
$output .= '<a title="Minus this" href="#" onclick = "removefromCart("' . $item . '", "' . $nonce . '", ' . $deductQty . ')"></a>';
But in both cases there is Uncaught SyntaxError: Unexpected token }
The quotes is totally wrong. Do this way, using the first one:
$output .= '<a title="Minus this" href="#" onclick=\'removefromCart("' . $item . '", "' . $nonce . '", ' . $deductQty . ');\'></a>';
See the 's I have added and removed spaces? And please, next time, don't mingle both PHP and JavaScript. It's confusingly dangerous.
See also:
Are single quotes allowed in HTML?
Is there a better way to write this php code?
You should use single quotations to represent string in HTML element
$output .= '<a title="Minus this" href="#" onclick = "removefromCart(\'' . $item . '\', \'' . $nonce . '\', ' . $deductQty . ')"></a>';
For greater than or equal to PHP5
$output .= '<a title="Minus this" href="#" onclick = removefromCart($item,$nonce,$deductQty);></a>';
For Less than PHP5 try it
$output .= '<a title="Minus this" href="#" onclick = removefromCart(' . $item . ',' . $nonce . ', ' . $deductQty . ');></a>';

How to change database values with dynamically created buttons in PHP

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.

Iterating over different divs in Javascript and passing arguments to a script

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
}

Rate image system

So I've created this function where you upload an image to the server together with some information.
The text information is saved to a database while the image is saved to a folder.
Then I echo out the image together with the information that was stored in the database.
But I want to enchance it some by adding a rating system.
The rating system that I have created store the stastistics inside a txt-file.
What I need help with is to swap the saving with statistics from the txt-file and store it inside the database instead.
This is how I echo out the image, along with the information and star function:
<?php
//Sortering
$order = "";
if(isset($_GET['order'])){
if($_GET['order'] == "date"){
$order = " ORDER BY date DESC";
}
}
if(isset($_GET['order'])){
if($_GET['order'] == "uppladdare"){
$order = " ORDER BY uppladdare";
}
}
//Database connection
$dbcon = mysqli_connect("");
$selectall = "SELECT * FROM mountains $order";
$result = mysqli_query($dbcon, $selectall);
while($row = mysqli_fetch_array($result)){
$information = ' Titel: ' . $row['titel'] . ' Uppladdare: ' . $row['uppladdare'] . ' Filnamn: ' . $row['filname'] . ' History: ' .$row['History'] . ' Datum: ' . $row['date'];
//Print out correct information to the uploaded image
echo "<br>";
echo "Title: " . $row['titel'] . "<br>";
echo "Uploader: " . $row['uppladdare'] . "<br>";
echo "Imagename: " . $row['filname'] . "<br>";
echo "History: " . $row['History'] . "<br>";
echo "Date: " . $row['date'] . "<br>";
echo "Image:";
echo "<br>";
echo "<form name='rating' id='rating'>
<div id='rating-area' class='shadow'>
<img src='stjärna.png' id='thumb1' data-value='1' />
<img src='stjärna.png' id='thumb2' data-value='2' />
<img src='stjärna.png' id='thumb3' data-value='3' />
<img src='stjärna.png' id='thumb4' data-value='4' />
<img src='stjärna.png' id='thumb5' data-value='5' />
</div>
</form>";
?>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ rating : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
<script>
$(document).ready(function(){
setInterval(function(){
$('#resultat').load('ajax.php');
},500);
});
</script>
<?php
$original = $row['filname'];
echo "<a class='fancybox' rel='massoravbilder' href='bilder/$original'> <img src='bilder/thumb_" . $row['filname'] . "' alt='$information' /></a>" . "<br>";
}
?>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ rating : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
Im still quite a beginner so I would appreciate if anyone could show me an easy way to solve this. Prefer it to be simple, like without restrictions when it comes to the vote.
Just upload each rate-onclick and echo the average of all the votes right beneath the stars.
Notes: The rating system works fine when just using textfile. ajax.php is the calculation master behind the function. And post.php sends the rating statistics to the tex-file.
You should do something like this. I don't know if fields exist but it's the way to follow. I hope it's give you an idea.
In your form
//...
while($row = mysqli_fetch_array($result)){
$information = ' Titel: ' . $row['titel'] . ' Uppladdare: ' . $row['uppladdare'] . ' Filnamn: ' . $row['filname'] . ' History: ' .$row['History'] . ' Datum: ' . $row['date'];
//Print out correct information to the uploaded image
echo "<br>";
echo "Title: " . $row['titel'] . "<br>";
echo "Uploader: " . $row['uppladdare'] . "<br>";
echo "Imagename: " . $row['filname'] . "<br>";
echo "History: " . $row['History'] . "<br>";
echo "Date: " . $row['date'] . "<br>";
echo "Image:";
echo "<br>";
// Add the input with image id value (I suppose it exist)
echo "<form name='rating' id='rating'>
<div id='rating-area' class='shadow'>
<input type='hidden' name= 'image_id' value = $row[image_id]>
<img src='stjärna.png' id='thumb1' data-value='1' />
<img src='stjärna.png' id='thumb2' data-value='2' />
<img src='stjärna.png' id='thumb3' data-value='3' />
<img src='stjärna.png' id='thumb4' data-value='4' />
<img src='stjärna.png' id='thumb5' data-value='5' />
</div>
</form>";
Ajax
<script>
jQuery('div#rating-area img').click(function(e){
// serialize the form and retrieve all value in PHP with $_POST['theNameOfInput']
jQuery.post('post.php',{ form : $(this).serialize() },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
post.php
<?php
$imageId = (int) $_POST['image_id'];
// ... Your database treatments
$sql = "UPDATE image SET image_rating = image_rating + 1 WHERE image_id = $imageId";
//... Your code

Categories

Resources