2

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?

2
  • 2
    Always escape your SQL INSERTS!!!!!! Commented Nov 1, 2012 at 18:47
  • i'm just trying things first, don't worry :) Commented Nov 1, 2012 at 18:52

1 Answer 1

4

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 } };
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent point and one that I missed. Except in very rare cases, you should never have to json_decode your input twice
okay so, with nick and score separated from post,it's working, but i get still error back on ajax, but it inserts into database. on second approach with json_decode, nothing works, even inserting failed. why?
Your insert should look like: $mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded->nick."', ".$json_decoded->score.")");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.