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

22.9k views Asked by At

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.

3

There are 3 answers

12
Lal On BEST ANSWER

you can use

document.getElementById('exampleModalLabel').innerHTML

This returns hello.

See the fiddle

According to the docs

The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.

To assign this to a php variable, please try

<?php $text="<script>document.writeln(document.getElementById('exampleModalLabel').innerHTML);</script>";

UPDATE after seeing If it were an input would be easier but I have yo use a different element in your question

Use document.getElementById('exampleModalLabel').innerHTML to set the value of a hidden input field and then you can use it as you said in the question.

1
Jose Manuel Abarca Rodríguez On

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.
?>
0
MB_18 On
<?php 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fltNo= $_REQUEST["txt_fltNo"];
} else{


 echo "<form action='' method=POST>
<input type=text name='txt_fltNo'>
<input type=submit value='Get Value'></form>";
}

?>