-1

How can I upload data to database with AJAX, JSON and PHP? Here is the code.

AJAX

    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

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    require_once 'includes\dbh.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

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
xMrViktorx
  • 79
  • 2
  • 9

1 Answers1

0

As the response points you have syntax error, here I refactored your code in order to work.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once 'includes\dbh.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.

G.Spirov
  • 198
  • 9