Skip to content

Instantly share code, notes, and snippets.

@techslides
Created October 20, 2014 19:09
Show Gist options
  • Select an option

  • Save techslides/d80703ea7c3c2e225847 to your computer and use it in GitHub Desktop.

Select an option

Save techslides/d80703ea7c3c2e225847 to your computer and use it in GitHub Desktop.
HTML Ajax POST call to PHP
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Save Data with Ajax and PHP</title>
</head>
<body>
<textarea id="data">Enter some content here you want to save as a file</textarea>
<button id="save" onclick="save();return false;">Save</button>
<div id="response"></div>
<script>
function save(){
var response=document.getElementById("response");
var data = 'data='+document.getElementById("data").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
response.innerHTML='<a href="files/'+xmlhttp.responseText+'.txt">'+xmlhttp.responseText+'.txt</a>';
}
}
xmlhttp.open("POST","save.php",true);
//Must add this request header to XMLHttpRequest request for POST
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
}
</script>
</body>
</html>
@techslides
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment