Ajax runs my insert query twice - javascript

I am working in WordPress and I run a function to insert a row in database with ajax. Ajax runs but for some reason insert operation is performed twice.
Below is my code
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 code
Insert function
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();}
}
Below is my form which is the result of another ajax call. I'm not pasting the full ajax php function but just showing how my form looks like.
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>";

Try with this modified code - jquery .off()
jQuery(function ($) {
$(document).off().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

Related

Change order status with AJAX in plugin wordpress

I am customizing a plugin, which gives recent orders and plays a sound notification. However i want to add an ajax call to a custom button that shows in every row:
This is my method so far:
// ajax function in plugin file
<?php
function my_action_javascript($order_id) {
$order = wc_get_order( $order_id ); // returns correct order id in every button
?>
<script type="text/javascript"> // initiate script
jQuery(function($){
$('pluginchangebutton').click( function(e){
e.preventdefault();
$.ajax({
type: 'POST',
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
'action': 'my_action', // send php function ?
'order_id': <?php echo $order_id; ?>, // Here we send the order Id
},
success: function(response) { // no response at all
alert('ok');
},
error: function(response) { // no response at all
alert('error');
}
});
});
});
</script> <?php
}
add_action( 'wp_ajax_my_action', 'my_action' );// register my_action to wp ajax
function my_action() {
if ( isset($_POST['order_id']) && $_POST['order_id'] > 0 ) {
$order = wc_get_order($_POST['order_id']);
$order->update_status('completed'); // function to update status
die();
}
}
// ajax end
This is the ajax function which i place on top of the plugin file.
And this is how i display my table:
// get recent orders
$recent_orders = wc_get_orders(array(
'limit' => $show_order_num,
'orderby' => 'date',
'order' => 'DESC',
'status' => $show_order_statuses,
));
$content = "<h1>Нови порачки</h1>";
$content .= "<table id='customers-new-order-notification'>";
$content .= "<tr><th>Последни порачки</th></tr>";
$content .= "<tr><th>Порачка бр.</th><th>Дата на порачка</th><th>Статус на порачка</th><th>Детали за порачка</th></tr>";
foreach ($recent_orders as $recent_order) {
// get order details .. ... .. .. .. .. ..
$order_id = $recent_order->get_id();
$_order = wc_get_order($order_id);
$order_date = $_order->get_date_created();
$order_status = $recent_order->get_status();
$order_link = get_site_url();
$order_link .= "/wp-admin/post.php?post=";
$order_link .= $order_id;
$order_link .= "&action=edit";
$billing_first_name_plugin = $recent_order->get_billing_first_name();
$billing_address_1_plugin = $recent_order->get_billing_address_1();
$billing_city_plugin = $recent_order->get_billing_city();
$billing_postalcode_plugin = $recent_order->get_billing_postcode();
$billing_email_plugin = $recent_order->get_billing_email();
$billing_phone_plugin = $recent_order->get_billing_phone();
$billing_country_plugin = $recent_order->get_billing_country();
$order_shipping_method_plugin = $recent_order->get_shipping_method() . ' - ' . $recent_order->get_shipping_total() . ' rsd';
$order_get_subtotal_plugin = $recent_order->get_subtotal() . ' rsd';
$order_get_total_plugin = $recent_order->get_total() . ' rsd';
$order_javena='Непотврдена';
$customer_note_plugin = $recent_order->get_customer_note();
$statusPrefix = "wc-";
$_orderStatus = $statusPrefix . $order_status;
$_order_status = $order_status_map[$_orderStatus];
$date_format = get_option('date_format'); // format
$time_format = get_option('time_format'); // format
$format_order_date = $time_format . " - " . $date_format;
$items = $recent_order->get_items(); // get product items from order
// add content to $content .. table .. .. . .. row 1
// .... .... ... ... ... ... ... ... row 2
// row 3 start
$content .= "<td>" . esc_html($order_javena) ."<br>";
$content .= my_action_javascript($_order) . "<button class=pluginchangebutton type=submit>Потврди</button>";
$content .="</td>"; // row 3 end
// row 4 add .. .. ..
// row 4 end
if (!$isNew) {
delete_option('_new_order_id_for_notification');
$time = $refreshTime;
header("Refresh:" . esc_html($time) . "");
add_action('wp_head', 'wpb_hook_javascript');
}
echo $content;
}
In inspecting, the $.ajax gets the correct order id for every button, however i do not get a response at all. I've tried with console.log as well but still, no response.
I have tried inserting type, datatype and url with ' ', as well as " ", still nothing.
This code is in the plugin file.
I have tried adding it to functions.php, it does not work.
Can i get some guidance?

Send php value with jQuery ajax function to php function

I have an ajax form that filters posts based on the category.
Setup:
HTML form
PHP function to echo ouput
jQuery ajax request to load php
function
Question: How can I parse a value to the php function ($test, see below) from within the jQuery ajax function?
Form - Outputs html select field and button to filter posts
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories
echo '<select name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</form>
<div id="response"></div>
PHP function - Outputs result on button click in HTML form
function misha_filter_function($test){
// Do something with $test, but how to parse it with jQuery into this php function?
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC или DESC
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
jQuery - Question: how to parse php value $test to the above php function?
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
You serialize data so accesed by:
parse_str($_POST['data'], $inputValues); //$inputValues will be array with your form fields

wordpress plugin jquery ajax call to function not working

JQuery Code:
jQuery("#dmhsc-form").on("submit", function () {
var form = this;
if (jQuery("input[name='url']", form).val() == "") {
jQuery("div[id='results']", form).html('<div class="not-available">Please, Enter site address.</div>');
return false;
}
var url = jQuery("input[name='url']", form).val();
jQuery("div[id='results']", form).css('display', 'none');
jQuery("div[id='results']", form).html('');
jQuery("div[id='loading']", form).css('display', 'inline');
var data = {
'action': 'dmhsc_show',
'url': url,
'security': badnc_ajax.dmhsc_nonce
};
jQuery.post(badnc_ajax.ajaxurl, data, function (response) {
var x = JSON.parse(response);
if (x.status >= 0) {
display = x.text;
} else {
display = "Error occured." + x;
}
jQuery("div[id='results']", form).css('display', 'block');
jQuery("div[id='loading']", form).css('display', 'none');
jQuery("div[id='results']", form).html(unescape(display));
});
return false;
});
Plugin File
function badnc_load_styles() {
wp_enqueue_script( 'badnc-script', plugins_url( 'script.js', __FILE__ ), array('jquery')); // script.js contains jquery code
wp_localize_script( 'badnc-script', 'badnc_ajax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'dmhsc_nonce' => wp_create_nonce( 'dmhsc_nonce' ))
);
}
add_action( 'wp_loaded', 'badnc_load_styles' );
add_action( 'admin_enqueue_scripts', 'badnc_load_styles' );
function dmhsc_show() {
check_ajax_referer( 'dmhsc_nonce', 'security' );
if(isset($_POST['url']))
{
$url = sanitize_text_field($_POST['url']);
if(!$url || !is_string($url) || ! preg_match('/^(https?:\/\/)?(www\.)?\w+\.[a-z]{2,6}(\/)?$/i', $url)) {
$result = array('status'=>0,'url'=>$url, 'text'=> '<div class="not-available">Please, Enter valid domain name.</div>');
echo json_encode($result);
} else {
/*$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$url.'</div>');
echo json_encode($result);*/ //It display the message without calling to fucntion
check_https($url); //function call
}
}
die();
}
add_action('wp_ajax_dmhsc_show','dmhsc_show');
add_action('wp_ajax_nopriv_dmhsc_show','dmhsc_show');
function check_https($host) {
$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$host.'</div>');
echo json_encode($result);
}
Problem
I want to show "Domain: domain name" when I submit the form. Form contains url field and submit button.
but I don't know it is not displaying the message written in check_https() function.
I am also getting error in console:
Uncaught SyntaxError: Unexpected token { in JSON at position 74
at JSON.parse (<anonymous>)
If I display the message without calling to function check_https(), it works.
What should be the problem.

how to use lastInsertId() if the column called different

i have a function which insert my data into my database. But at the same time i want that my javascript add the content to my list #div.
my php file
function xhrInsertPost() {
// echo $_POST[''];
$title = $_POST['title'];
$msg = $_POST['msg'];
$sth = $this->db->prepare('INSERT INTO posts (post_title, post_content) VALUES (:title, :msg) ');
$sth->execute(array(
':title' => $title,
':msg' => $msg
));
$data = array( 'post_title' => $title, 'id' => $this->db->lastInsertId());
echo json_encode($data);
}
my js file
$('#postText').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(data) {
console.log(data);
console.log(data.msg);
$('#listMsg').append('<tr><td>' + data.post_title + '</td><td><a class="del" rel="'+ data.post_id + '" href="#"> delete</a></td></tr>');
}, 'json');
return false;
});
i think it didn't work because my column called different. my code works but my "data.post_id" is undefined.. in my other method (if i refresh the page) it works

