Currently, I am in the process of developing a script that can effectively receive and parse a JSON array within the POST array. To start off, I am sending some random JSON data to my script so that I have something to work with.
The receiving script is written in PHP (although it could also be implemented in Javascript). At this moment, I am simply serializing the POST array and saving it to a text file to confirm that data is being received. However, what the script is saving appears to be an empty array.
To send the data, I am utilizing an ajax request. The following is what I currently have:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var jsondata = JSON.stringify({
val1:"this",
val2:"that"
});
$.ajax({
url: "http://api.mydomain.com/test/index.php",
method: "POST",
data: {json: jsondata},
contentType: "application/json",
success: function(data){alert(JSON.stringify(data));},
error: function(errMsg) {
alert(JSON.stringify(errMsg));
}
});
});
</script>
</head>
<body>
</body>
</html>
I have tested various modifications as well, such as
- not stringifying jsondata
- adjusting data to:
data: jsondata
- utilizing
type:
instead ofmethod:
in the request - adding
datatype: "json"
to the request
and several other attempts that are slipping my mind at the current moment. Is there a simple step that I am overlooking? Or perhaps, is there a simpler way to approach this task?
EDIT: I have included my index.php file below:
if (isset($_POST)){
// This line is commented out because it breaks it.
//$jspost = json_decode($_POST['json']);
$jsser = serialize($_POST);
echo "I'm here.";
// Write to text file
$myfile = "response.txt";
$fh = fopen($myfile, 'w') or die("can't open file");
$now = date("n/j/y g:i:s a");
fwrite($fh, $now."\r\n");
fwrite($fh, "I received a POST.\r\n");
fwrite($fh, $jsser);
fwrite($fh, "\r\n\n");
fclose($fh);
}