How can I upload data to database with AJAX, JSON and PHP? Here is the code.
AJAX
JavaScript
x
function saveToTheDB(ratedIndex) {
$.ajax({
url: 'fetch.php',
method: 'POST',
cache: 'false',
dataType: 'json',
data: {
ratedIndex: ratedIndex
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
}
PHP
JavaScript
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
require_once 'includesdbh.inc.php';
$rate = $_POST['ratedIndex'];
if(isset($_GET['userid'])){
if($db->query(" INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`)
VALUES (null, 3 , 8, '".$rate."')
"))
}
echo json_encode($rate);
}
What have I done wrong? Can some one help me to solve this problem? Thank you very much!
EDIT
ERROR I get back a full object
Advertisement
Answer
As the response points you have syntax error, here I refactored your code in order to work.
JavaScript
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once 'includesdbh.inc.php';
$rate = $_POST['ratedIndex'];
if (isset($_GET['userid'])) {
if($db->query("INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`) VALUES (null, 3 , 8, '".$rate."')")) {
// implementation if query is successful
}
}
echo json_encode($rate);
}
JFYI: Avoid directly placing the input variables into the query, you should use Prepared Statements.