I’m attempting to send a JSON document to a PHP script using AJAX. The JSON document is constructed from the value of a <textarea>
.
I have successfully executed the solution using JQuery, and (for fun?!) am working on achieving the same result with vanilla AJAX.
The calling PHP script:
print("<script>n");
print(" function preview() {n");
print(" var xhttp;n");
print(" xhttp = new XMLHttpRequest();n");
print(" xhttp.onreadystatechange = function() {n");
print(" if (this.readyState == 4 && this.status == 200) {n");
print(" document.getElementById("output").innerHTML = this.responseText;n");
print(" }n");
print(" };n");
printf(" var postData = {n");
printf(" 'html' : document.getElementById("editor").value,n");
printf(" };n");
printf(" xhttp.open("POST", "markuppreview.php");n");
printf(" xhttp.setRequestHeader('Content-type', 'application/json');n");
printf(" xhttp.send(postData);n");
print(" };n");
print("</script>n");
print("<pre><textarea id="editor" name="content" placeholder="Enter your markup"></textarea></pre><br />n");
print("<button value="Preview" onclick="preview();">Preview</button>n");
print("<h2>Preview</h2>n");
print("<div id="output" style="height:100px"></div>n");
The receiving PHP:
$Parsedown = new Parsedown();
$Parsedown->setSafeMode(true);
$data['success'] = false;
$data['output'] = '';
if ($_POST['html']) {
$data['success'] = true;
$data['output'] = $Parsedown->text($_POST['html']);
}
echo json_encode($data);
I receive the following error, and can’t work out why the postData.html isn’t being received.
Warning: Undefined array key "html" in /Library/WebServer/Documents/markuppreview.php on line 8
{"success":false,"output":""}
I also tried a Javascript object method for constructing the JSON document, but received the same message. When I alert
the JSON document, it does show an html element with the data from the <textarea>
.
printf(" var postData = new Object();n");
printf(" postData.html = document.getElementById("editor").value;n");
printf(" postData = JSON.stringify(postData);n");
printf(" alert(postData);");