Issue with insert into sql query

75 views Asked by At
$.ajax({
    url: 'http://localhost/xampp/htdocs/ajax.php',

    contentType: 'application/json',
    type: 'post',
    data: {

//score is a new variable and count2 is an integer variable which i want to send it to the database "score":"count2" },

    success: function () {
        alert("ok");

    },
    error: function () {
       alert("error");
    }
});    

The above code alerts me "ok".

function connect(){
    $connect = mysql_connect('localhost','root','') or die("ERROR");
    $connect2Database = mysql_select_db('fypdb', $connect);
    return $connect;
}

if(isset($_POST)){

    if($connect = connect()){

        $query = "INSERT INTO fypdbtable (score) VALUES ('".$_POST['score']."');";
        $completeQuery = mysql_query($query, $connect);
    }
}

I think the problem is on "insert into" query because in ajax.php prompts me Notice: Undefined index: score in C:\xampp\htdocs\xampp\htdocs\ajax.php on line 14 where it is the query line

Any help would be appreciate

2

There are 2 answers

3
harrow On

The "error" message tells you, that $_POST['score'] is not defined. But thats just a warning. If you want to know if your variable is set, use isset() function or turn off warnings in the configuration.

7
alphawow On

Problem here is in your ajax code. You are using contentType: 'application/json' but you try to acces param in your php script with $_POST, but post works with form encoded content types. So you can remove contentType from your ajax call and it will use default which is
contentType:'application/x-www-form-urlencoded; charset=UTF-8'

EDIT Make your ajax code like that:

$.ajax({
url: 'http://localhost/xampp/htdocs/ajax.php',
type: 'post',
data: {
    "score":"count2"
},

success: function () {
    alert("ok");

},
error: function () {
   alert("error");
}
});