Wordpress send email with callback and response using Jquery

Unfortunately I am a beginner in WP code writing and I am trying to implement a custom mail send form in WP whit a response but I have no idea how to do it.
I have the following code in witch "send_carrier_email_callback" should be the e-mail send function:
add_action('wp_ajax_send_carrier_email', 'send_carrier_email_callback');
add_action('wp_ajax_nopriv_send_carrier_email', 'send_carrier_email_callback');
function send_carrier_email_callback(){
global $wpdb;
var_dump($_POST);
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$to = $_POST['email'];
$subject = $_POST['carriertittle']." állásjelentkezés";
$body = $_POST['massage'];
wp_mail( $to, $subject, $body );
// Reset content-type to avoid conflicts -- https://core.trac.wordpress.org/ticket/23578
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
}
function get_carier_ation_callback() {
global $wpdb;
$post_id = $_POST['career'];
$meta = get_post_meta($post_id, "slide_options");
$meta_values =$meta[0];
$args = array (
'p' => $post_id,
'post_type' => array( 'enetix_career' ),
);
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<script>
jQuery(document).ready(function(){
jQuery('#applybutton').click(function(){
jQuery('#applyform').toggle("slow");
});
jQuery('#carrieremailsend').click(function(){
var career_id = jQuery('#carrierid').val();
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var massage = jQuery('#massage').val();
var data = {
action: 'send_carrier_email',
career: career_id,
name: name,
email: email,
massage: massage
}
jQuery.post(ajaxurl, data, function(response) {
});
});
});
In the "jQuery.post(ajaxurl, data, function(response)" I should get a response if the send was successful or not.
Anyone could help me?
Thank you
You need to do something like this. Hope it works for you:
add_action('wp_ajax_send_carrier_email', 'send_carrier_email_callback');
add_action('wp_ajax_nopriv_send_carrier_email', 'send_carrier_email_callback');
function send_carrier_email_callback(){
global $wpdb;
$send_email = false;
$to = $_POST['email'];
$subject = 'Your subject goes here';
$message = $_POST['message'];
$send_mail = wp_mail( $to, $subject, $message );
echo $send_mail; //returns true or false
}
function get_carier_ation_callback() {
global $wpdb;
$post_id = $_POST['career'];
$meta = get_post_meta($post_id, "slide_options");
$meta_values =$meta[0];
$args = array (
'p' => $post_id,
'post_type' => array( 'enetix_career' ),
);
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<script>
jQuery(document).ready(function(){
jQuery('#applybutton').click(function(){
jQuery('#applyform').toggle("slow");
});
jQuery('#carrieremailsend').click(function(){
var career_id = jQuery('#carrierid').val();
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var massage = jQuery('#massage').val();
$.ajax({
type: 'post',
url: ajaxurl,
data: {action: 'send_carrier_email_callback', name: name, email: email, message: message},
success: function(response){
console.log(response); //your response goes here
if(response === true){
//color your div or whatever element green
}else{
//color your div red
}
}
});
});
});

Categories