Hello!
I am having trouble with setting up a simple post script to push some data to my php/mysql db…
I have my js that simply is loaded with page load:
var levelData = [];
var mapWidth = 50;
var minTileRange = 0;
var maxTileRange = 9;
//DO STUFF TO PUSH ROW/COL GRID TO LEVELDATA ARRAY HERE
//BEGIN BY RANDOMLY GENERATING TILES
for (var i = 0 ; i < mapWidth; i++) {
levelData[i] = []; // Initialize inner array
for (var j = 0; j < mapWidth; j++) { // i++ needs to be j++
levelData[i][j] = Math.floor(Math.random() * (maxTileRange - minTileRange + 1) ) + minTileRange;
}
}
//LEVELDATA CREATED, NOW PUSH TO DB WITH AJAX
$(document).ready(function() {
var levelDataString = JSON.stringify(levelData);
if (levelData === "") {
console.log('LEVELDATA EMPTY');
}else{
$.ajax({
type: 'POST',
url: '../includes/worldpush.php',
data: { levelData : levelDataString },
success:
function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
console.log('SHOULD BE SUCCESSULL');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
});
My worldpush.php:
<?php
include "../dbauth/users.inc.php";
$usersconn = new mysqli($usershostname, $usersusername, $userspassword, $usersdbname);
// Check connection
if ($usersconn->connect_error) {
die("Connection failed: " . $usersconn->connect_error);
}
$levelData = $_POST['levelData'];
$worldpushsql = "INSERT INTO worlds leveldata='$levelData'";
if (mysqli_query($usersconn, $worldpushsql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($usersconn);
?>
While I am aware it is unwise to simply push data to a server on page load, this is just for development purposes so I can better understand my Ajax scripting. Currently, the page loads with 201 error alert and the game loads but the data is not pushed to server. I know the issue is not with the db connection as I have other php scripts that work with these connection settings without issue. Am I missing something with the ajax part?