jquery ajax sending json to php error

Okay so here is my ajax request:

$("#scoreForm").submit(function(e){
    e.preventDefault();
    var nickName = $('#nickName').val();
    var gameScore = parseInt($('#gameScore').text());
    var result = {  'result' : '{ "nick":"'+nickName+'", "score":'+gameScore+' }' };
    //var result = { "nick":nickName, "score":gameScore };
    $.ajax({
        url: "http://localhost:8888/snake/addScore.php",
        type: "POST",
        data: result,
        //dataType: "jsonp",
        success: function(data){
            alert("siker");

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("bukta " + textStatus);
            //console.log(data);
        }
    });
    return false;
});

and my php process code:

$json_decoded = json_decode($_POST['result'],true);
//$nick = $_GET['nick'];
//$score = $_GET['score'];

$mysqli = new mysqli("localhost", "root", "root", "snake",8889);
//$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$nick."', ".$score.")");
$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded['nick']."', ".$json_decoded['score'].")");

echo "true";

Now i got the data inserted into the database, but ajax still firing error event. i read that if i set the dataType to jsonp it will go trough , but then i get parse error, how do i get past that?

Upvotes: 2

Views: 502

Answers (1)

user1026361
user1026361

Reputation: 3657

Wehn you access the $_POST variables in your php script, you need to refer to them the way they are packaged with the JSON object:

$_POST['nick']
$_POST['score']

If you want to refer to the items as $_POST['result'] and use your json decoding approach, youll need to package it this way:

var result = {  result : { "nick":nickName, "score":gameScore } };

Upvotes: 4

Related Questions