Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda