skip to Main Content

I have spent two days trying to get the issue resolved, but can’t get it done.

I am sending session stored in browser through jQuery AJAX to PHP function so that to save the data to WordPress db.

in session Storage data is stored like this –

enter image description here

so this without success:

var dataStorage = JSON.stringify(sessionStorage.getItem('shoppingCart'));


       $.ajax({
            url: "https://mywebsite.com/wp-admin/admin-ajax.php",
            method: "POST",
            data: 'globalvar='+dataStorage+'&action=myfunction',
             dataType: "json"  
        }).done(function (response) {});

the PHP function is:

if (!function_exists('myfunction')) {

function myfunction() {
    

     
  $object = $_POST['globalvar'];
     
     $decoded_object = json_decode($object);

       //wordpress update db                 
      update_post_meta('42393', 'menu_items_list',  $menu_make_arr);
        
 }

     
             add_action('wp_ajax_myfunction', 'myfunction');
            add_action('wp_ajax_nopriv_myfunction',  'myfunction');
}

I get null in db like this

enter image description here

4

Answers


  1. I think sessionStorage is a reserved keyword so it is creating the issue. You can debug the variable state. This code works for me.

    var dataStorage = JSON.stringify(sessionStorage.getItem('shoppingCart'));
    
    $.post({
      url: "https://mywebsite.com/wp-admin/admin-ajax.php",
      method: "POST",
      data: 'globalvar=' + encodeURIComponent(dataStorage) + '&action=myfunction',
      dataType: "json"
    }).done(function(response) {});

    PHP Code – Just removed a few lines for debugging

    if (!function_exists('myfunction')) {
    
        function myfunction()
        {
            $object = $_POST['globalvar'];
            $decoded_object = json_decode($object);
            print_r($decoded_object);
        }
    
        myfunction();
    }
    
    Login or Signup to reply.
  2. There are several aspects to fix/check:

    1. Is the function defined as you want?

    Your

    if (!function_exists('myfunction')) {
        //...
    }
    

    Checks whether myfunction exists and only executes he inner block if a function by this name does not already exist. You will need to make sure that your function ends up existing and some older function by the same name does not prevent this function from being created.

    2. Is your JSON in proper format?

    You are json_decode‘ing your session data and on the database level you would need to store a value like

    '[{"name":"том","price":259,"count":1},{"name":"жак","price":299,"count":1}]'
    

    into your record. Try to make sure that the way you are storing your JSON is valid in WordPress.

    3. Check the Network tab of your Dev Tools

    You will need to make sure that your request is being sent properly and the JSON you expect to be sent is being sent after all.

    4. Make sure myfunction is being executed after all

    It would not hurt to add some logging to this function to see that it’s being executed.

    Login or Signup to reply.
  3. Firstly, the sessionStorage already stores a string, and the var you are saving into, shouldn’t be called sessionStorage, because it hides the name of the original sessionStorage. Also avoid using "var" alltogether, use const and let.

    const shoppingCart = sessionStorage.getItem('shoppingCart')
    

    Secondly, the data you are sending is URL encoded into the body of the HTTP request (and the JSON part probably gets scewed up).

    encodeURIComponent(shoppingCart)
    

    My recommendation would be to encode everything in JSON. Since you are already "lying to the protocol" with the dataType: "json" you provided (your actual data is application/x-www-form-urlencoded not application/json).

    JS:

    const shoppingCart = JSON.parse(sessionStorage.getItem('shoppingCart'))
    
    $.ajax({
      url: "https://mywebsite.com/wp-admin/admin-ajax.php",
      method: "POST",
      data: JSON.stringify({
        globalvar: shoppingCart,
        action: "myfunction"
      }),
      dataType: "json"  
    }).done((res) => {});
    

    PHP (🤢):

    $json = file_get_contents('php://input');
    $body = json_decode($json);
    
    $func = $body->action;
    $data = $body->globalvar;
    
    Login or Signup to reply.
  4. To read application/json in php we can use php://input

    So the code will be like this

    function myfunction() {
            $rawData = file_get_contents("php://input");
            $json = json_decode($rawData);
    
            $object = $json->globalvar;
    

    To send application/json from browse to php we can use JSON.stringify

    So the code will be like this

    sessionStorage.setItem("shoppingCart", JSON.stringify([{"name": "name1"},{"name": "name2"}]));
    
    var dataStorage = JSON.parse(sessionStorage.getItem('shoppingCart'));
    
    $.ajax({
        url: "test1.php",
        method: "POST",
        data: JSON.stringify({ "globalvar": dataStorage, "action" : "myfunction"}),
        dataType: "json"  
    }).done(function (response) {
        console.log(response)
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search