Pass the Javascript variable to PHP using AJAX Jquery

a very basic example for passing the javascript variable to a php page is explained here :

index.php

<html>
<head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript">
        var var_data = "Hello World";
        $(document).ready(function() {
            $('#sub').click(function() {
                $.ajax({
                    url: 'response.php',
                    type: 'GET',
                    data: { var_PHP_data: var_data },
                    success: function(data) {
                        $('#result').html(data);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        //case error                    }
                });
            });
        });
    </script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<p id="result"></p>
</body>
</html>

response.php

<?php
$test = $_GET['var_PHP_data'];
echo "variable is : .$test";
?>


 OUTPUT :

  

4 comments:

  1. Great insights! I really appreciate how clearly you’ve outlined the topic. Your post has provided some valuable clarity. Thanks for sharing!

    ReplyDelete
  2. You can pass a JavaScript HostMyCode variable to PHP using AJAX in one line like this:







    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete