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!
db_connect.php
$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 = "
CREATE TABLE IF NOT EXISTS ClassValues (
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
$.ajax({
url: 'php/insertvalue.php',
data: { 'one': value }, // slider value
type: 'post',
dataType: 'json',
success: function(x) {
alert(x.one);
},
error: function(request, status, error) {
alert(error);
}
});
insertvalue.php
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)";
mysql_query($query);
$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";
}
$conn->close();