简体   繁体   中英

Use jQuery for defining variable in PHP

I want to JQuery while defining a variable in PHP.

Suppose I have the following index.php file:

<!DOCTYPE html>
<html>
<head>
    <title>Page</title>
    <script type="text/javascript" src="../../../resources/js/common/jquery-latest.min.js"></script>
</head>
<body>
    <div class="bigdaddy">
        <div class="daddy">
            <header class="main"></header>
            <main>
                <aside>
                </aside>
                <article>
                    <div class="div1">
                        Sample1
                    </div>
                    <div class="div2">
                        <div> //Child 1
                            Sample2
                        </div>
                        <p> //Child 2
                            Sample3
                        </p>
                    </div>
                    <?php
                        // the code
                    ?>
                </article>
            </main>
            <footer class="main"></footer>
        </div>
    </div>
</body>
</html>

Questions:

  • How can I select <div> with attribute and attribute value class="div1" to get its node/inner text?
  • How can I select <p> child of <div class="div2"> its node/inner text?
  • Is it even possible to use jQuery in PHP?

Both questions are using jQuery

I thought of

<?php
    $answer1 = $('div[class="div1"]').html();
    echo $answer1;
    $answer2 = $('div.class="div2"').children('p').html();
    echo $answer2;
?>

But it didn't work.

Expected result should be:

Sample1 Sample3

EDIT: I can't use AJAX.

You can use AJAX to send the data you want to the server, and handle the rest using PHP:

var answer1 = $('.div1').text();
var answer2 = $('.div2').find('p').text();
$.ajax({
  type: 'post',
  url: 'your_php_script.php',
  data: {
    answer1 : answer1, answer2: answer2
  },
  success: function(response_from_php_script) {
    console.log(response_from_php_script);
  }
});

And in your PHP script you can get the value of the paragraph you need like this:

 $answer1 = $_POST['answer1'];
 echo $answer1;
 $answer2 = $_POST['answer2'];
 echo $answer2;

Of course you will have to sanitize the post values if you want to insert it in the database, but that's a whole new thing.

I hope this will get you started.

You can read more about AJAX here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM