I normally use javascript ajax and everything works fine, but wordpress requires jquery ajax which i am not familiar with.
Why are the variables described in the following code are not defined?
var option = "'USER_ID': 'my id is 32',"
var note = "'this is my first note'";
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
option //this does not work. <--- WHAT DO YOU MEAN DOES NOT WORK?
'USER_NOTE': note //this does not work. <--- WHAT DO YOU MEAN DOES NOT WORK?
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
4
Answers
Define it as a function and wrap it in a closure passing the context in.
Or, just move everything into jQuery.ready
This is because your
data
json object is not properly defined. You need to change your option definition to the valid json object:to
And add it a bit different way, so it would get merged properly:
That should fix your problem.
Here is a codepen with your question: https://codepen.io/geoidesic/pen/wvoEdeN
Here is the code:
If you view the console. You can see that there is no problem with any undefined variables. If you view the network tab you can see that the POST request is sent.
This should also serve as an example of how better to formulate your questions in a way in which people can actually help you, i.e. by using CodePen or similar.