I have 2 Ajax call the first is working but when it send the data to other the file send_data.php
and when I try to run any wordpress function it doesn't work!
This's the first ajax call ok now the data sent to send_data.php
file when I try to run any wordpress function like this add_post_meta(2, 'dropbox', 'Senddataphp', false);
it prints this error what I want to do is pretty simple just get the data from ajax insert into wp database but I've no idea everytime I work with js with php problems like this happens
caught Error: Call to undefined function add_post_meta() in C:\xampp\htdocs\wordpress\wp-content\plugins\Dropboxapi\includes\send_data.php:17
Stack trace:
First Ajax code
$.ajax({
type: "POST",
url: 'wp-content/plugins/Dropboxapi/includes/send_data.php',
data: {
req: JSON.stringify(dropbox_links)
},
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
console.log("Data recived: " responseData);
console.log("First Ajax" dropbox_links);
}
});
Second Ajax code here I tried to execute a function that take the sent data and insert into database but it doesn't work, dropbox.php
file is the main file of the plugin
$.ajax({
type: "POST",
url: 'wp-content/plugins/Dropboxapi/dropbox.php',
data: {
functionname: 'printdata2'
},
success: function(obj, textstatus) {
if (!('error' in obj)) {
var yourVariable = obj.result;
console.log("SEc Ajax" dropbox_links yourVariable);
} else {
console.log(obj.error);
console.log("SEc1 errr Ajax" dropbox_links
yourVariable);
}
},
error: function(msg) {
console.log(
" errrnot sure what to ask for here to check issue"
msg);
}
});
CodePudding user response:
When using ajax in WordPress the file that stores the function you want to run is not called directly. Instead admin-ajax.php
is called, and callback function is added in 'action'
.
First create a function and add your add_meta_box
inside it, then add wp_ajax action hooks like the following. Remember that every function which is going to be called by ajax request must end with wp_die().
function printdata2() {
add_post_meta(2, 'dropbox', 'Senddataphp', false);
wp_die();
}
add_action( 'wp_ajax_nopriv_printdata2', 'printdata2' );
add_action( 'wp_ajax_printdata2', 'printdata2' );
Next use wp_localize_script() to pass admin_url('admin-ajax.php')
to javascript.
function load_script() {
wp_enqueue_script( 'your-js', get_template_directory_uri() . '/js/your-js.js', array('jquery') );
wp_localize_script( 'your-js', 'ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')) );
}
add_action('wp_enqueue_scripts', 'load_script');
Now in your javascript file call ajaxurl
in url
and the callback function name in action
.
$.ajax({
url: ajax_object.ajaxurl,
data: {
action: 'printdata2'
},
success: function(obj, textstatus) {
// obj goes here...
},
error: function(msg) {
console.log(msg);
}
});