Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract text from a html element by id and assign to a php variable?

I have this:

<h4 class="modal-title" id="exampleModalLabel"> hello </h4>

and I want to extract the hello word using its id and assign this to a php var but I don't have an idea. If it were an input it would be easier, but I have to use a different element.

like image 266
Rene Limon Avatar asked Nov 27 '22 15:11

Rene Limon


1 Answers

Ok, Rene Limon, as you already know, PHP variables exist on the server side, while the text "hello" exists on the client side. So, what you need is to send the value ("hello" or any other) to the server. It's possible to do it with Ajax. Next file (sendhello.php) gets the value inside the tag and send it to the server. The second file (sendhelloo.php) gets the value and stores it in a variable. To test my code you have to create two text files with the given names, copy-paste the code in them, open your browser and type "localhost/sendhello.php" :

sendhello.php

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
          data : {'action':document.getElementById('my_h4').innerHTML },
          url  : 'sendhelloo.php',
          success: function ( data ) {
            alert( data );
          },
          error: function ( xhr ) {
            alert( "error" );
          }
        });
}
    </script>
  </head>
  <body>
    <h4 id="my_h4"> hellooo </h4>
    <br/>
    <button onclick="myAjax()">Send hello to server</button>
  </body>
</html>

sendhelloo.php

<?php
session_start();
$_SESSION["my_data"] = $_POST['action']; // STORE VALUE IN VARIABLE.
echo "data received = " . $_POST['action']; // RETURN VALUE TO CONFIRM.
?>
like image 176
Jose Manuel Abarca Rodríguez Avatar answered Dec 10 '22 03:12

Jose Manuel Abarca Rodríguez