Reputation: 73
Trying to get json array from ajax, but when i'm trying to write it down in the text file, it shows nothing.
var img = JSON.parse(localStorage.getItem("iPath"));
var img = JSON.stringify(img);
console.log(img);
$.ajax({
url: './php/temporary.php?deletefile',
cache: false,
type: 'POST',
data: img,
success: function( respond, textStatus, jqXHR ){
if( typeof respond.error === 'undefined' ){
//window.location.assign("/buyplace.html");
}
else{
console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error );
}
},
error: function( jqXHR, textStatus, errorThrown ){
console.log('ОШИБКИ AJAX запроса: ' + textStatus );
}
});
if( isset( $_GET['deletefile'] ) ){
$params = json_decode( $_POST);
$myfile = fopen("testfile.txt", "w");
fwrite($myfile, $params);
//$img = "uploads/" . $imgPath;
//move_uploaded_file($imgPath, "./uploads/");
//unlink('./uploads/' . $img);
}
?>
How can i solve this problem?
Upvotes: 0
Views: 111
Reputation: 780994
There's no need to send the parameters as JSON. You can use an object as the data:
option, and each property will be sent as the corresponding $_POST
element.
var img = JSON.parse(localStorage.getItem("iPath"));
console.log(img);
$.ajax({
url: './php/temporary.php?deletefile',
cache: false,
type: 'POST',
data: img,
success: function( respond, textStatus, jqXHR ){
if( typeof respond.error === 'undefined' ){
//window.location.assign("/buyplace.html");
}
else{
console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error );
}
},
error: function( jqXHR, textStatus, errorThrown ){
console.log('ОШИБКИ AJAX запроса: ' + textStatus );
}
});
In PHP, you'll need to use json_encode()
to convert the $_POST
array to a string that can be written to a file.
if( isset( $_GET['deletefile'] ) ){
$params = $_POST;
$myfile = fopen("testfile.txt", "w");
fwrite($myfile, json_encode($params));
}
Upvotes: 0
Reputation: 91734
$_POST
will contain key-value pairs and what you are sending, is a string.
So you should either read the standard input, or you need to make sure that you are actually sending key-value pairs.
The first case is already posted as a comment by @Scuzzy.
For the latter, using the standard key-value pairs in $_POST
:
$.ajax({
url: './php/temporary.php?deletefile',
cache: false,
type: 'POST',
data: {json: img},
// the rest of your js
And in php:
if( isset( $_GET['deletefile'] ) ){
$params = json_decode($_POST['json']);
// the rest of your php
Upvotes: 1