helpmeplz helpmeplz - 2 months ago 15
Ajax Question

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:


  1. Create a variable (based on what the user clicked on in a pie chart)

  2. Send that variable to PHP using AJAX

  3. Open the PHP page that the variable was sent to



Task one works as confirmed by the console log.

Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.

Task three works.


Javascript (located in index.php):

function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {

console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));

// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});

// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}


PHP (located in test.php)

$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";


Thanks to anyone who can help!

Answer

From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax

See the following function (no ajax):

function selectHandler(e)     {
            // Task 1 - create variable
            var itemNum = data.getValue(chart.getSelection()[0].row, 0);
            if (itemNum) {

                console.log('Item num: ' + itemNum);
                console.log('Type: ' + typeof(itemNum));

                window.location = 'test.php?itemNum='+itemNum;
            }
        }

change:

   $item = $_GET['itemNum'];
    echo "<h2>You selected item number: " . $item . ".</h2>";

or better you do a simple post request from a form like normal pages do :)