I'm trying to send data through AJAX to a PHP file to then upload to my database using SQL. I've already altered my table to allow UTF-8 to be inserted. When I insert using a form it works fine but when using AJAX to send data it won't send it.
For example, I'm trying to send some text and an emoji to a PHP file which then uploads to my database.
I've already got <meta charset="utf-8">
at the top of my page and even added header("Content-Type: text/html; charset=utf-8");
to the page and PHP file as I've seen some other posts mention that but it hasn't worked.
Here is the AJAX function:
$detail = $('#post').text(); //Gets text from div
$.ajax({
url: 'edit.php',
type: 'post',
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
data: {detail: $detail},
datatype: 'html',
success: function() {
console.log($detail);
}});
The $detail
is simply the value from a div and all the edit file simply does is UPDATE
the table.
When I console.log
the data it comes back with text and an emoji but it doesn't insert into my database.
While writing this, I noticed that adding 'application/x-www-form-urlencoded;charset=utf-8'
stops the whole process from working but I'm not sure why.
Backend Code for those that asked:
<?php
$host = "hostname";
$user = "user";
$password = "pass";
$db_name = "database";
$tbl_name = "table";
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$detail = $_POST['detail'];
// Add your validation and save data to database
if(strlen($detail) <= 5000) {
$stmt = mysqli_stmt_init($conn);
$sql = "UPDATE $tbl_name SET detail = ?";
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $detail);
mysqli_stmt_execute($stmt);
}
mysqli_stmt_close($stmt);
}
}
?>
NOTE: This works when I pass it through a form but via AJAX when adding an emoji such as it doesn't work.