2

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

7
  • Have you checked what is sent to PHP with the browser developer tools? Note that when you send data as a string you should encode it: data: 'globalvar='+encodeURIComponent(sessionStorage)+'&action=myfunction' Commented Jan 8, 2023 at 14:47
  • 1
    Change your variable name sessionStorage to some other like dataStorage or whatever you want. var dataStorage = JSON.stringify(sessionStorage.getItem('shoppingCart')); Commented Jan 8, 2023 at 14:54
  • Yes. A logical name for the sessionStorage variable would be shoppingCart. Commented Jan 8, 2023 at 14:55
  • @KIKOSoftware , i have added encodeURI but still get NULL, how can i check what is sent to PHP ? Commented Jan 8, 2023 at 15:05
  • 1
    See: What are browser developer tools? You cannot write code without it. Commented Jan 8, 2023 at 15:14

4 Answers 4

1

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;
Sign up to request clarification or add additional context in comments.

5 Comments

dont understand php part , tried it but get ajax error 400
I agree that posting JSON is a good idea.
Which part requires clarification? $func will contain the string "myfunction" $data will contain the shopping cart object
$json = file_get_contents('php://input') this one , but anyways a get ajax error 400, in response header is 0
file_get_contents('php://input') takes the body of the request and returns it as a string. $body = json_decode(file_get_contents('php://input')); this turnes the aformentioned string into a PHP object/map that you can use like your regular old JS object. Btw this isn't EVERYTHING you should have in your php. Just use $func and $data instead of $_POST['action'] $_POST['globalvar']
1

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)
});

5 Comments

This exact answer has already been posted here 38 minutes ago. What does your answer add? Of course you are free to post any answer you want, just wondering if you didn't notice this?
no I did not notice, I was typing the code in Notepad++ and xampp
Well, it is a good answer. 🙂
@DickensAS Ajax error 400 , header response 0
it should be related to wordpress, so we need to understand how to satisfy wordpress
0

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.

4 Comments

1) Function doesnt exist anywhere else. 2) when i dont json_decode it i get "[{\"name\":\"том\",\"price\":259,\"count\":1},{\"name\":\"жак\",\"price\":299,\"count\":1}]" 4) its execute since i can get back the variable to js and console log it
@Andy what happens when you execute it without json_decode?
i get this in my db "[{\"name\":\"том\",\"price\":259,\"count\":1},{\"name\":\"жак\",\"price\":299,\"count\":1}]"
@Andy how did you initialize $menu_make_arr?
0

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();
}

4 Comments

@Shoaib_Ijaz tried this one but still get NULL
Check the Network tab of your Dev Tools. You can debug the request that you are sending.
You code says you're posting JSON, but you're actually posting an URL query string. Will that work?
Yes, I have tried with the provided PHP code, Now added the PHP code as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.