Проблема заключается в том, что когда я нажимаю кнопку «отправить данные», я получаю ответ (это правильно), но когда я нажимаю ссылку «перейти к файлу php» (которая тот же файл php, что и ранее) Я получаю Undefined index: firstname и Undefined index: lastname error. Как я могу это исправить?Как получить переменную из ajax в другом php-файле
Вот мой код:
<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 = "my_parse_file.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>
<a href="my_parse_file.php">go to the php file</a>
</body>
и файл PHP
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
Вы собираетесь в php-файл по запросу get ('href'), и поэтому это другой запрос .. – Pogrindis
вам нужно отправить параметры на php –
Во второй раз, когда вы нажмете« перейти в php-файл », это будет запрос GET, и php не найдет эти переменные в супергрупповом $ _POST. – Vincent