'How to get variable from JavaScript to PHP [duplicate]

i need to transfer a variable from js to a php page then insert it in the database

the Js code

    function tableText(tableCell) {
    var x =tableCell.innerHTML;
     console.log(x);
}

also tried the ajax

function tableText(tableCell) {
    var x =tableCell.innerHTML;
    console.log(x);
    $.ajax({  
    type: 'POST',
    url: 'try.php', 
    data: x ,
    complete: function(text){
         return text; }
 });
}

not sure if i got it right and i don't know how to call it in the php page

so How to get variable from JavaScript to PHP ??



Solution 1:[1]

Try this one: (Edit, explanation set json)

function tableText(tableCell) {
    var x =tableCell.innerHTML;
    console.log(x);
    $.ajax({  
    type: 'POST',
    url: 'try.php', 
    dataType: "json",
        data: { x:x },
    complete: function(text){
         return text; }
 });
}

function tableText(tableCell) {
    var x =tableCell.innerHTML;
    console.log(x);
    $.ajax({  
    type: 'POST',
    url: 'try.php', 
    dataType: "json",
        data: { x:x },
    success : function(text){
            $('#MyDiv').html(text);
        }
 });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can retrieve by $_POST['x'] just like a normal post.

For the return in php you need to use echo json_encode(['text'=>'ok']);.

Solution 2:[2]

You are not sending your data correctly with ajax, your ajax should look like this

Edit: Add a sweet alert to display a nice looking message after your insert

function tableText(tableCell) {
    var x =tableCell.innerHTML;
    console.log(x);
    $.ajax({  
        type: 'POST',
        dataType: 'json',
        url: 'try.php', 
        data: {
            x:x
        },
        success: function(text) {
            //SWAL
            Swal.fire(
                'Success!!',
                text,
                'success'
            )
        }
     });
 }


<!-- SWEET ALERT -->
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

and on your try.php file

<?php
$_REQUEST['x'];//here you receive what you send thru ajax

//here goes your insert

echo json_encode('insert was successfull')//this msg is what you will see when you return text
?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2