Я работаю в WordPress, и я запускаю функцию для вставки строки в базу данных с помощью ajax. Ajax работает, но по какой-то причине операция вставки выполняется дважды.Ajax дважды запускает мой запрос на ввод
Ниже мой код Ajax
jQuery(function ($) {
$(document).on("submit","#myvoteform", function(e) {
//form is intercepted
e.preventDefault();
//serialize the form which contains secretcode
var sentdata = $(this).serializeArray();
//Add the additional param to the data
sentdata.push({
name: 'action',
value: 'votes'
})
//set sentdata as the data to be sent
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
//$("#myresult").append(res.l);
// $("#myresult").html("");
$("#myresult").html(res);
//$.parseJSON(data);
return false;
} //end of function
,
'json'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
}); //vote function ends here
PHP код функция Insert
add_action('wp_ajax_votes', 'votes');
add_action('wp_ajax_nopriv_votes', 'votes');
add_shortcode('sketchfamvotes','voteus');
function voteus(){
// register & enqueue a javascript file called globals.js
wp_register_script('votess', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array('jquery'));
wp_enqueue_script('votess');
// use wp_localize_script to pass PHP variables into javascript
wp_localize_script('votess', 'yes', array('ajaxurl' => admin_url('admin-ajax.php')));
}
function votes()
{//echo json_encode("pakistan zindabad"); die();
$cat =$_POST['category'];
$comp = $_POST['competition'];
$uid= $_POST['uid'];
global $wpdb;
$userid = $_POST['userid'];
$myvote = 1;
if($wpdb->insert(
'votes',
array(
'votes' => 1,
'competition' => $comp,
'uid' => $uid
)
) == false) {wp_die(json_encode('Database Insertion failed')); die();} else {echo json_encode('your vote was successfully recorded');die();}
}
Ниже моя форма, которая является результатом другого АЯКС вызова. Я не вставляю полную функцию ajax php, а просто показываю, как выглядит моя форма.
if(is_array($results) && count($results) > 0 ) {
$form = "";
foreach($results as $result) {
$form .= '<form id="myvoteform" action="" method="post">';
$form .= "<input name='category' type='hidden' value='$result->category'>";
$form .= "<img src='$result->path' width='150' height='150' >" . '<br><br>';
$form .= "<input name='uid' type='text' value='$result->uid'>";
$form .= "<input name='competition' type='hidden' value='$result->competition'>";
$form .= "<input name='userid' value'$result->uid' type='text'>".'<br>';
$form .= $result->category.'<br>';
$form .= $result->uid.'<br>';
$form .= $result->votessum.'<br>';
$form .= "<input style='margin-bottom:30px;' id='votebutton' value='vote' name='submit' type='submit'/></form>";
Если вы смотрите в (например) Google Chrome инструменты для разработчиков, это вызов Ajax выполняется два раза подряд? – Raiment