Hi i have this script when link is click the data will be saved into the database. Now my problem is after clicking the link this is the error:
ReferenceError: ajax_object is not defined
This is my script below in single-knowledge page
<script type="text/javascript">
jQuery(document).ready(function($) {
$(".dL").click(function(){
var name = ($(this).attr('name'));
var urldata = ($(this).attr('href'));
var data = {
'action': 'my_action',
'name': name,
'urldata': urldata // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
// alert('Got this from the server: ' + response);
alert(response);
});
});
});
</script>
This is my function.php script below
function my_action(){
global $wpdb; // this is how you get access to the database
$name = $_POST['name'];
$url = $_POST['urldata'];
$wpdb->insert('list_of_downloads', array(
'name' => $name,
'filename' =>$url
));
// wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // <= this one
The problem is this one ajax_object
Can someone help me figured this thing out? Any help is muchly appreciatd.
TIA
答案 0 :(得分:0)
I don't see anywhere that you declared 'ajax_object'. You can use it like below, if your server side code on file 'function.php':
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post("function.php", data, function(response) {
// alert('Got this from the server: ' + response);
alert(response);
});
答案 1 :(得分:0)
You are getting error because you didn't declare that variable. Since you are trying to call function through ajax using wordpress, so i would like to share what i have done recently.
Add following script in your function.php which will add the admin-ajax.php
url in the header.
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_enqueue_script( 'add-order-front', get_template_directory_uri() . '/js/ajax.js' );
wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'add-order-front' );
}
Then use following ajax script for calling that function.
jQuery(document).on('click','.dL',function(){
var name = ($(this).attr('name'));
var urldata = ($(this).attr('href'));
jQuery.ajax({
type : 'POST',
url : MyAjax.ajaxurl,
data: {action: 'my_action','name': name,'urldata': urldata},
dataType:"json",
success:function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
});
The above script is working for me.