pass variable javascript to catch with post in php

3

Good afternoon, I found numerous ways to pass javascript to php but no way worked. I thought of a way but I do not know how to effect it, I saw that with ajax would be the only way I think, what I thought was.

I have an information in localstorage, I submit via SELF (same as the self of php that sends to the same page in form) this information that in the case will not generate refresh for a session in php,

javascript > localstorage.getitem () - > ajax without needing another file php > session - > ajax post

    <script>
    function readaccent_color() {
        var accent_color = localStorage.getItem("accent_color");
        if(accent_color) {
            //ajax sem utilizar outro arquivo, tipo self do php para enviar uma variável para o post
$.post('SELF', {}
        } else {
            localStorage.setItem("accent_color", "#6A00FF"); } }
    readaccent_color();
    </script>
    <?php echo $_POST["accent_color"]; ?>

Is there a possibility?

edit

I found this ajax code, but it displays the whole page, all the entire html in the console, not just the value of the localstorage

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script><script>functionreadaccent_color(){varaccent_color=localStorage.getItem("accent_color");
    if(accent_color) {

        jQuery.ajax({
            type: "POST",
            data:  $(accent_color).serialize(),
            success: function(data) {
                console.log(data); } });

    } else {
        localStorage.setItem("accent_color", "#6A00FF"); } }
readaccent_color();
</script>
    
asked by anonymous 05.04.2016 / 18:40

1 answer

1

Friend, I do not know if I understood 100% of your question, but based on the title of the question I will answer you.

<?php
if ($_POST) {
    $teste = $_POST['teste'];
    echo "PEGUEI O VALOR: $teste";
}
?>
<form action="" method="POST" id="formteste">
    <input type="hidden" value="" id="teste" name="teste">
    <input type="text" value="" id="teste2" name="teste2">
    <input type="submit" value="Enviar">
</form>
<script>
    var x = "testando";
    document.getElementById("teste").value = x;
</script>

This code throws a JS variable into a hidden HTML field and takes this value from PHP.

Does this solve your problem?

PhpFiddle

    
05.04.2016 / 19:12