Save a "click to edit" with ajax - javascript

I'm making a simple list application and the items should be easy to edit (just clicking on them). It works fine, but I still have a problem at saving the changes to the database, for some reason it doesn't happen. I'm sure it's a code problem, but I haven't been able to find it.
List Page
<input type="hidden" id="hidden" id="hidden" value="">
<ul id="lista">
<?php
$IDllista = 1;
$selectitems = mysql_query ("SELECT * FROM items WHERE IDllista=".$IDllista." ORDER BY posicio ASC") or die (mysql_error());
while ($row = mysql_fetch_array($selectitems))
{
echo'<li class="item" id="';
echo $row['IDitem'];
echo '"><span class="edit" id="span-';
echo $row['IDitem'];
echo '" data="';
echo $row['Text'];
echo '">';
echo $row['Text'];
echo'</span></li>';
}
?>
</ul>
JavaScript
//Call the edit function
$(".edit").live("click", function () {
// Get the id name
var iditem = $(this).parent().attr("id");
var element = this;
var id = element.id;
//New text box with id and name according to position
var textboxs = '<input type="text" name="text' + id + '" id="text' + id + '" class="textbox" >'
//Place textbox in page to enter value
$('#'+id).html('').html(textboxs);
//Set value of hidden field
$('#hidden').val(id);
//Focus the newly created textbox
$('#text'+id).focus();
});
// Even to save the data - When user clicks out side of textbox
$('.edit').focusout(function () {
//Get the value of hidden field (Currently editing field)
var field = $('#hidden').val();
//get the value on text box (New value entred by user)
var value = $('#text'+field).val();
//Update if the value in not empty
if(value != '') {
//Post to a php file - To update at backend
//Set the data attribue with new value
$(this).html(value).attr('data', value);
$.ajax({
type: 'POST',
data: {id: iditem},
url: 'editartext.php'
});
}
// If user exits without making any changes
$(".edit").each(function () {
//set the default value
$(this).text($(this).attr('data'));
});
});
Edit Page
<?php
include_once "../connect.php";
$IDitem = $_POST['id'];
$noutext = "hola";
$actualitza = mysql_query ("UPDATE items SET Text = ".$noutext." WHERE IDitem = ".$IDitem." ");
?>

Quote problem i think. You can use query with single quote like;
"mysql_query("UPDATE items SET Text ='$noutext' WHERE IDitem ='$IDitem'");

Related

I want to add html text filed value in other text filed value will changed

I want to set PHP variable in HTML text field during other text field value will be changed.
<input type="text" class="form-control" name="refrence" id="refrence" onkeydown="myFunction(event)"
placeholder="Reference" autocomplete="off">
javaScript
<script>
function myFunction(event) {
var x = event.keyCode;
if (x == 17) {
var name = document.getElementById("companyName");
var address = document.getElementById("address");
alert("df");
name.value = "<?php echo $invoiceValues['order_receiver_name']; ?
>;
address.value = "<?php echo invoiceValues['order_receiver_address']; ?>;
}
}
</script>
php code
public function getrefer() {
$sqlQuery = "SELECT * FROM " . $this->invoicevendortable
. " WHERE reference = '" . $_SESSION['refrence'] . "'";
return $this->getData($sqlQuery);
}
You need to read the current value via JS; PHP only gets parsed on page load!
var refDomElement = document.querySelector( '#reference' )
, useDomElement = document.querySelector( '#companySomething' )
useDomElement.value = refDomElement.value

how to set varialble

In my DB i have created a table named "coursePlaces" in which i have 7 columns and a number of rows.
Loading the php-file course.php I connects to the db and selects data from the table "coursePlaces" using it to echo a number of buttons with different id and value each:
<?php
/* CONNECTION TO DB */
require 'includes/dbh.inc.php';
/* ACCESS COURSE AND GRADE VAR FROM URL WITH GET */
$course = $_GET['course'];
$grade = $_GET['grade'];
/* SELECTS DATA FROM TABLE AND ECHOES BUTTONS WITH DIFFERENT ID AND VALUE DEPENDING ON TABLE CONTENT */
$sql = "SELECT * FROM coursePlaces WHERE grade='$grade' AND course='$course'";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '">';
}
/* CONVERTS VAR TO USE IN JQUERY SCRIPT */
echo '<script>';
echo 'var grade = ' . json_encode($grade) . ';';
echo 'var course = ' . json_encode($course) . ';';
echo '</script>';
?>
<script src="includes/global.inc.js"></script>
<!-- DIV TO ECHO OUTPUT FROM PLACE.INC.PHP -->
<div class="selectedPlace" id="selectedPlace"></div>
When clicking one of the buttons the value should be send to the file "global.inc.js" In which i have placed a script used to listen for clicks:
$('input#$row['placeName']').on('click', function() {
var place = $('input#place-$row['placeName']').val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
My problem is, that I don't know what the name of the button id is - since it is created from a varchar in a database table. How do i bring this information over into my .js file, so the script posts individual value from button no matter what button the user presses on the courses.php.
Use jQuery to set your variable with Ajax ( method POST ).
Try to change code as below:
$('input[type="submit"]').on('click', function() {
var place = $(this).val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
set on click attribute when you echo your inputs:
echo sprintf('<input type="submit" id="place-%s" value="%s" onclick="yourfunction("%s", "%s", "%s") >', $row['placeName'], $row['placeName'], $grade, $course);
and separate this yourfunction function:
function yourfunction(place, grade, course){
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
You should use a generic click handler instead of the one you are using.
If all button have one common class you can listen to the click of all.
Add class inputBtn to following:
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '" class="inputBtn">';
Change
$('input#$row['placeName']').on('click', function() {
to
$('.inputBtn').on('click', function() {
var btnID = $(this).prop('id');
var spltID = btnID.split('-'); //split from the - & spltID[1] will contain the part that you required.
}
This code is written like just for the sake of clarity. It is possible to make it more optimal like split() function can be called on btnID to reduce code line.

how to delete a comment in javascript and ajax?

I am trying to write a simple delete function for a comment system that i am working on. the comments are stored in a database where each comment has a cid that is incremented automatically. i have noticed that the user can only delete the first comment he/she has written but when a the user writes two comments and presses delete on the second one, the comment can not be deleted, can someone help fix this. here is my code. thank you for your help.
this is my meatballs.php file where i have the comments loaded.
<div class = "page" id = "comments">
<p class = "style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type = 'hidden' id = 'uid' value = '".$_SESSION['u_uid']."'>
<input type = 'hidden' id = 'date' value = '".date('Y-m-d H:i:s')."'>
<textarea id = 'message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'meatballsSubmit'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML=
$("#comments").load("getComments.php");
});
});
</script>
as for getCommetns.php file which retrieves the comments from the database.
<?php
include 'includes/dbh.inc.php';
session_start();
$sql = "SELECT * FROM meatballscomments";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class = 'comment-box'>";
echo '<span class = "user">'.$row['user_uid'].'</span><br><br>';
echo "<p>".htmlspecialchars($row['message'])."</p>";
echo '<span class = "datef">'.$row['date'].'</span>';
if(isset($_SESSION['u_id']) && $_SESSION['u_uid'] == $row['user_uid']){
echo "<br>";
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' id = 'meatballsDelete'>Delete</button>";
}
echo "</div><hr>";
}
?>
<script>
$(document).ready(function(){
$("#meatballsDelete").click(function(){
var cid = $("#cid").val();
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid
}});
alert("Your comment has been deleted");
});
});
</script>
the deleteComment.php file that i have is very short and here it is.
<?php
include 'includes/dbh.inc.php';
$cid = $_POST['cid'];
$sql = "DELETE FROM meatballscomments WHERE cid = '$cid'";
$result = mysqli_query($conn, $sql);
You're assigning the same id on multiple html elements & using val() on the result of the jQuery selector which returns the first element with the id of cid. From jQuery:
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM.
Therefore there's no guarantee that it automatically grabs the right element for you, when you're using the same id multiple times.
The quickest fix would be to change #meatballsDelete to .meatballsDelete, and add the meatballsDelete class to your button, that way clicking will register on both buttons. Also add the $row['cid'] value as attribute to the button and then grab that with $(this).attr("myAttribute") in the function in click, which will always guarantee that the id is returned which belongs to the button.
Like #u_mulder says in the comments, you're also using an id to register the click, which will also bind to the first element with that id.
A reasonably easy way to modify your code to resolve this issue would be to get rid of the hidden cid input and add the cid value as a data value to your button. You also need to change the button to have a class meatballsDelete rather than an id, since id values must be unique. So change this:
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' id = 'meatballsDelete'>Delete</button>";
To
echo "<button class = 'btn meatballsDelete' type = 'submit' data-cid = '{$row['cid']}'>Delete</button>";
and then modify your javascript to add the click handler to items of class meatballsDelete (instead of id) and retrieve the cid value from the data-cid attribute:
$(document).ready(function(){
$(".meatballsDelete").click(function(){
var cid = $(this).data('cid');
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid
}});
alert("Your comment has been deleted");
});
});
if(isset($_SESSION['u_id']) && $_SESSION['u_uid'] == $row['user_uid']){
echo "<br>";
echo "<p id='demo'></p>";
$commentId = $row['cid'];
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' onclick= 'deleteFunction($commentId, 1)'>Delete</button>";
}
and the script i used
<script>
function deleteFunction(cid, page){
//document.getElementById("demo").innerHTML = cid + " ----"+ page;
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid,
"page": page}
});
alert("Your comment has been deleted!");
}
</script>

