0

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
?>

2 Answers2

3

The following line

var str = document.getElementById('comment');

should be

document.getElementById('comment').value;

You also want to add return false for good measure to prevent the form from submitting without ajax.

onclick = "submit();return false;"
-1

You see your form event is working and not your ajax call. You might consider it doing this way....

<button type="submit" name="submitComment" id='submitbtn'>Save</button>
<script>
    $('#submitbtn).click(function(event){
        event.preventDefault();
        /// rest of your code here
    });
</script>
Raihan Kabir
  • 447
  • 2
  • 10