LadyT LadyT - 1 year ago 134
Javascript Question

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data when trying to inser to mysql

I am using new to using AJAX and PHP I am trying to send a post request to a file called insertvalue.php. I already created the table and database. I am trying to grab the value from a jquery slider through ajax and then insert that value into the mysql table. After that, I want to return the results from the mysql table.

When I try running the script I get the error "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". I checked, and I am not sure what I did wrong. Any assistance would be appreciated. Thanks!


$connect = mysqli_connect("localhost", "private", "private", "private");
// fake credentials for posting

if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();

$createTable = "
question VARCHAR(40) NOT NULL,
slider_value INT(50) NOT NULL

if ($connect->query($createTable) === TRUE) {
// echo "Table ClassValues created successfully";
} else {
echo "Error creating table: " . $connect->error;

js file with ajax to send js to php

url: 'php/insertvalue.php',
data: { 'one': value }, // slider value
type: 'post',
dataType: 'json',
success: function(x) {
error: function(request, status, error) {


include 'db_connect.php'; // database connection

$one = $_POST['one'];
$array = array('one'=>$one);

echo json_encode($array);

$query = "INSERT INTO ClassValues (question, slider_value) VALUES('Question 1', $one)";

$selection = "SELECT slider_value FROM ClassValues";
$result = $conn->query($selection);

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "slider_value" . $row["slider_value"] . "<br/>";
} else {
echo "0 results";

Answer Source

From your JavaScript code, you are expecting JSON encoded data from the server.

Hence, you have to make sure your server will respond with only one JSON encoded result, per each client request. The parser will not understand mixture of JSON encoded data with text like { "one": "one" }slider_value or mixture of JSON encoded data with another JSON encoded data like { "one": "one" }{ "two": "two" }.

To achieve this, you need to convert all your echo 'some result' statements to $result = 'some result'. At the end of your script, you will then encode and echo the final result, e.g.: { "result": "Success", "message": "Data inserted successfully"}.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download