Home > Back-end >  js object sending through ajax
js object sending through ajax

Time:01-09

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

CodePudding user response:

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 (

  • Related