سؤال

I have a jQuery script file on a page which requires data to be uploaded. Depending on if the data uploaded has a value or not, the PHP page will either return the current time (if value uploaded !isset()), or some sql data. However, when the variable I upload actually has a value, it still returns the !isset() method. Am I doing something incorrectly?

AJAX

    $.ajax({
        url: 'download.php',
        type: 'REQUEST',
        datatype: 'json',
        data: ({
            last_downloaded: latestTimestamp,
            username: username
        }),
        success: function (data) {
        parsedData = $.parseJSON(data);

            if (!latestTimestamp) {
                latestTimestamp = parsedData.most_recent;
            }
        }
    });

}

if latestTimestamp is null, (it should be the first time this method is run), then the most recent time is run. However when it runs the second time, latestTimestamp has a value when I console.log.

PHP

<?php

// Get variables sent
$last_chat_time = $_REQUEST['last_downloaded'];
$username = $_REQUEST['username'];

// Start echoing JSON

if (!isset($last_chat_time)) {
    // User did not send last chat time they have, assume they just joined
    // Get the most recent chat date
    $SQL     = 'SELECT current_timestamp() as "most_recent" from dual';
    $results = mysql_fetch_assoc(mysql_query($SQL));
    $last_chat_time = $results;
    echo '{"most_recent":"' . $results['most_recent'] . '"}';
} 
else{
    $SQL = 'return some tasty data'
    $result = mysql_query($SQL);

    $messages = Array();

while ( $row = mysql_fetch_assoc($result) ) {
    $messages[] = Array(
        'chat' => $row['chat'],
        'time' => $row['time_sent'],
        'username' => $row['username']
    );
}

echo json_encode($messages);

}

On the php, it ALWAYS returns the first if. However, if I visit the url directly for the php page and append ?last_downloaded=somedate, it returns the correct information. Am I doing the AJAX incorrectly?

هل كانت مفيدة؟

المحلول

To me this has to be updated to type : 'post or get' because php's $_REQUEST handles both, so you can change your type to this:

$.ajax({
    url: 'download.php',
    type: 'post',

or this:

$.ajax({
    url: 'download.php',
    type: 'get',
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top