pass javascript variable to catch with php post

Asked

Viewed 4,285 times

3

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

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

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"]; ?>

there is this possibility?

Edit

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

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function readaccent_color() {
    var accent_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>

1 answer

1

Friend, I do not know if I understood 100% 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 plays a JS variable for an Hidden field in HTML and takes this value with PHP.

That solves your problem?

Phpfiddle

  • but then I’d have to send a Ubmit to pick up the variable? in this case, how to do this in ajax without needing to lynch another file that is the default and in the case of the second code, it does not take all the html of my site, only the variable, that is, it would improve that code from there, its works, but would have an input on the page and would have to dr.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.