简体   繁体   中英

Pass variable from Javascript to PHP using AJAX

I'm trying to pass in variables from a Javascript file to a PHP file. From my js file:

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.

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"

Any help would be appreciated!

You're creating an AJAX request using POST :

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

Yet in your PHP code, you use the $_GET variable:

$range = $_GET['query'];

Change $_GET to $_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. 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:

$_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:

$_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 . 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:

$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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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