How to make an XMLHTTPRequest to send values to the page itself?

3

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

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

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

Then 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 get the value of the variable

Echo($_GET['b']);

In short: All I want is to make an XMLHTTPrequest for the page itself so I can collect the information from that variable. If you do not understand my question, I will edit it.

    
asked by anonymous 02.10.2015 / 10:58

2 answers

2

Using <a href='#' onclick='pagination($botoes_criados)'>$botoes_criados</a> to make the page reload as you suggested in the answer does not make much sense.

an answer that might be helpful to read . In your case you have two options in my view:

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

In your answer you use the first option. In that case, if you're going to reload the page or 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 you refer to in the question is the tool to use. And in that case you 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.

    
02.10.2015 / 23:56
1

I solved the problem as follows

<script>

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

</script>
                                    
02.10.2015 / 11:47