I'm trying to send some data to save.php in order to save it in db. The thing is: Ajax post i success and it's returning right data in a console but 'echo' in save.php is returning nothing.I don't know what's wrong with this code.
var $nick = $('span.nick').html();
var $scores = points;
var range = n2;
var $upgrades =
{
'numbers': range,
'pointsPerSec': pps,
'multip': multi
};
//Save to DB
$.ajax({
url: "save.php",
type: "POST",
data: {
userID: $nick,
userPoints: $scores,
userUpgrades: $upgrades
},
async: false,
cache: false,
success: function(){
alert('Data saved');
console.log(save);
getData();
},
error: function(){
alert('You fucked up mate :(');
}
});
function getData(){
$.ajax({
type: 'GET',
url: 'save.php',
async: false,
cache: false,
success: function(data){
data = $.parseJSON(data);
$.each(data, function(i, save){
console.log(save);
});
},
error: function(){
alert('Error Ajax');
}
});
}
Here's my save.php file
if(isset($_POST['userPoints']) && !empty($_POST['userPoints'])){
$post=$_POST["userPoints"] or $_REQUEST["userPoints"];
$dec_post=json_decode($post);
echo $dec_post;
}
you did not passed any parameter in your ajax success function, to retrive and console data in success function you should pass a parameter in the success change your ajax success function as
success: function(response){
alert('Data saved');
console.log(response);
getData();
},
found your mistake:
if(isset($_POST['userPoints']) && !empty($_POST['userPoints']))
{
$post = $_POST["userPoints"] or $_REQUEST["userPoints"];
$dec_post = json_encode($post); // mistake was here
echo $dec_post;
// you should exit; or die; here if this is final response
}
success callback has a response arg you were missing that
//Save to DB
$.ajax({
url: "save.php",
type: "POST",
data: {
userID: $nick,
userPoints: $scores,
userUpgrades: $upgrades
},
async: false,
cache: false,
success: function(save){
alert('Data saved');
console.log(save);
getData();
},
error: function(){
alert('You fucked up mate :(');
}
});
Here's save.php
session_start();
/*if(!isset($_SESSION['loggined'])&&($_SESSION['loggined']==true)) {
header('location: index.php');
exit();
}*/
require_once "dbconnect.php";
$connect= @new mysqli($host, $db_user, $db_pass, $db_name);
if($connect->connect_errno != 0){
die("There was an error");
}
else
{
$nick = $_POST['userID'] or $_REQUEST["userID"];
$enNick = json_encode($nick);
echo $enNick;
$points = $_POST['userPoints'] or $_REQUEST["userPoints"];
$enPoints = json_encode($points);
echo $enPoints;
$upgrades = $_POST['userUpgrades'] or $_REQUEST["userUpgrades"];
$enUpgrades = json_encode($upgrades);
echo $enUpgrades;
$connect->close();