简体   繁体   English

使用AJAX将变量从Javascript传递到PHP

[英]Pass variable from Javascript to PHP using AJAX

I'm trying to pass in variables from a Javascript file to a PHP file. 我正在尝试将变量从Javascript文件传递到PHP文件。 From my js file: 从我的js文件中:

dataQuery = {
    range: [[range.lower, range.upper]],
    detail: { id: detail.id }
  };

 $.ajax({
    type: "POST",
    async: true,
    url: scope.fetchUrl,
    data: { query: dataQuery }
    })
    .done(function( data ) {
        alert("success!");
    }

In my php file I have session variables because I need to do oauth authentication. 在我的php文件中,我有会话变量,因为我需要进行oauth身份验证。

if (isset($_SESSION['accessToken'])) 
{
    $companyId = "1234";
    $rollupFreq = "1H";
    $oauth->setToken(
        $_SESSION['accessToken'],
        $_SESSION['accessTokenSecret']);
    $apiUrl = ($apiBaseUrl
                . '&company_id=' . urlencode($companyId) 
                . '&rollup_frequency=' . urlencode($rollupFreq) 
                . '&start_datetime_utc=' . urlencode($range['lower'])
                . '&end_datetime_utc=' . urlencode($range['upper'])
                );
    try
    {
        header('Content-Type: application/json');       

        $data = $oauth->fetch($apiUrl);
        $responseInfo = $oauth->getLastResponse();
        print_r($responseInfo);
        if (isset($_GET['query']))
        {
            $range = $_GET['query'];
            print_r($range);
            }
    }
}

Nothing appears when I try to print $range, and when I try to use values from $range in the url I get "Undefined variable: range in url" 当我尝试打印$ range时,什么都没有出现,当我尝试在url中使用$ range中的值时,出现“ Undefined variable:range in url”

Any help would be appreciated! 任何帮助,将不胜感激!

You're creating an AJAX request using POST : 您正在使用POST创建AJAX请求:

 $.ajax({
     type: "POST",
     //...
 });

Yet in your PHP code, you use the $_GET variable: 然而,在您的PHP代码中,您使用了$_GET变量:

$range = $_GET['query'];

Change $_GET to $_POST . $_GET更改$_GET $_POST

You're also using the $range variable (in urlencode($range['upper']) for example), but there's no code anywhere that actually declares, let alone initializes it. 您还使用了$range变量(例如,在urlencode($range['upper'])中),但是实际声明的任何地方都没有代码,更不用说初始化它了。 That's the cause of the "Undefined variable" notices you're seeing 这就是导致您看到“未定义变量”的原因

Lastly, the data you're sending to PHP will look something like this: 最后,您要发送到PHP的数据如下所示:

$_POST['query']['range'] = array(
    array(range.lower, range.upper)//whatever these values may be
);

So to get at the range.lower value, you'd have to write: 因此,要达到range.lower值,您必须编写:

$_POST['query']['range'][0][0];
//for the upper:
$_POST['query']['range'][0][1];

That's just messy. 太乱了 see the docs : jQuery will correctly format your data for you, regardless of what you pass to $.ajax . 请参阅文档 :无论您传递给$.ajax什么,jQuery都会为您正确格式化数据。 I'd suggest the following: 我建议以下内容:

dataQuery = {
    range: {lower: range.lower, upper: range.upper},
    detail: { id: detail.id }
};

 $.ajax({
    type: "POST",
    //async: true, <== you can leave this out
    url: scope.fetchUrl,
    data: dataQuery
}).done(function( data ) {
    alert("success!");
});

Then, in PHP, you can get at the values a bit more intuitively: 然后,在PHP中,您可以更直观地了解这些值:

$upper = $_POST['range']['upper'];
//to get a range array:
$rage = range(
    (int) $_POST['range']['lower'],//these values are strings so cast
    (int) $_POST['range']['upper'] //to ints to get a numeric range
);
$detailId = $_POST['detail']['id'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM