Further to my code which teaches you how to retrieve JSON data from the server, here is another example which shows you how to post JSON data to the server and store it in a mySQL database.
There are three basic steps
- Link to AJAX code
- Write the JavaScript code to call the server side file
- Write the server side code that will be called by the JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
function handleSaveLocation(){
$("#message").html("Storing the location to server..");
var fileurl = "http://www.yourwebsite.com/saveLocation.php";
var parameterurl_1 = "latitude=" + $("#txtlatitude").val();
var parameterurl_2 = "longitude=" + $("#txtlongitude").val();
var url = fileurl + "?" + parameterurl_1 + "&" + parameterurl_2;
$.post(url, saveLocationToServer);
} //end function
function saveLocationToServer(data,status){
var obj = JSON.parse(data);
var s = obj[0];
$("#message").html("Location stored in server under record id: #" + s);
} //end saveLocationToServer(data,status)
<?
$latitude = $_REQUEST["latitude"];
$longitude = $_REQUEST["longitude"];
try {
$mysqli = new mysqli('localhost','username','password','database');
$query = "INSERT INTO locations (latitude,longitude) VALUES (?,?)";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('dd', $latitude,$longitude);
$stmt->execute();
$insert_id = $mysqli->insert_id;
$data = array();
$datarow = array($insert_id);
array_push($data, $datarow);
echo json_encode($data);
mysqli_stmt_free_result($stmt);
$stmt->close();
} //end if $stmt = $mysqli->prepare($query))
} //end try
catch (Exception $exception){
echo $exception;
} //end catch
?>