I wrote a plugin in wordpress. It has some .js
files and .php
files and I receive data from db by calling ajax method in jquery.
when I use wp_enqueue_script
and add them to the wordpress, it works fine. but my question is how to use wp_ajax
method instead raw ajax call.
here is my code:
in my.js file:
$(document).ready(function(){
$('#submit').on('click', function(){
var name = $('input[name=name]').val();
var price = $('input[name=price]').val();
var goods = $('input[name=goods]').val();
var date = $('input[name=delivery]').val();
if( name.length > 1 && price.length >1 && goods.length > 1 && date.length >1){
var obj = {
name: name,
price: price,
goods: goods,
date: date
};
var btn=$(this).button('loading');
$.ajax({
url: "service.php",
method: "POST",
data: obj,
dataType:'json',
success: function(e){
$('#alt-div').html('<div id="alert" class="alert alert-info alert-dismissable"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>'+e.Comment+'</div>');
},
error: function(){
alert('error');
}
})
}
});
});
in service.php file:
$name = $_POST['name'];
$goods = $_POST['goods'];
$date = $_POST['date'];
$price = $_POST['price'];
$tmp = explode('/', $date);
$jy = $tmp[0];
$jm = $tmp[1];
$jd = $tmp[2];
$query = "INSERT INTO products (name, goods, price, date) VALUES ('$name',
'$goods', '$price', '$time')";
results = mysql_query($query);
$inserted_id= mysql_insert_id();
if ($results > 0)
echo json_encode ([
'status'=>1,
'Comment'=>"ok"]);