Created
March 31, 2017 19:55
-
-
Save webyroki/395eb34499bba00375afe76645d17b5f to your computer and use it in GitHub Desktop.
Получаем данные из input: имя и фамилия. Отправляем методом с помощью JS/POST. Обрабатываем и сохраняем
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script> | |
function ajax_post(){ | |
// Create our XMLHttpRequest object | |
var hr = new XMLHttpRequest(); | |
// Create some variables we need to send to our PHP file | |
var url = "forms.html.php"; | |
var fn = document.getElementById("first_name").value; | |
var ln = document.getElementById("last_name").value; | |
var vars = "firstname="+fn+"&lastname="+ln; | |
hr.open("POST", url, true); | |
// Set content type header information for sending url encoded variables in the request | |
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
// Access the onreadystatechange event for the XMLHttpRequest object | |
hr.onreadystatechange = function() { | |
if(hr.readyState == 4 && hr.status == 200) { | |
var return_data = hr.responseText; | |
document.getElementById("status").innerHTML = return_data; | |
} | |
} | |
// Send the data to PHP now... and wait for response to update the status div | |
hr.send(vars); // Actually execute the request | |
document.getElementById("status").innerHTML = "processing..."; | |
} | |
</script> | |
</head> | |
<body> | |
<h2>Ajax Post to PHP and Get Return Data</h2> | |
First Name: <input id="first_name" name="first_name" type="text"> <br><br> | |
Last Name: <input id="last_name" name="last_name" type="text"> <br><br> | |
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br> | |
<div id="status"></div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$file = 'index.json'; | |
$postdata = file_get_contents("php://input"); | |
// $postdata = 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file'; | |
file_put_contents($file, $postdata, LOCK_EX); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment