0

How can I store this javascript data to a php variable on the same page. This is what I've tried.

index.php

PHP

//Receiving Data
$ajax_data = $_POST['data'];
echo $ajax_data;

JS

    var fname = "Mike";
    var form = {"first_name":fname};

    person = JSON.stringify(form);

    $.ajax({
        url: "index.php",
        method: "POST",
        dataType: 'JSON',
        data: ({
            data: person
        }),
    });
</script>
5
  • your question gives the impression that you did not realize that the pages sent to a browser are multiplied by as many Internet users who visit this initial page, it is the same for the variables. Commented Nov 25, 2020 at 4:55
  • is there any other way to pass a js data and store to a php variable rather than using ajax? Commented Nov 25, 2020 at 4:57
  • the other way is sending a <form>, but it implies a new page load. You are talking about a client(JS) <-> server (php) relationship... Commented Nov 25, 2020 at 5:02
  • can you give me an idea how to do it Commented Nov 25, 2020 at 5:06
  • shure: developer.mozilla.org/en-US/docs/Web/HTML/Element/form Commented Nov 25, 2020 at 5:11

1 Answer 1

1

Store data through JavaScript cookie and get through PHP

<script>
var fname = "Mike";
document.cookie = 'first_name=' + fname; </script>  

<?php echo $_COOKIE['first_name'];
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.