gigapico00
gigapico00

Reputation: 457

Data sent through AJAX not available in $_POST

My Javascript code is the following:

function on(logged_user) {
    alert(logged_user);

    $.ajax({
        url: "update_stats.php",
        type: "POST",
        data: logged_user
    });
}

update_stats.php contains

<?php
     $logged_user = $_POST["logged_user"];
?>

but I can see that $logged_user is just an empty string (I'm inserting it into a database table)

Upvotes: 0

Views: 42

Answers (4)

SachinPatil4991
SachinPatil4991

Reputation: 774

You need to pass data in key - value format to get accesible by $_POST, $_GET and $_REQUEST array variables in php.

data: {'logged_user' : data: logged_user}

You can access raw input like JSON data or text data which not in the key value format you can use file_get_contents("php://input") to access data.

Upvotes: 0

JIJOMON K.A
JIJOMON K.A

Reputation: 1280

Its not javascript , its a jquery ajax, so please include a jquery library. and change your function like this

Syntax to pass the values like,

data: '{ "key":' + value+ ', "key":"value" }',

or

data = "key=" + value

or

data: JSON.stringify({ key: value, key: value}),

 function on(logged_user) {

        var dataString = "logged_user=" + logged_user

        $.ajax({
            type: "POST",
            url: "update_stats.php",
            data: dataString,
            cache: false,
            success: function(result) {
                    alert(result)
            }
        })
    }

Upvotes: 0

just try this:

function on(logged_user) {
alert(logged_user);

$.ajax({
    type : 'POST', 
    url  : update_stats.php,
    data : logged_user,
    dataType : 'json', 
    encode : true
});
}

Upvotes: 0

Nick
Nick

Reputation: 147146

Your data parameter for the $.ajax call is not in the right format. From the manual:

The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}

You should change that line to:

data: { logged_user : logged_user },

or

data: 'logged_user=' + logged_user,

Upvotes: 1

Related Questions