I am posting some data to a PHP file using ajax and saving it to a MySQL database. This works fine, but I also want to save one of the data elements to a text file (which should be created) on the server but I can't get it to save to a file.
This is how my code looks:
jQuery (snippet)
var uid = "1";
var name = "bruno";
var number = "0889-123-123";
var location = "{"locationInfo":[{"title":"home","lat":-16.450902223672625,"lng":10.6103515625,"speed":""},{"title":"work","lat":-14.94621907436008,"lng":17.99560546875,"speed":""}]}"
$.ajax({
type: "POST",
url: "process.php",
data: {uid:uid, name:name, number:number, location:location},
dataType: 'json',
cache: false,
})
PHP - process.php
<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
$mysqli = new mysqli('localhost', "root", "", "tp");
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$mysqli->query("
INSERT INTO `table`(`uid`, `name`, `number`)
values ('".$inputvalues['uid']."', '".$inputvalues['name']."', '".$inputvalues['number']."');
");
file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));
}
mysqli_close($mysqli);
$returnResult ="success";
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>