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 –
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
4
Answers
I think sessionStorage is a reserved keyword so it is creating the issue. You can debug the variable state. This code works for me.
PHP Code – Just removed a few lines for debugging
There are several aspects to fix/check:
1. Is the function defined as you want?
Your
Checks whether
myfunction
exists and only executes he inner block if afunction
by this name does not already exist. You will need to make sure that yourfunction
ends up existing and some olderfunction
by the same name does not prevent thisfunction
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 likeinto 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.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.
Secondly, the data you are sending is URL encoded into the body of the HTTP request (and the JSON part probably gets scewed up).
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:
PHP (🤢):
To read
application/json
in php we can usephp://input
So the code will be like this
To send
application/json
from browse to php we can useJSON.stringify
So the code will be like this