Getting value from contenteditable div - javascript

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());

Related

Submit button intermittently not submitting form information

So I've got this form for adding comments under a post. The methods utilized here are MYSQL(holds the submitted form data in a database) PHP(communicating with the database) and JavaScript, more specifically AJAX (for hooking up the submit button and handling events).
Typing in your comment into the form and pressing submit is supposed to print the comment onto the screen.
When I click submit, it doesn't print anything. Then, when I type another comment and click submit once more, it prints the contents of that comment. Other times, it successfully prints the contents of the comment instead of failing to submit.
I checked it out in inspect element and in the console log, whenever it misses, it still sends some blank <p> tags through with the class of the comment that should be submitted.
The PHP page for the comment form:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="Forums.css">
</head>
<body>
<?php
$result = mysqli_query($link, $displayPost); ?>
<?php $row = mysqli_fetch_assoc($result);?>
<p> <?php echo $row["title"];?> </p>
<br>
<p> <?php echo $row["body"];?> </p>
<form action="<?php echo $url ?>" method="post" id="form-group">
<div class="forum col-md-12">
<textarea type="text" style="overflow: auto; resize: none;" name="body" class="txtBody"></textarea>
<input type="submit" name="submit" class="btnCreate" style="margin-bottom: 4px;">
</div>
</form>
</body>
<script>
function refreshData() {
$.ajax({
type:'GET',
url: 'getcomments.php?id=<?php echo $id ?>',
dataType: 'html',
success: function(result){
console.log(result);
$('#comments').html(result);
}
});
}
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData
});
refreshData();
event.preventDefault();
});
});
</script>
<div id="comments"></div>
The PHP page for getting previously submitted comments and printing them on the screen
<?php
$link = mysqli_connect("localhost", "root", "WassPord64", "forum");
$id = $_GET["id"];
$displayPost = "SELECT * FROM comments WHERE post_id='$id'";
$link->query($displayPost);
$result = mysqli_query($link, $displayPost);
if (mysqli_num_rows($result) > 0) :
// output data of each row
while($row = mysqli_fetch_assoc($result)) :
$row = mysqli_fetch_assoc($result);?>
<p class="postBody"><?php echo $row['body'];?></p>
<?php endwhile; ?>
<?php endif; ?>
You are calling refreshData() when the Ajax is not done. You can make a callback function by using $.ajax.success
Try this:
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData,
success: function(){
refreshData();
}
});
event.preventDefault();
});
});

jQuery/Ajax POST with ContentEditable spans not working

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 }
});
});

insert image into database with ajax using formData

I'm having some difficulties with uploading an image from an html form. the form should be able to send the image name with other data to php page.
I used formData instead of serialized function, since it can't handle files data.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:"includes/widgets/insert.php",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
success: function (data) {
alert(data);
},
});
return false;
});
html form
<form id="insert_post" action="includes/widgets/insert.php" method="post" enctype="multipart/form-data" >
<div class="row">
<div class="medium-6 columns">
<label>First name
<input type="text" name="first_name" id="first_name" contenteditable>
</label>
</div>
<div class="medium-6 columns">
<label>Last name
<input type="text" name="last_name" id="last_name" contenteditable>
</label>
</div>
<div class="medium-12 columns">
<label>Last name
<input type="file" name="file" id="image" multiple contenteditable>
</label>
</div>
</div>
<button type="button" name="btn_add" id="btn_add" class="button btn btn-xs btn-success" >Submit</button>
</form>
php page
<?php
$connect = mysqli_connect("localhost", "root", "", "myaddboard");
echo $_POST['first_name'];
echo $_POST['last_name'];
echo $image = $_FILES['file']['name'];
echo $image_tmp = $_FILES['file']['tmp_name'];
/*
if(empty($image)){
echo 'error';
}
move_uploaded_file($image_tmp,"img/$image");
//$sql = "INSERT INTO posts(post_content, post_author) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
} else {
echo 'error';
}
*/
?>
The php form is just to test if the ajax send the data correctly.
When I click on the button I always get errors that the php variables is not defined
The errors i get each time I submit the form
undefined index: frist_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 4
undefined index: last_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 5
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 8
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 9
what should I do to make the ajax send the data to the php page ?
This won't work because of how your selector is created.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
In the above scenario, $(this)[0] is getting you the raw HTML interpretation of the button.
What you actually want is to change your button to a submit type, capture the form submit event, and then process your request.
button type="submit" <-- change
$(document).on('submit', '#insert_post', function(e){
e.preventDefault(); //stop default form submission
//do the rest of your stuff here
});
Now $(this)[0] is actually the form and not the button.

Popup message and ajax to jquery form

