javascript - AJAX POST REQUEST -
i'm trying save data database javascript using ajax. part of code create request , send json formatted data save/save1.php:
urlpath = "save/save1.php"; var request = new xmlhttprequest(); request.addeventlistener('load',function() { console.log(this.responsetext); }); idgame = "1"; data = json.stringify({'iduser': iduser, 'idgame': idgame, 'score': score}); request.addeventlistener('error', function () { document.write('there error ajax request!'); }); request.addeventlistener('load', this.onsuccess); request.onreadystatechange = function(){ if(request.readystate == 4){ alert(request.responsetext); } }; request.open("post", urlpath); request.setrequestheader('content-type','application/json'); request.send(data);
and save1.php file:
<?php include '../database_connection.php'; var_dump($_post);die(); //this debuging , prints array empty if (isset($_post['iduser']) && isset($_post['idgame']) && isset($_post['score'])) { $rez = $_post['score']; $idgame = $_post['idgame']; $iduser = $_post['iduser']; $query = 'insert scores (iduser, idgame, score) values ('.$iduser.','.$idgame.','.$rez.');'; $sucess = mysql_query($query); if($sucess) { echo 'yes'; } else { sendjsonresponse(array( 'error' => "not saved")); } } else { sendjsonresponse(array( 'error' => "not set")); }; function sendjsonresponse($data) { header('content-type: application/json'); die(json_encode($data)); }
what doing wrong? :(
edit: solved it. found explanation:
i noticed setting contenttype well... work won't able use $_post var. instead you'll need grab data file_get_contents("php://input") "should" give raw json string. there should able use php's json_decode turn true php object.
so added save1.php document:
$data = json_decode(file_get_contents('php://input'), true); if (isset($data['iduser']) && isset($data['idgame']) && isset($data['score'])) { $rez = $data['score']; //and on...
Comments
Post a Comment