I'm having issues posting an Array to a PHP page using AJAX. I've been using this question as guidance, but for whatever reason I still can't get it to work. From what I can tell by using print_r($_POST)
, I am posting an empty Array, but on the HTML/Javascript page I use an alert to see that the Array has been filled. The post is working because it inputs blank values into a MySQL database on post, but I can't figure out why it is passing an empty Array. The code is as follows:
Javascript:
<script type="text/javascript">
var routeID = "testRoute";
var custID = "testCustID";
var stopnumber = "teststopnumber";
var customer = "testCustomer";
var lat = 10;
var lng = 20;
var timeStamp = "00:00:00";
var dataArray = new Array(7);
dataArray[0]= "routeID:" + routeID;
dataArray[1]= "custID:" + custID;
dataArray[2]= "stopnumber:" + stopnumber;
dataArray[3]= "customer:" + customer;
dataArray[4]= "latitude:" + lat;
dataArray[5]= "longitude:" + lng;
dataArray[6]= "timestamp:" + timeStamp;
var jsonString = JSON.stringify(dataArray);
function postData(){
$.ajax({
type: "POST",
url: "AddtoDatabase.php", //includes full webserver url
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
window.location = "AddtoDatabase.php"; //includes full webserver url
}
alert(JSON.stringify(dataArray))
</script>
PHP:
<?php
print_r($_POST);
$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
$mysqli= new mysqli("fdb5.biz.nf","username","password","database");
mysqli_select_db($mysqli,"database");
$sql = "INSERT INTO Locations (routeID, custID, stopnumber, customer, latitude, longitude, timestamp) VALUES " .
"('$routeID','$custID','$stopnumber','$customer','$latitude','$longitude','$timestamp')";
mysqli_query($mysqli, $sql);
$error = mysqli_error($mysqli);
echo $error;
?>
print_r($_POST)
only displays Array() on the php page while the jsonString alert on the javascript page shows
["routeID:testRoute",
"custID:testCustID",
"stopnumber:teststopnumber",
"customer:testCustomer",
"latitude:10",
"longitude:20",
"timestamp:00:00:00"]
Anyone see what I'm doing wrong?
See Question&Answers more detail:os