Search code examples
javascriptphpjquery.htaccesshttp-status-code-406

406 response with a $.post request jQuery to external PHP


I'm trying to post large amounts of text via $.post in jQuery and getting a 406 response. It works fine under around 300 characters. Below is my code:

index.php

html

<form class="formss" action="index.php">
    <textarea id="submittts" name="tts" spellcheck="false"></textarea>
</form>

jQuery

$('.save').click(function() {
    $.post('store.php', $('.formss').serialize())
});

store.php

<?php
$tts = $_POST['tts'];
$texttostore = $tts;

$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "notes";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO notes (code)
VALUES ('$texttostore')";

if ($conn->query($sql) === TRUE) {
    echo stripslashes(str_replace('\r\n',PHP_EOL,$texttostore));
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

.htaccess

<IfModule mod_security.c>
SecFilterCheckURLEncoding Off
</IfModule>

Getting the following response: https://i.sstatic.net/MUZpX.png

Have also tried with a local form submit, but it would also bring up a bad request.

Note: All whitespace and formatting is preserved when stored, and that is intentional

If anyone could help me out that would be great, thanks :)


Solution

  • Web browsers make a request for information from the server. When this happens, it sends an Accept header. This tells the server in what formats the browser can accept the data. If the server cannot send data in a format requested in the Accept header, the server sends the 406 Not Acceptable error.

    From the screenshot attached in the comments, you can see clearly that charset in response headers is iso-8859-1. Just send the response in UTF-8 encoding and that should solve the issue.

    Have a look at this SO link for setting charset header in PHP response.