I create a form with PHP and jQuery, I add this in footer of my website, all I need is to display the form results in a popup in the main of my website not in the footer and make this to work without page refresh (with ajax). I add here my entire code:
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<?php
if(isset($_REQUEST['submit'])) {
$url = $_REQUEST['url'];
if(substr( $string_n, 0, 7 ) != "http://" && substr( $string_n, 0, 8 ) != "https://")
$url = "http://".$url;
if(stripos($url,"folder/")>0)
$content = file_get_contents($url);
else
$content = file_get_contents($url."/folder/");
if(preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : ".$result[1];
else
echo "Sorry cannot determine year";
}
?>
EDIT
dont forget to put jquery in top of the html page
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
Check below solution
//this will be your html file
<form id="form1" enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<script>
$(function() {
$('#form1').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(html) {
alert(html);
}
});
});
});
</script>
create a post.php file put your php code
<?php
if (isset($_REQUEST['submit']))
{
$url = $_REQUEST['url'];
if (substr($string_n, 0, 7) != "http://" && substr($string_n, 0, 8) != "https://")
$url = "http://" . $url;
if (stripos($url, "folder/") > 0)
$content = file_get_contents($url);
else
$content = file_get_contents($url . "/folder/");
if (preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : " . $result[1];
else
echo "Sorry cannot determine year";
}
?>
If you are only using the code provided, you are still missing some AJAX code. As you have used both the jQuery and JavaScript tags, I wasn't sure if you are using Vanilla or jQuery (my example uses jQuery).
My example will make an AJAX request when the user clicks the submit button. $your_url will need to be set to a file which contains your PHP code you specified in the question.
$('#my_button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
text: $('#some_text').val(),
},
url: "<?php echo $your_url; ?>",
success: function(data) {
console.log($data);
}
});
});
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text" / id="some_text">
<input type="submit" name="submit" value="Check" class="btn btn-primary" id="my_button" />
</form>
Your PHP will need to be changed so that it works correctly with this AJAX request. As mentioned in the comments, it seems like you do not fully understand how AJAX works, and how it communicates with PHP. I suggest the following documentation and tutorials:
AJAX documentation
AJAX beginners guide

how to change the html tag element when onclick to a input text, so the user can edit comment

I am actually trying to make comments and also edit option when the comment enters it will show in a 'div'through ajax.
<?php
$q="select * from discuss where rownum=1 order by id desc";
$s=oci_parse($conn, $q);
$r=oci_execute($s) or die(oci_error());
echo "<table border=1>";
while($m=oci_fetch_assoc($s))
{
echo "<tr style='background-color:red'><th style='float:left;color:white'>Name : ".$m['NAME']."</th><th style='float:right;color:white'>Date: "."".$m['DATE_TIME']."</th></tr>";
echo "<tr class='edit_option' style='width:1000px;height:10px;background- color:white'><div><td id='input_text' style='width:1000px;height:10px;background- color:white'>".$m['COMMENTS']."</div><div class='anchor_edit' id='anchor_id_edit'><span onclick=\"edit_text('".$m['COMMENTS']."')\">edit</span></div></td></tr>";
}
echo "</table>";
?>
<script>
function edit_text(edit_option){
alert(edit_option);
}
</script>
onclick the function value is coming to edit_text() function getting alert, here i am not getting how can iput logic for this comment.
when edit option is clicked the user has to get his/her comment in a input text 'value' so the user can edit comment.
onclick how can i do the edit comment, please anyone can help!!
This may be help to you
Here I take a sample array input data
PHP SCRIPT
<?php
$r=array(
array('COMMENT-ID'=>'1','NAME'=>'Comment1','COMMENTS'=>'Comment1Comment1Comment1Comment1','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'2','NAME'=>'Comment2','COMMENTS'=>'Comment2Comment2Comment2Comment2','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'3','NAME'=>'Comment3','COMMENTS'=>'Comment3Comment3Comment3Comment3','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'4','NAME'=>'Comment4','COMMENTS'=>'Comment4Comment4Comment4Comment4','DATE_TIME'=>'12547896321')
);
echo "<div>";
foreach($r as $m)
{ ?>
<div>
<div>
Name : <?php echo $m['NAME']; ?>
</div>
<div>
Date: <?php echo $m['DATE_TIME']; ?>
</div>
</div>
<div class="comment">
<div class="comment-text" id="comment<?php echo $m['COMMENT-ID']; ?>">
<?php echo $m['COMMENTS']; ?>
</div>
<div class="commentEditBtn">
Edit
</div>
<div class="editedText"></div>
<div class="commentInput" data-id="<?php echo $m['COMMENT-ID'] ?>">
<input type="text" name="comment" /><br/>
<button class="commentSubmit">Submit</button>
</div>
</div><br/>
<?php }
echo "</div>";
?>
jQuery
$(".commentEditBtn").on('click',function(){
$('.commentinput').hide();
var parentDiv = $(this).parent();
var commentText = parentDiv.find('.comment-text').html();
parentDiv.find('.commentInput input').val(commentText.trim());
parentDiv.find('.commentInput').show();
});
$(".commentInput > input").keypress(function(){
var commentData = $(this).val();
$(this).parent().parent().find('.editedText').html(commentData.trim()).show();
});
$(".commentInput .commentSubmit").on('click',function(){
var commentId = $(this).parent().attr('data-id');
var commentText = $(this).parent().find('input').val().trim();
$(this).parent().parent().find('.editedText').html('').hide();
$.ajax({
url: "AJAX_POST_URL",
type: "POST",
data: {
commentId: commentId,
commentText: commentText
},
dataType: 'json',
success: function (data) {
if (data.error == 'false') {
$('#comment' + commentId).html(commentText);
}
}
});
});
CSS
.commentInput{display: none;}
.editedText{display: none;}
Check out this jquery plugin: http://jsfiddle.net/2u89gnn8/1/
You can make, for example, an h1 editable when a user clicks a button:
$('h1').editable({
"enable": true,
"trigger": $('button')
});

Categories