Take the value of a javascript button and run php function

Asked

Viewed 312 times

0

Hello!

I have a button html with a value which is generated from a foreach, following example:

   foreach ($array_informado as $rows){
            if (mysqli_num_rows(consulta_imei($rows))>0) {
                $valores_consulta = mysqli_fetch_row(consulta_imei($rows));
                if ($rows = $valores_consulta[0]) {
                    if ($valores_consulta[21] == 0) {
                        echo "<tr class='table-success'>";
                        echo "<th scope='row'> 
                        <button type='submit btn-sm' id='liberar' value='".$rows."' onClick='capturaimei(this.value);' class='btn btn-success'>Lib</button>
                        <button type='submit btn-sm' id='bloquear' value='".$rows."' onClick='capturaimei(this.value);' class='btn btn-warning'>Bloq</button>
                        ";
                    }

By clicking on any of these buttons (release or block) I have to capture the field value and call a function in php by running a UPDATE in the database with this value as a parameter.

In this case, the javascript function is giving an Alert:

function capturaimei(imei) { alert(imei); }

These are my updates, where they receive the code as parameter:

function lock_travapda($imei){ // bloqueia os aparelhos que vem por parametro
include('con.php');
include_once('con.php');
$query_block_travapda   = "update jupiter_controle set travapda = 1 where imei in ($imei)";
$rs_block_travapda      = mysqli_query($con,$query_block_travapda) or die(mysqli_error($con));
mysqli_close($con);

The question is this, how can I call this function locktravapda passing through parameter the captured code with the value button?

Follow prints of the visual part to facilitate understanding: Imagem dos buttons com o retorno no alert

Grateful

  • If it is by AJAX, search on the site a lot of material on the subject.

1 answer

0

For a Javascript to run a ". PHP" it is necessary to use the API Fetch javascript.

This code demonstrates how you can use Fetch which is a native Javascript API to run a . PHP

function capturaimei(imei) {
  // Formulário onde iremos inserir dados que serão enviados para o PHP
  var formdata = new FormData();
  // Estamos inserindo no formulário o valor que pegamos por parâmetro
  formdata.append("imei", imei);

  // Opções da requisição que será feita ao arquivo PHP.
  var requestOptions = {
    method: 'POST',
    body: formdata,
    redirect: 'follow'
  };

  // URL do arquivo PHP que contém a função a ser executada.
  // Lembre de alterar a URL de acordo com o seu projeto 
  fetch("http://localhost/locktravapda.php", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    // Se ocorrer algum erro durante o envio o JavaScript chama essa função
    .catch(error => console.log('error', error));
}

Now you need to create a separate PHP file for the function you want to run in PHP.

In this example I created a file called locktravapda.php where I will put the logic that will be executed when Javascript calls this file. PHP

<?php

// Salva o valor que foi enviado pelo JavaScript em uma variável.
$imei = $_POST['imei'];

// 
function lock_travapda($imei){ // bloqueia os aparelhos que vem por parametro
    include('con.php');
    include_once('con.php');
    $query_block_travapda   = "update jupiter_controle set travapda = 1 where imei in ($imei)";
    $rs_block_travapda      = mysqli_query($con,$query_block_travapda) or die(mysqli_error($con));
    mysqli_close($con);
}

// Chama a função passando como parâmetro o valor que foi enviado pelo JavaScript
lock_travapda($imei);
  • Thank you, I will test tomorrow morning !!

  • Good morning, can you tell me how I test if the formdata is correct?

  • I ask because I am not able to print the value of the variable $Imei = $_POST['Imei']; la on the screen locktravapda

  • Good afternoon, for you to test if the values are being passed correctly to PHP just use browser debugging, if you are using Google Chrome press the F12 key and then click on the Network tab, there will be listed all the requests made, then you should click on the request made to the PHP file and right after clicking on the Headers tab and go down until you find Form Data, because there will be listed all the parameters that were sent. If you still have doubts see this video. I hope I helped good luck.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.