I hate JavaScript/jQuery.... and, most days it hates me. Just when I think we're starting to build a rapport, I fall down a hole I can't find my way out of.
I'm trying to have ContentEditable spans POST changes to MySQL onBlur.
Here's my HTML/PHP:
<h4><strong>Number of Employees: </strong><span contenteditable="true" onBlur="saveToDatabase(this,'NumberOfEmployees','<?php echo $row["mysqlid"]; ?>')"><?php echo number_format($row['numberofemployees']); ?></span></h4>
Here's my jQuery:
function saveToDatabase(editableObj,column,id) {
var dataString = 'column='+column+'&editval='+editableObj.innerHTML+'&id='+id;
$.ajax({
url: "_updatelead.php",
type: "POST",
data: { dataString },
}
}
});
I can't find my error, but every attempt I make throws the same error:
Uncaught ReferenceError: saveToDatabase is not defined
at HTMLSpanElement.onblur (viewleaddetail.php?id=5658:225)
Any ideas how I can resolve this? It seems to be a simple answer, but I can't get it right. Thanks!
If you use jQuery why don't you try like this:
HTML
<h4><strong>Number of Employees: </strong>
<span contenteditable="true" class="emp_item">
<input type="hidden" value="NumberOfEmployees" name="column">
<input type="hidden" value="<?php echo number_format($row['numberofemployees']); ?>" name="editval">
<input type="hidden" value="<?php echo $row['mysqlid']; ?>" name="id">
<?php echo number_format($row['numberofemployees']); ?>
</span>
</h4>
javascript
$(document).on('blur', ".emp_item", function () {
var dataString = $(this).find(":input").serialize();
$.ajax({
url: "_updatelead.php",
type: "POST",
data: { dataString }
});
});
Related
I have a PHP file which SELECT's all from the row found based on an SQL query. When I put the echo in a div, I get all information, but when I try to echo it into an input box in a form, it does not shows.
What am I doing wrong?
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
DO_CUSTEDIT.PHP
$custName = $_POST['custName'];
$query = "SELECT * FROM `CustDB` WHERE CustName LIKE '%$custName%'";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
$custID = $row['CustID'];
......;
}
if (!$result) {
echo $db->lastErrorMsg();
$db->close();
exit;
} else {
echo $custID;
echo ......;
$db->close();
exit;
}
EDITCUST.PHP / Javascipt
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
if (strMessage == "Customer updated successfully") {
$("#message").text(strMessage);
$("#neweditform").get(0).reset();
} else {
$("#message").text(strMessage);
}
}
});
});
});
</script>
EDITCUST.PHP / HTML
<form id="editcustform" name="editcustform" action="" method="post">
<div class="row">
<div class="column-half" style="background-color:#fff">
<table>
<tr>
<td>
<a>Customer ID</a>
</td>
<td>
<div class="inputb">
<input type="text" name="custID" value="<?php echo (isset($custID)) ? $custID: ''; ?>" readonly/>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<table style="table-layout:fixed">
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="subeditcust" type="submit" class="mainbtn">Create</button>
</td>
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="reseteditcust" type="reset" class="mainbtn">Reset</button>
</td>
</table>
</div>
</form>
<input type="text" name="custID" value="<?php echo (isset($custID) ? $custID: ''); ?>" readonly/>
Replace this line with yours it will work. IA
It seems you have two different files, right? DO_CUSTEDIT.PHP and EDITCUST.PHP
The variables are being created on DO_CUSTEDIT.PHP and the when you are creating the HTML code those variables ($custID) are not setted.
Is one file including or requiring the other?
EDITCUST.PHP is your first page from you are submitting form to DO_CUSTEDIT.PHP
When you land on EDITCUST.PHP variable $custID is not created
When the form is submitted through ajax, the ajax returns the data inform of object or array depending on how you are echoing the data from DO_CUSTEDIT.PHP
I would recommend to use json_encode() php function to return inform of array
To debug the value by logging the data in console (though function console.log())
After returning the value from ajax, you have to populate the value in form through jquery something like $(input[name="custID"]).val( data.custID )
I managed to figure it out!
DO_CUSTEDIT.php / PHP
$results = array($custID, $custName);
echo json_encode($results, JSON_PRETTY_PRINT);
EDITCUST.php / HTML
<input type="text" id="custID" name="custID" value="" readonly/>
<input type="text" id="custName" name="custName" value="" readonly/>
EDITCUST.php / JS
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: 'json',
success: function(data){
document.getElementById('custID').value = data[0];
document.getElementById('custName').value = data[1];
}
});
});
});
</script>
I'm having issues with creating multiple unique datepicker instances within one div and then submitting the dates in a form.
My issue is that my div currently has multiple array elements building this form:
<?php foreach($expiredPages as $expiredPage): ?>
<form id="updateTime_<?php echo $expiredPage['id']?>" class="updateTime" method="POST">
<input type="hidden" name="currentPageID" value="<?php echo $expiredPage['id']?>">
<div class="datepick input-group date" id="datetimepicker_<?php echo $expiredPage['id']?>" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" name="datePicker<?php echo $expiredPage['id']?>" />
<span class="input-group-addon" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" data-toggle="datetimepicker">
<span class="fa fa-calendar"></span>
</span>
<input type="submit" name="Extend Date" class="extendDate">
</form>
<?php endforeach; ?>
WHich means I have 3 forms in the div, each with its own datepicker and submit button. I've fixed this to make sure each datepicker works independently, but I can't figure out how to uniquely pass my two inputs to the PHP.
I'm getting errors of undefined index for both currentPageID and datePicker
The JS:
<script type="text/javascript">
$(".extendDate").click(function(){
event.preventDefault();
var string = $('.updateTime').serialize();
console.log(string);
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "extendTime.php",
data: string,
dataType: 'json',
cache: false,
success: function(response){
location.reload();
}
});
});
</script>
extendTime.php
$pageID = $_POST['currentPageID'];
$dtPick = 'datePicker' . $pageID;
$newTime = $_POST[$dtPick];
$newEndTime = DateTime::createFromFormat('m/d/Y h:i A', $newTime);
$convertedDateTime = $newEndTime->format('Y-m-d H:i:s');
$extendExpiration = "
UPDATE pages
SET end_time = '$convertedDateTime'
WHERE id = '$pageID';
";
if($mysqlConn->query($extendExpiration)=== TRUE){
echo "SUCCESS";
}else{
echo "Could not extend Time";
}
Regarding your php, you don't have post key called datePicker...
$_POST['datePicker'];
doesn't exists...
you add to your input's name an id:
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" name="datePicker<?php echo $expiredPage['id']?>" />
A simple fix should be something like this :
$dtpick = 'datePicker' . $pageID;
$newTime = $_POST[$dtpick];
I am making a comment system where a user can comment something to a post and then other users can reply to that comment. I have made a function to comment which works perfectly. I also wanted a similar function to work for that reply to comment part so I copied the same function and made some changes to the code like variable names etc. But its not working. When I write a reply and press enter it takes me to a new line rather than submitting. Please help me.
// COMMENT UPDATE (WORKING)
$(document).on('keydown', '.commentarea', function(event) {
var comtt = $(".commentarea").val();
if(comtt!=''){
if(event.keyCode == 13 && !event.shiftKey) {
var id = $(this).attr('id');
var status_id = id.replace("postcomment_", "");
createComment(status_id);
event.preventDefault();
}
}
});
function createComment(status_id){
var comment = $('#postcomment_'+status_id).val();
$.ajax({
url: "post-comment.php",type: "POST",
data: {comment : comment, statsid : status_id},
success: function (data) {
$("#showbox_"+status_id).append(data);
},
error: function () {
alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
},
complete: function(xhr) {
$('#postcomment_'+status_id).val('');
}
})
}
// REPLY TO COMMENT (SAME FUNCTION BUT NOT WORKING)
$(document).on('keydown', '.replyarea', function(event) {
var comtr = $(".replyarea").val();
if(comtr!=''){
if(event.keyCode == 13 && !event.shiftKey) {
var rid = $(this).attr('id');
var commentId = rid.replace("replycomment_", "");
createReply(commentId);
event.preventDefault();
}
}
});
function createReply(commentId){
var creply = $('#replycomment_'+status_id).val();
$.ajax({
url: "post-replies.php",type: "POST",
data: {creply : creply, cmtid : commentId},
success: function (data) {
$("#showreply_"+commentId).append(data);
},
error: function () {
alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
},
complete: function(xhr) {
$('#replycomment_'+commentId).val('');
}
})
}
PHP Part:
<?php while($get_stf = $get_stq->fetch()){ extract($get_stf); // fetch posts ?>
<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); // fetch comments?>
<!-- Reply to comments form -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width" id="cmt_form_id_<?php echo $cmt_id; ?>">
<input type="hidden" name="comment_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id; ?>" />
<textarea name="reply" placeholder="Give a reply..." class="reply-comment-field replyarea" id="replycomment_<?php echo $cmt_id; ?>"></textarea>
</form>
<!-- End Reply to comments form -->
<?php } ?>
<!-- Comment form -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width" id="cmt_form_id_<?php echo $cmt_id; ?>">
<input type="hidden" name="comment_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id; ?>" />
<textarea name="reply" placeholder="Give a reply..." class="reply-comment-field replyarea" id="replycomment_<?php echo $cmt_id; ?>"></textarea>
</form>
<!-- End Comment form -->
<?php } ?>
Both functions are same. But one being used for COMMENTS is working perfectly whereas the one used for REPLY TO COMMENTS is not working. It should submit the form and insert the data when I press enter in REPLY TO COMMENTS form after writing some text just like FACEBOOK. Please help.
your comment is broken the code:
Change this:
<!-- Reply to comments form -- >
for this:
<!-- Reply to comments form -->
and update.
For example, there is such a JS-code:
function openAlbum() {
$("#tracks").html('Some text...');
var uid = $("#uid").val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
}); }
And this html/php-code that is displayed in a cycle:
for ($i = 0; $i < count($searchAlbum); $i++) {
echo '<div id="cover"><form action=""><input type="hidden" id="uid" value="'.str_replace('https://example.com/', '', $searchAlbum[$i]->href).'"/><img src="'.$searchAlbum[$i]->images[1]->url.'"/><br><br><span>'.$searchAlbum[$i]->name.'</span><input type="submit" style="position: absolute;;left: -99999px;" /></form></div>';
}
Problem: currently by clicking grabs only the first input value on the page with id="uid".
How do I put a JS var uid value from the div, which clicked a link?
P.S. Sorry for my bad english.
I'm going to change the way you kinda do this a bit...
<?php
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div class="cover">
<form action="">
<input type="hidden" class="uid" value="<?php echo str_replace('https://example.com/', '', $searchAlbum[$i]->href); ?>"/>
<img src="<?php echo $searchAlbum[$i]->images[1]->url; ?>"/>
<span><?php echo $searchAlbum[$i]->name; ?></span>
<input type="submit" style="position: absolute;left: -99999px;" />
</form>
</div>';
<?php
}
?>
Script:
$(document).on('click','.cover img',openAlbum);
function openAlbum() {
$("#tracks").html('Some text...'); var uid = $(this).parent().find('.uid').val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
//$("#results").empty();
//$("#results").append(html);
$("#results").html(html);
}
});
}
This should cover everything. I switched all ids to classes and changed how you execute your jQuery.
Thank you all for your help!
As a result, I will be able to solve the problem.
JS-code:
function openAlbum(uid)
{
$("#results").html('Some text...');
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
});
}
HTML-code:
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div id="cover"><a href="#" onclick='openAlbum("<? echo $searchAlbum[$i]->id; ?>");'><img src="<? echo $searchAlbum[$i]->images[1]->url; ?>"/></a><br><br><span><? echo $searchAlbum[$i]->name; ?></span></div>
<?
}
Since id in HTML must be unique, it is taking only the first element's value. Make the ids unique or use class attribute as Cayce K has answered.
Up to this point, I've been using a textarea as the main input for a form. I've changed it to use a contenteditable div because I wanted to allow some formatting.
Previously, when I had the textarea, the form submitted fine with Ajax and PHP. Now that I've changed it to use a contenteditable div, it doesn't work anymore and I can't tell why.
HTML:
<form>
<div name="post_field" class="new-post post-field" placeholder="Make a comment..." contenteditable="true"></div>
<input name="user_id" type="hidden" <?php echo 'value="' . $user_info[0] . '"' ?>>
<input name="display_name" type="hidden" <?php echo 'value="' . $user_info[2] . '"' ?>>
<ul class="btn-toggle format-post">
<button onclick="bold()"><i class="fa-icon-bold"></i></button>
<button onclick="italic()"><i class="fa-icon-italic"></i></button>
</ul>
<div class="post-buttons btn-toggle">
<button class="btn-new pull-right" type="submit">Submit</button>
</div>
</form>
JQuery Ajax:
$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'php/post.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
}
});
});
});
PHP (post.php): Just your typical checks and echo a message back. This is just a snippet of the code.
<?php
$user_id = $_POST["user_id"];
$display_name = $_POST["display_name"];
$post_content = $_POST["post_field"];
$array = array('message' => $post_content);
echo json_encode($array);
?>
For some reason, it's not sending back the post content anymore ever since I added the contenteditable div.
Please help!
The contents of the div are not serialized. You would have to add them on your own.
var data = $(this).serialize();
data += "post_field=" + encodeURIComponent($("[name=post_field]").html());