How to do an Xmlhttprequest to send values to the page itself?

Asked

Viewed 920 times

3

What do I have: I created several buttons through PHP and to distinguish them I used the variable $botoes_criados.

So I have the variable value $botoes_criados in PHP that is passed to a button as follows:

echo("<li><a href='#'  onclick='pagination($botoes_criados)'>$botoes_criados</a></li>");

Next I made a javascript to receive through the function pagination() receives the variable $botoes_criados through the parameter.

What I intend to do: I want to pass the value of this variable back to PHP so I know which button was clicked.

What I tried to do:

  <script>
            function pagination(botao)
            {
              alert(window.location.href );
              var xhttp = new XMLHttpRequest();
              xhttp.open("GET", window.location.href, true);
              xhttp.send("b=".botao);            
            }
   </script>

In PHP I have the following code to try to receive the variable value

Echo($_GET['b']);

In short: All I want to do is make an Xmlhttprequest for the page itself so that I can collect the information of this variable. If you don’t understand my question comment I edit.

2 answers

2


Use <a href='#' onclick='pagination($botoes_criados)'>$botoes_criados</a> to reload the page as you suggested in the reply doesn’t make much sense.

There’s an answer that may be useful to read. In your case you have two options for me:

  • reload the page completely
  • use ajax to fetch new content to not reload the page

In your answer you use the first option. In this case, if you are going to reload the page or you don’t need Javascript, you could simply do

<a href='?b=$botoes_criados'>$botoes_criados</a>

If you want to avoid loading the page again, then ajax as referees in the question is the tool to use. And in that case send the data to PHP, and it should return the new content.

var request = new XMLHttpRequest();
request.open('GET', window.location.pathname + '?b=<?php echo $botoes_criados; ?>', true);
request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Successo!
    var data = request.responseText;
  } else {
    // Deu erro

  }
};
request.send();

In PHP you need to use get as you have in the question, process and decide what to send back.

1

I solved the problem as follows

<script>

         function pagination(botao)
         {
             window.location.href = "?b=" + botao; 
         }

</script>

Browser other questions tagged

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