I have been having problems with executing AJAX. I can't seem to get the JSON data sent to process.php. Every time I check to see if the data was sent, nothing gets printed out. I've probably read hundreds of posts about this but I still can not seem to figure it out. I only included the code that I thought was important. Any help would be greatly appreciated!
form.php (triggers JS)
<form action="process.php" method="post" id ="commentForm">
<textarea id="comment" name="comment"></textarea>
<button type="submit" name="submitComment" onclick = "submit(); return false;">Save</button>
</form>
footer.php (execute AJAX)
<script>
function submit() {
var str = document.getElementById('comment').value;
var jsonString = {"comment":str};
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange= function() {
if (xhttp.readyState== 4 && xhttp.status== 200) {
var result = JSON.parse(xhttp.responseText);
// execute some code with result
};
xhttp.open("POST", "includes/process.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('string=' + JSON.stringify(jsonString));
}
</script>
process.php
<?php
if (isset($_POST['string'])) { // checks if data was sent
$str = $_POST['string'];
echo $str;
}
echo json_encode($arr); // assume array is already filled
?>