Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda