Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

292
Views
Store JavaScript variable in a php variable without page refresh

I've been been through numerous articles on here and tried dozens of variations including ajax. What I want to do is click a button and store the id of that button in a php variable without having to refresh the page.

I've tried using isset and POST and I get some variation of Undefined key array.

Ajax was suggested but when I use ajax I can get the variable stored, but I'm unable to get it into a php variable.

Current setup...

I have an HTML button from which I need the id stored in a php variable so I can use it in another SQL statement. This button is part of an HTML table of MySQL records returned from the db.

<input type='button' value='Edit' name='editbtn' onclick='edit(this.id)' id =  '" . $row['id'] . "'/> 

JavaScript...

function edit(clicked_id){
        var selid = clicked_id;
        var seleid = selid.toString();
        $.ajax({
            type: 'post',
            data: {name: seleid},
            datatype: 'text',
            success: function(data){
                console.log(name);
                alert("Success, data is: " + data);  // This correctly returns the id of the button clicked
            },
     });
} 

The PHP at the top of the page is...

if(isset($_POST['name']) && !empty($_POST['name'])){
    ob_clean();
    $varid = $_POST['name'];
    echo $varid;
    exit; 
}

PHP is not receiving anything. Is there a way to do this? I guess it's a backend/frontend issue?

Note: I have been able to store a JavaScript variable in an HTML tag but I've been unable to use it as part of a SQL statement, even after trimming the tags off of it.

Please help and thank you!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try something like this in your php code :

$data = json_decode(file_get_contents('php://input'), true);
if(isset($data['name']) && !empty($data['name'])){
    ob_clean();
    $varid = $_POST['name'];
    echo $varid;
    exit; 
}
about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!