Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a PHP variable in JavaScript in this case?

in following case I want my script to running post.php. That works fine. But while running the post.php file, in it a variable should be created with content "1". And I want to get the variable in my javascript back. So there are two files:

part of index.php

<script type="text/javascript">
        function post()
        {
            var message = $('#message').val();
            $.post('post.php', {postmessage:message},
            function(data)
            {
                $('#result').html(data);
            });
        }
</script>

and then I have the post.php where the variable with content "1" should be created.. Then I want to get back it in index.php in the script. How can I do this?

Why do I want to do this? When in post.php a variable with content "1" will be created, >>I think it has to be a $_POST variable?<< then I want to clear my form field because the action in post.php went successfully.

like image 520
Kadnick Avatar asked Nov 17 '25 06:11

Kadnick


1 Answers

One of the ways to do so is to return JSON encoded variable from your post.php file. Response from your file is in the data variable in the callback function parameter of your $.post method after the server responds.

Take care, that you need to also parse this data from JSON into plain JS on frontend side so you can work with that. The code may look like this:

Frontend side - index.php:

<script type="text/javascript">
    function post()
    {
        var message = $('#message').val();
        $.post('post.php', {postmessage:message},
        function(data)
        {
            var parsedData = JSON.parse(data);
            $('#result').html(parsedData);
        });
    }
</script>

Backend side - post.php:

<?php
// get sent variable
$message = $_POST['postmessage'];

// do what you need to do with that

// consider your processing resulting in success
$success = true;

echo json_encode($success);
?>
like image 110
Jakub Hubert Avatar answered Nov 19 '25 20:11

Jakub Hubert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!