Pass value from a button to a php variable through POST using AJAX

Asked

Viewed 47 times

1

Hello I would like to ask a help, I started using ajax recently and I am having a problem that I could not identify with my little knowledge. I am developing a project that I want to take the value of a button as soon as it is pressed and return this value to the same page in a variable $_POST using AJAX. When the problem starts, I was able to develop the script but when returning this value it does not send to $_POST, it is shown in the "Network" part of the browser and also in the console.log() but when I try to var_dump in php the value is always Empty. Follow an image of what is happening:inserir a descrição da imagem aqui

Below the code: panel.php

    <div class="col bg-light ">
        <div class="shadow-lg p-4">
            <?php var_dump($_POST); ?>
            <?php
            while ($resultcatglist = $categolist ->fetch_array()){
            ?>
              <button  type="button" class="btn btn-outline-success btnenviar" value="<?php echo 
                $resultcatglist["id"] ?>">
                <?php echo $resultcatglist["nome"];?>
              </button>
         <?php } ?>
 </div>
</div>

Script:


$( ".btnenviar" ).click(function() {
  var btnvalue = $(this).val();
$.ajax({
  method: "POST",
  dataType:"html",
  url: "painel.php",
  data:{"valor":btnvalue}
})
  .done(function( data ) {
    console.log( "Data Saved: " + btnvalue );
  });
});
  • Try a console.log($(this)) and see if it’s getting the right element.

  • Yeah, you came right back.

  • My suggestion is to separate the script for this ajax request (e.g. processes Ajax.php from the script. panel.php. In this processAjax you insert your logic and return a json response. In the ajax call configs, dataType leaves it as json ( which refers to the expected response type). In this post of the OS in English there is an example that can help you https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php I am on mobile and it is difficult to write an example

  • I tried to do it this way and it still didn’t, it’s like I wasn’t sent. I tried to read the Jquery documentation but I confess that I am still lost I believe that something is missing. Note: when I give a console.log(date) it returns my entire html page... and when I give that date in some $_POST div it gets the value.

No answers

Browser other questions tagged

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