简体   繁体   中英

AJAX POST return data not appearing

I have an AJAX call which runs on a form submit (with prevent default to stop standard submit):

var form = $(this);
$.ajax({
    type: form.attr('method'),
    url: form.attr('action'),
    data: form.serialize()
}).done(function(data) {
    $('#processingFile').hide();
    $('#downloadFile').show();

    $('#shareURL').val(data.url);
    $('#downloadFile').attr('href', data.url);
    $('#aboutFile').html('<b>File URL:</b> ' + data.url + '<br /><b>File Size:</b> ' + data.size + '<br /><b>Time Stamp:</b> ' + data.timestamp + '<br /><b>Client IP:</b> ' + data.ip);
}).fail(function() {
    $('#saveFile').hide();
    $('#error').show();
});

The file it submits to is a PHP file which is as follows:

// VARIABLES
$fileURL = $_POST['fileURL'];
$tmpURL = substr(md5(rand()), 0, 7);
$deleteCode = md5($tmpURL);

// COOKIE
setcookie($tmpURL, $deleteCode, time()+86400);

// SAVE FILE
if($fileURL){
    file_put_contents("tmp/" . $tmpFile, file_get_contents("http://" . $fileURL));
}

// OUTPUT
$result = array(
    'url' => "tmp/" . $tmpFile,
    'size' => filesize("tmp/" . $tmpFile) * .0009765625 * .0009765625,
    'timestamp' => date('H:i:s d-m-Y'),
    'ip' => $_SERVER['REMOTE_ADDR']
);

echo json_encode($result);

When the script is run everywhere which uses data.x in the jQuery returns undefined. Any idea why that happens and how to fix it?

data is a string containing your returned JSON text; it isn't an object.

To parse the JSON object, you have a couple of options:

  • Call JSON.parse() yourself.

  • Pass dataType: "json" to tell jQuery AJAX to parse it for you.

  • Set Content-Type: application/json in the server's response so that jQuery knows to parse it for you.

Set dataType: 'json' and check! Look this doc and set your datType.

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