Получение переменных из Javascript в файл PHP через Ajaxrequest.open

У меня есть следующая функция JavaScript

function ajax_runs3(value){
var ajaxRequest;  // The variable that makes Ajax possible!
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}

var runs3= value;
ajaxRequest.open("POST","runs3.php"+ runs3, true);
ajaxRequest.send(null);
}

а также файл PHP

<?php
$servername = "localhost";
$username = "USER";
$password = "PASS";
$dbname = "labi8575_inventory";
$conn = mysql_connect($servername, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('labi8575_inventory');
$runs3 = $_POST["runs3"];
$sql = mysql_query("UPDATE demo SET runs3 = '$runs3'");
$retval = mysqli_query( $sql, $conn );
?>

Проблема в том, что я не могу передать var run3 из функции javascript в файл php. Я пробовал также по следующей теме (Использование ajaxRequest.open для отправки переменной в php) решения, такие как ajaxRequest.open («POST», «run3.php? variable =» + run3) или AjaxRequest.open («POST», «run3.php? myvar = run3», true); но в моем случае это не работает. Вы знаете, что не так в моем случае? Спасибо за ваш интерес.

1

Решение

ПОЧТОВЫЙ запрос не использует URL для параметров! Это метод GET, который использует параметры in-url …

Решение:

var runs3= value;
ajaxRequest.open("POST","runs3.php", true); //We open the url
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //IMPORTANT!! We add this header to tell to PHP that it is a "form" which sent requesdt
ajaxRequest.send("value=" + encodeURIComponent(runs3)); //Then we send DATA HERE  (encodeURIComponent encodes data to prevents URL-specific characters (for example '&'))

И тогда вы получите в PHP значение run3 в $_POST["value"]

Это «обычный» способ.

Но если вам нужен более гибкий формат запроса, вы также можете отправить данные в формате JSON:

var runs3 = {"val" : value};
ajaxRequest.open("POST","runs3.php", true); //We open the url
ajaxRequest.setRequestHeader("Content-type", "application/json");
ajaxRequest.send(JSON.stringify(runs3));

И сторона PHP 🙁 объяснено здесь: Чтение JSON POST с использованием PHP ):

$request = file_get_contents('php://input'); //raw request data
$object  = json_decode($request, true);      //we convert it to associative array, by JSON

print_r($object); //Should return Array[1] {  "val" => YOUR_VALUE};

Не «обычный» способ, но у вас больше гибкости при отправке данных
(потому что вы отправляете не строки, а необработанные данные: объекты / массивы …)

2

Другие решения

Попробуй это. Ваша функция (ajax_runs3)

function ajax_runs3(value){
var ajaxRequest;  // The variable that makes Ajax possible!
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}

var runs3= value;
//ajaxRequest.open("POST","runs3.php"+ runs3, true);
// ajaxRequest.send(null);

var url = "runs3.php";
var params = "runs3="+value;
ajaxRequest.open("POST", url, true);

//Send the proper header information along with the request
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");

ajaxRequest.onreadystatechange = function() {//Call a function when the state changes.
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
alert(ajaxRequest.responseText);
}
}
ajaxRequest.send(params);
}
0