• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

183
Views
How to get variable from JavaScript to PHP

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 ??

about 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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']);.

about 3 years ago · Juan Pablo Isaza Report

0

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
?>
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error