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

227
Visualizações
Button to change value in SQL without any redirection

Trying to use Javascript to pass the value from a button to execute a PHP Script (The script simply changed a boolean column to 1 / True.

However i cannot get the code to work, i am not sure if its my Formatting, but i am not very familiar with Javascript

i am simply trying to change the value in the SQL Database on a column without any redirection.

index.php

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script language="javascript">
    $("body").on("click","button", function(ev){
        ev.preventDefault(); // prevent submitting a form ...
        let data={id: $(this).data("id")}
        $.post("viewed.php",data)
            .done(function (result) {
                console.log("Message:",result);
            });
    });
</script>

My Button index.php

            <div><button name="Delete" data-id='<?echo $data['orderReference']?>'">Delete</button></div>

and Viewed.php

$orderID = $_POST['id'] ;

if ($_POST)
{
    try {
        $sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($orderID) ";
        $resultOrderupdate = $products->conn->query($sqlOrderviewed); // Execute Statement
        echo $count = $resultOrderupdate->rowCount();
    }  catch
    (PDOException $e) {  // If error in SQL
        echo "One or more errors occurred saving to database This transaction will be rolled back:" . $e->getMessage();  // Display Message on End Point
        //  $products->conn->rollback();       // Rollback SQL
    }
}

I am aware of the SQL Injection in this example, this is not production just trying to get an example working

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

To do this I would suggest making REST API type behaviour in your PHP that accepts JSON (as an example) which you can define with headers. So your JavaScript can stay mostly the same, just make sure you are pointing to the correct URL. But I think your PHP should look more like this:

    <?php 
      // Headers
      header('Access-Control-Allow-Origin: *');
      header('Content-Type: application/json');
      header('Access-Control-Allow-Methods: POST'); //maybe make this an update to be Semantic with the SQL operation you are doing
    
      // Get raw data from the post you made in JavaScript
      $data = json_decode(file_get_contents("php://input"));
      $id = $data.id;

      // Use the data in your SQL
      $sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($id) ";

    ?>

If you need more information on creating APIs with PHP I suggest these resources:

  • https://www.youtube.com/watch?v=OEWXbpUMODk
  • https://shareurcodes.com/blog/creating%20a%20simple%20rest%20api%20in%20php
  • https://github.com/bradtraversy/php_rest_myblog

I am not sure that $(this).data("id") is getting the data you want. I assume you want to get the value of data-id in your button? If so I would change your JavaScript to something more like this:

<script language="javascript">
    $("body").on("click","button", function(ev){
        ev.preventDefault(); // prevent submitting a form ...
        let id = ev.target.getAttribute("data-id");
        let data={id: id};
        $.post("http://localhost:{port}/viewed.php",data)
            .done(function (result) {
                console.log("Message:",result);
            });
    });
</script>

I hope this helps!

P.S this is how I might have written the JS for this, I just find it a bit more readable (Not tested, just written in the MD editor while answering the question):

let buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
  button.addEventListener("click", (e) => {
    e.preventDefault();
    
    let id = e.target.getAttribute("data-id");
    
    let data = {
      id: id
    };
    
    $.ajax({
      type: 'POST',
      url: '/viewed.php',
      data: data,
      success: function(result){
        console.log( "result: " + result );
      }
    })
  })
});
about 4 years ago · Santiago Trujillo 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