Reputation: 43
So I have a problem. I'm trying to insert into a database Posts made by users and I'd like to use Ajax to make it more dynamic and send input, select values and content in a div with its content editable, via jQuery. I'm using FormData to get all data in the form.
I have this form:
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Title">
<div id="content" class="content" contenteditable="true"></div>
<input type="text" name="tags" placeholder="Tags">
<input type="file" name="file">
<select>
<option value="0">Select...</option>
<option value="1">Option A</option>
<option value="2">Option B</option>
<option value="3">Option C</option>
</select>
<button name="insert" value="insert" class="button">Post</button>
</form>
jQuery/Ajax:
$(document).ready(function(){
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
var cont = $("#content").val();
formData.append("content", cont);
$.ajax({
url: 'iproddone.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data);
location.reload();
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
I recently added the line var cont = $("#content").val();
and formData.append("content", cont);
and I noticed php no longer marks an error when it tries to $_POST['content'];
but when I did not have those lines php marked an error.
PHP:
<?php
if (isset($_POST['insert'])) {
include_once('conn.php'); //connection file
$tt=$_POST['title'];
$cont=$_POST['content'];
$tags=$_POST['tags'];
$foo = $tt;
$foo = ucfirst($foo);
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'img/tmb_prod/' . $_FILES['file']['name']);
$photo=$_FILES['file']['name'];
}
echo "Image uploaded";
$connn=mysql_connect("localhost","root","")or die("Connection problems");
mysql_select_db("gtcomputer",$conn)or die("Error");
mysql_query("insert into posts(title,content,tags,photo)values('$foo','$cont','$tags','$photo')",$conn)or die("Error".mysql_error());
}
else{
header('Location: index.php');
}
?>
When I make a new post, in the posts table are inserted just the title, tags and file name.
Upvotes: 0
Views: 2437
Reputation: 43
Just added formData.append('content', $('#content').html());
and worked.
$(document).ready(function(){
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
formData.append('content', $('#content').html());
$.ajax({
url: 'iproddone.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data);
location.reload();
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Upvotes: 2