Improve code to only get value from localstorage

Asked

Viewed 1,057 times

2

I have the following code:

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

How do I get this code to pick up the value below:

var accent_color = localStorage.getItem("accent_color");

And instead of console.log send to a php post?

The problem is that the variable data is taking the whole HTML, not only the value of localstorage, see the photo:

alert(data) mostra todo o código html, quero apenas o conteúdo de localstorage

So much so that if I put this:

if($_COOKIE["data"]) { echo $_COOKIE["data"]; }

Nothing appears.

  • "and instead of sending console.log to a php post" - I don’t know what you mean. Ajax already sends POST to PHP, but did not give any url address. What has the variable accent_color?

  • in the accen_tcolor variable comes a localstorage, as I do to put the localstorage variable of accent_color inside a variable instead of the console.log and take the php post normally

  • localStorage is used for browser session, which has to do with your ajax request? localStorage.setItem('chave', valor); localStorage.getItem('chave');

  • for an ajax request, I did not understand?

  • just do this: localStorage.setItem('accent_color', $('#accent_color').serialize()); and then: on the other page: var serie = localStorage.getItem('accent_color');

  • @Ivanferrer I need to pass the content of localstorage to a php variable, in a localstorage accent_color has a value defined by the user that can be the same in another browser but this value is from each browser, with this value in localstorage I want to move to php, in case I saw how to do in ajax but the idea of having one more file didn’t cheer me up, I just need localstorage to enter a javascript variable and pass to a php variable, as javascript runs in browser and php on server, vi ajax is the solution, but, how to do this?

Show 1 more comment

2 answers

0

You can create a input of the kind hidden and receive the form data as POST.

<input type="hidden" value="valor" name="accent_color" id="accent_color">

Then just create a script to make the input capture the value.

var accent_color = localStorage.getItem("accent_color");
$('input #accent_color').attr('value',accent_color);
  • yes, but instead of console.log I put what to ask with php after? or just take "data"?

  • @flourigh O console.log(data) is just a way to bring the data that has been processed on your php page, back to Ajax. In simpleton terms, everything you write there in php will go back to your ajax in that date variable. But instead of console you could return one alert(data) or click on a div $('div .cores').html(data) there goes your need.

  • but then the page error comes all in Alert(see image) or the console is in ajax? and how not to do that, make it take only the value of the localstorage?

0

See here a summary of how to "capture" javascript data and send it to php and how to recover this data in php

    Recupere os dados em PHP oriundos do Javascript
    $arrayPost = $_POST; //Se foi serializado ou não
    $arrayPost = json_decode($_POST["meuJSON"], true); //Se foi enviado JSON

    //Codigo php que vai processar os dados e mandar de volta para o JS
    $arrToJSON = array(
    "dataPHPtoJs"=>"yourData",
    "asYouWant"=>"<div class=\".class1\">soemting</div>"    
    );  
    return json_encode(array($arrToJSON));




//Javascript que vai mandar algo para o php
$(document).on("event", "#idElement", function(){
     //Vc pode usar 
     var dt={ 
              ObjEvn:"btn_Login",
              dataJsToPHP: $("#txt_EmailLogin").val(),

            };

    //Ajax      
     var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
                            url: "yourServer.php",
                            type: "POST",
                            data: dt,
                            dataType: "json"
                        });

    //Ajax Done catch JSON from PHP 
        request.done(function(dataset){
            for (var index in dataset){ 
                 dataPHPtoJsJS=dataset[index].dataPHPtoJs;
                 asManyasYouWantJS=dataset[index].asYouWant;
             }

             //JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response
             if(dataPHPtoJsJS){
                $( "#idYourHtmlElement" ).removeClass( "class1" )
                $( "#idYourHtmlElement" ).addClass( "class2" )
             }


     }); 

    //Ajax Fail 
        request.fail(function(jqXHR, textStatus) {
            alert("Request failed: " + textStatus);
        }); 
}

Note: If you are going to serialize use this function:

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

and if you send JSON the whole function would look like this:

var meuJson = JSON.stringfy($(form).serializeObject());

Browser other questions tagged

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