简体   繁体   中英

PHP isn't recognizing data posted by ajax

I'm sending an ajax call to my PHP script as follows:

function load(){
    var request = {};
    request['action'] = 'load';
    request['file'] = 'lorem_ipsum.txt';
    $.ajax({
        type: 'POST',
        url: cgi_file,
        data: JSON.stringify(request),
        processData: false,
        dataType: 'html',
        contentType: 'application/html',
        success:function(response){
            console.log("received " + response);
        }
    });
}

and my PHP script is as follows:

$content_dir = '/static/content/';

$action = $_POST['action'];

switch ($action){
    case 'load':
        $file = $_POST['filename'];
        echo file_get_contents($content_dir . $file);
        exit();
}

The PHP is responding with the following failure:

Notice: Undefined index: action in /var/www/river/api.php on line 5

What's the issue here?

Just leave data as it is:

data: request,

You don't need to stringify it.

Also, your file parameter allows an attacker to read arbitrary files from your filesystem. Sanitize it.

Try ditch processData: false and contentType: 'application/html' and it should work

$.ajax({
    type: 'POST',
    url: cgi_file,
    data: request,
    dataType: 'html',
    success:function(response){
        console.log("received " + response);
    }
});

A few things wrong here, firstly the contentType property is for the data you are sending to the server, secondly dataType should be set to text as that is what you are recieveing from the server. If you want to receive the data in the $_POST array your javascript should look like this,

$.ajax({
    type: 'POST',
    url: cgi_file,
    data: {
        action: "load",
        file: "lorem_ipsum.txt";
    },
    dataType: 'text',
    success:function(response){
        console.log("received " + response);
    }
});

Jquery will send your data as a standard post to your server side code.

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