Value of div being sent dynamically to php page

Asked

Viewed 47 times

2

I have a simple game that ultimately generates a score. The score appears this way:

<div id='cScore'>0</div></div>

I would like at the moment that this div is called that this score be sent also to the page processes.php, using a form for example.


More details: what I really need is to save this value in the database along with the name of the user of the page, I thought to send to a page "processes.php" because there I could develop it.

2 answers

1


You do not need a form to send this value to the back end, for this you can use Ajax to know about it can see more in the documentation here.

1 - If you already have the value you want to pass to the back-end, and this value is not in an input, but rather, in text form, you can take this value through the jQuery method text(), learn more here.

2 - Then just mount Ajax, sending the value via a request to a url that receives and treat this value.

$(function() {

  $('#envio').on('click', function() {
    let pts = $('#cScore').text();
    
    $.ajax({
      method: "POST",
      url: "processa.php",
      data: pts	
    }) 
    .done(function(pts) {
      setTimeout(function(){
        alert( "Pontuação: " + pts );
      },2000);	
    })
    .fail(function() {
      alert("Não foi enviado mas o valor é: " + pts);
    })
  });
  
})
#cScore {
  display: inline-block;
  background-color: #999;
  color: #FFF;
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  Valor total da pontuação:
  <div id='cScore'>100</div>
</div>

<button id="envio">Enviar pontuação</button>

OBS: O meu exemplo vai retornar o FAIL, pelo motivo de que a url não foi encontrada.

  • Friend, very grateful is exactly what I needed, I made some simple adaptations to my code and is already working. Big hug !

  • Great guy, success there!

  • If somehow the answer helped you to resolve your doubts, consider accepting it as an answer by clicking on this icon ✔.

-1

  • val() is for input and not for picking up texts only. You can learn more here https://api.jquery.com/val/#val.

Browser other questions tagged

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