How can I get the text from dynamic textbox by dynamic button in HTML and ajax

I'm trying to get data from a database and update the records one by one,
I had made a table I created a text input field and button which will build dynamically with the records, the text input field will have the previous record, then I should change that and submit it. the problem is when I try to edit and submit which I changed, it gives the first text input value for all the button
this is my Javascript code:
$("body").delegate("a","click",function(event){
//$("#category_editing").click(function(){
event.preventDefault();
var cat_name = $("#new_cat_name").val();
//var cat_name = $(this).attr('new_cat_name');
var cat_id = $(this).attr('cat_id');
console.log('starting ajax');
alert(cat_name);
$.ajax({
url : "update_cat.php",
method: "POST",
data : {cat_id:cat_id,cat_name:cat_name},
success : function(data){
alert(data);
}
});
});
and this is my php and html code:
$category_query = "SELECT * FROM `CATEGORIES`";
$run_query = mysqli_query($connect,$category_query);
echo "
<div class='nav nav-pills nav-stacked'>
<li class='active'><a href='#'
>Categories</a></li>";
if(mysqli_num_rows($run_query)>0){
while
($row = mysqli_fetch_array($run_query))
{
$CATEGORY_ID = $row['CATEGORY_ID'];
$CATEGORY_NAME = $row['CATEGORY_NAME'];
$CATEGORY_DESC = $row['CATEGORY_DESC'];
$CATEGORY_IMAGE_PATH = $row['CATEGORY_IMAGE_PATH'];
echo "
<li><a class='category_editing' cat_id='$CATEGORY_ID'><input type='text' class='form-control' id='new_cat_name' value='$CATEGORY_NAME'><a href='#' class='category_editing btn btn-warning' cat_id='$CATEGORY_ID' cat_name='$CATEGORY_NAME'>Submit</a></a></li>";
}
}
//}
?>
That's the problem:
var cat_name = $("#new_cat_name").val();
You should access the changed input by the id of the anchor tag or something like this. You have to select a specific input. You could render it this way:
cat_id='$CATEGORY_ID'><input type='text' class='form-control' id='input_$CATEGORY_ID'
And try to access the input by concatenation of the string 'input' and the id of the anchor text in the handler context.

Passing form data through js/jquery

I have the following code which when div clicked converts the div into a dropdown - works perfectly, however, I have "on change" set to submit the form and it passes all data apart from the option selected in the dropdown/select element, any ideas?
This is the js
<script type="text/javascript">
$(document).ready(function(){
var choices = "<select class='choices_dropdown' name='list_name' onchange=\"this.form.submit();\">"+"<option value='My list'>My list</option>"
<?php
// this loads the select element
$wishes4 = mysql_query("select event_id from user_events where user_id = '$userfromcookie'",$db);
while ($databack444 = mysql_fetch_array($wishes4)) { // cc
$wishes5 = mysql_query("select event from events_master where event_id = '$databack444[event_id]'",$db);
$databack555 = mysql_fetch_array($wishes5);
echo "+\"<option value='".$databack555[event]."'>".$databack555[event]."</option>\"";
} // close CC
?>
+"</select>";
$(".update").click(function() {
var $this = $(this),
currentChoice;
// don't continue if there's already a select in this cell
if ($this.find("select").length != 0)
return;
currentChoice = $this.html();
var $choices = $(choices);
$this.empty().append($choices);
$choices.val(currentChoice);
});
$(document).on("change", ".choices_dropdown", function() {
var $this = $(this);
$this.parent().html($this.val());
$('#event_update').submit(); /* this submits the form */
return false;
});
});
</script>
and the html which displays the div is:
echo '<td class="update">
<form action=/list2.html method=post id=event_update>'
.$databack33[list_name].
'<input type="hidden" name="wishlist_id" value='
.$databack33[list_id].
'>
<input type="hidden" name="action" value="update_list">
</form></td>';

Categories