我试图在wordpress中以表单形式输入插入数据,并希望使用ajax来实现这一点。如果没有ajax,它工作得很好,但当我使用ajax时,按submit按钮得到的结果为0,数据不会插入到数据库中。下面是我的代码。
Html代码位于表单标记之间,如下所示
<form id="insertform" action="" method="post">
<input id="user" style="height: 30px;" name="user" type="text" />
.
.
.
<button id="Submit" type="submit">SUBMIT </button>
</form>
php代码
function wp_insert(){
if(isset($_POST[\'skillname\'])!= \'\' && $_POST[\'Address\']!= \'\'){
$user_info = wp_get_current_user();
$username=$user_info->user_login;
//insert to database
If($_POST[\'Submit\']) {
// run validation if you\'re not doing it in js
global $wpdb;
//assigning textbox values to variables
$yourname=$_POST[\'user\'];
$lat=$_POST[\'latitude\'];
$long=$_POST[\'longitude\'];
$address=$_POST[\'Address\'];
$city=$_POST[\'City\'];
$state=$_POST[\'State\'];
$country=$_POST[\'Country\'];
$zip=$_POST[\'zipcode\'];
$skillname=$_POST[\'skillname\'];
$yourself=$_POST[\'yourself\'];
$email=$_POST[\'email\'];
$phone=$_POST[\'phone\'];
if($wpdb->insert(
\'wp_store_locator\',
array(
\'secretcode\' =>$username,
\'sl_description\' => $yourname,
\'sl_latitude\' => $lat,
\'sl_longitude\' => $long,
\'sl_address\' => $address,
\'sl_city\' => $city,
\'sl_state\' => $state,
\'sl_country\' => $country,
\'sl_zip\' => $zip,
\'sl_store\' => $skillname,
\'yourself\' => $yourself,
\'sl_email\' => $email,
\'sl_phone\' => $phone )) == false) wp_die(\'Database Insertion failed\'); else echo \'Database insertion successful\'; exit();
}
}
}//end of function
Jquery的排队代码
add_action( \'init\', \'add_insert\' );
function add_insert(){
add_action( \'wp_ajax_wp_insert\', \'wp_insert\' );
add_action( \'wp_ajax_nopriv_wp_insert\', \'wp_insert\');
// register & enqueue a javascript file called globals.js
wp_register_script( \'globalss\', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( \'jquery\' ) );
wp_enqueue_script( \'globalss\' );
// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( \'globalss\', \'yess\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
Jquery文件ajaxinsert。js公司
jQuery(function ($) {
$("#insertform").submit(function (e) { //form is intercepted
e.preventDefault();
//serialize the form which contains secretcode
var sentdataa = $(this).serializeArray();
//Add the additional param to the data
sentdataa.push({
name: \'action\',
value: \'wp_insert\'
})
//set sentdata as the data to be sent
$.post(yess.ajaxurl, sentdataa, function (rez) { //start of funciton
alert(rez);
return false;
} //end of function
,
\'html\'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
});
谢谢!