I created a Wordpress plugin to allow my client to create events with the ability to rsvp and pay for an event. I'm confused as to where certain code needs to be placed and how to submit a form to a function that resides within the plugin folder functions file.
At the moment it returns a blank alert.
I am displaying this form on a single event's page:
<div id="rsvpContent">
<form id="Attendevent" action="">
<input id="attend" name="attend" type="checkbox" value="yes" /><label for="attent">Yes, I plan to attend.</label>
</form>
Then, I placed this into the general header.php file:
$("#attend").click(function(){
var form = $("#Attendevent").serialize();
$.ajax({
type:'POST',
data:{"action":"Attending","data": form },
url: "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php",
beforeSend: function(){
alert(form);
},
success: function(data) {
alert(data);
}
});
});
Then, I placed this function into the main functions page within the plugin folder:
function eventAttent() {
$wpdb->show_errors();
if($_POST['attend'] == 'yes') {
$wpdb->insert('wp_event_attendants',
array( 'event_id' => get_the_ID(),'user_id' => $current_user->ID));
echo $wpdb->print_error();
}
}
add_action('wp_ajax_Attending', 'eventAttend');
add_action('wp_ajax_nopriv_Attending', 'eventAttend');
How can this function be called when a user clicks the 'Attending' checkbox?
This link is a very good source for ajaxifying your theme.
Put this code into functions.php in your child theme.
// enqueue your custom js
function my_js_method() {
// for jquery ui
wp_enqueue_style( 'jqueryUI_style', get_stylesheet_directory_uri() . '/customCSS/jquery-ui.css' );
wp_enqueue_script(
'handleFormAjax-script',
get_stylesheet_directory_uri() . '/handleFormAjax.js',
array( 'jquery' )
);
// add the appropriate hook
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'handleFormAjax-script', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
// AJAX handler snippet
function myHandlerMethod(){
if (is_admin())
echo "woow working like a charm";
die();
}
//add the hooks for your handler function
add_action('wp_ajax_myHandlerMethod', 'myHandlerMethod');
// for users who are not logged in
add_action('wp_ajax_nopriv_myHandlerMethod', 'myHandlerMethod');
In addition to that your form should look like this.
<form id="assetForm" action= "/wp-admin/admin-ajax.php" method="post">
<input type="hidden" name="action" value="myFunction"/>
<button id="sbmBtn">SUBMIT </button>
</form>
and lastly, you js function should address the handler function that you defined in functions.php
var data = jQuery("#myForm :input").serializeArray();
jQuery.post(jQuery("#myForm").attr("action"),data, function(info) {
// success code ;
});
try with this code. this is my tested code. working fine with me .. but it will not process FILE upload.
HTML
<form id="form_name" name="form_name" >
<span id='errfrmMsg' style='margin:0 auto;'></span>
//form attributes just as input boxe.
<input type="hidden" name="action" value="anyName" />
<input id="submit_button" onclick="submit_form();" type="button" value="Send" />
</form>
j Query
function submit_form()
{
jQuery.post(the_ajax_anyName.ajaxurl_anyName,
jQuery("#form_name").serialize(),
function(response_from_the_action_function){
jQuery("#errfrmMsg").html(response_from_the_action_function).css({"display":"block"});
}
);
}
Php code in functions.php
wp_register_script("ajax-anyName", get_bloginfo('template_directory')."/js/custom_js.js", array( "jquery"));
wp_enqueue_script('ajax-anyName');
wp_localize_script("ajax-anyName","the_ajax_anyName", array("ajaxurl_anyName" => admin_url("admin-ajax.php")));
// add actions
add_action( "wp_ajax_anyName", "ajax_action_anyName" );
add_action( "wp_ajax_nopriv_anyName", "ajax_action_anyName" );
function ajax_action_anyName(){
//Form processing code in PHP
}
Related
I moved the Woocommerce coupon form by editing the review-order.php based on this method
I would like to know if it's possible to make the coupon code apply with AJAX (without reloading the page) like in the cart page. I don't know where to start, please help.
as per your shared link, if you follow the same means you are using the coupon form inside the checkout form, so you should remove the coupon form tag and then use it.
Copy woocommerce review-order.php and past inside your active then woocommerce folder.
Open review-order.php and past coupon HTML inside table structure like this:
<tr class="coupon_checkout">
<td colspan="2">
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! wc_coupons_enabled() ) {
return;
}
?>
<i class="fa fa-plus"></i> REDEEM A PROMO CODE/GIFT VOUCHER
<div class="checkout_coupon" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" id="checkout_coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input id="checkout_apply_coupon" type="button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply Coupon', 'woocommerce' ); ?>" />
</p>
</div>
</td>
</tr>
Add jQuery code either your custom.js file or directly on the footer page like this:
<script>
jQuery(document).on('click','#checkout_apply_coupon', function() {
// Get the coupon code
var code = jQuery( '#checkout_coupon_code').val();
var button = jQuery( this );
data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
button.html( 'wait.');
// Send it over to WordPress.
jQuery.post( wc_checkout_params.ajax_url, data, function( returned_data ) {
if( returned_data.result == 'error' ) {
jQuery( 'p.result' ).html( returned_data.message );
} else {
setTimeout(function(){
//reload with ajax
jQuery(document.body).trigger('update_checkout');
button.html( 'Apply');
}, 2000);
console.log( returned_data+code );
}
})
});
</script>
As I have tested on my checkout page it's working perfectly like this:
https://www.loom.com/share/7dfc833895d248f191ba327cf5290403
Optional (if not setup wp_localize_script yet then add into functions.php)
function custom_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/custom.js', array('jquery') ); // optional - if you want to add custom.js then goto theme directory- > js -> and create/add custom.js file
wp_localize_script( 'ajax-script', 'wc_checkout_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); // setup ajax call url
}
add_action( 'wp_enqueue_scripts', 'custom_enqueue' );
You can modify the snippet below to match your styles.
Place the coupon form below in review-order.php or include it from a separate file
<form class="checkout_coupon m-0 p-0 border-0 woocommerce-form-coupon grid grid-cols-3" action="<?php echo esc_url(wc_get_cart_url()); ?>" method="post">
<input type="text" name="coupon_code" class="input-text col-span-2" placeholder="<?php esc_attr_e('Coupon code', 'woocommerce'); ?>" id="coupon_code" value=""/>
<button type="submit" class="theme-button-secondary" name="apply_coupon"><i class="fas fa-arrow-right"></i></button>
</form>
<script>
jQuery(document).on('submit', 'form.checkout_coupon', function (e) {
e.preventDefault()
var form = jQuery(this)
form.block({message: null, overlayCSS: {background: '#FFF', opacity: 0.6}})
jQuery.post(wc_checkout_params.ajax_url, {
action: 'ajax_apply_coupon',
coupon_code: form.find('[name="coupon_code"]').val()
}).done(function () {
jQuery(document.body).trigger('update_checkout')
form.unblock()
}).fail(function (data) {
jQuery(document.body).trigger('update_checkout')
form.unblock()
})
})
</script>
If you want to include it from different file use this
add_action('woocommerce_review_order_after_cart_contents', function () {
if (is_checkout()) {
wc_get_template('checkout/coupon.php');
}
});
Add your ajax handler with the coupon logic in your function.php
function ajax_apply_coupon()
{
$coupon_code = null;
if (!empty($_POST['coupon_code'])) {
$coupon_code = sanitize_key($_POST['coupon_code']);
}
$coupon_id = wc_get_coupon_id_by_code($coupon_code);
if (empty($coupon_id)) {
wc_add_notice(__('Sorry, there has been an error.', 'woocommerce'), 'error');
wp_send_json_error(['message' => __('Sorry, there has been an error.', 'woocommerce')], 400);
}
if (!WC()->cart->has_discount($coupon_code)) {
WC()->cart->add_discount($coupon_code);
}
wp_send_json_success(['message' => __('Coupon code applied successfully.', 'woocommerce')], 200);
}
add_action('wp_ajax_ajax_apply_coupon', 'ajax_apply_coupon');
add_action('wp_ajax_nopriv_ajax_apply_coupon', 'ajax_apply_coupon');
I am trying to load a content template based on the checkbox but want to use AJAX to improve my coding structure but not sure how. I have no prior experience to AJAX so I would really appreciate your help.
HTML
<input type="checkbox" class="checkbox" id"content_one">
<input type="checkbox" class="checkbox" id="content_two">
PHP/Jquery
jQuery(document).ready( function() {
if ($('#content_one').is(':checked')) {
<?php get_template('content_one'); ?> //displays a post loop
}
if ($('#content_two').is(':checked')) {
<?php get_template('content_two'); ?> //displays a post loop
}
});
If you want to ajax you need to register the action in wordpress, it would be something like this.
add_action('wp_ajax_your_action_name', 'my_fallback_function')
add_action('wp_enqueue_scripts', 'my_script');
And you need to specify your function here, in the functions.php, it would be something like this
function my_fallback_function()
{
$param = $_GET['param'];
echo get_template($param);
wp_die();
}
function my_script()
{
wp_localize_script(
'ajaxUrl',
'ajaxObject',
array('ajax_url' => admin_url( 'admin-ajax.php' )
);
}
Then we need to specify the ajax call from the client side it would be something like this
$(document).ready(function() {
$("input[type='checkbox']").click((e) => {
const content = $(e.target).val();
const params = {
'action': 'your_action_name' // should be the same in the wp_ajax,
'param': content
};
$.ajax({
method: 'GET',
url: ajaxObject.ajax_url
data: params,
done(function(respond){
//append your respond here
})
})
})
})
<label for="checkbox1"><input type="checkbox" name="checkbox1" value="content_1"/>Content 1</label>
<label for="checkbox2"><input type="checkbox" name="checkbox2" value="content_2"/>Content 1</label>
I am trying to add my own "Add Media" Button in my own plugin form pages, I created a plugin and I have a form in add-new.php file here is the code:
<div class="wrap">
<h1><?php _e( 'Add Deal', 'webdevs' ); ?></h1>
<form action="" method="post">
<!-- I NEED TO CHANGE THIS TO SHOW "ADD MEDIA BUTTON" -->
<input id="upload_image" type="text" size="36" name="upload_image" value="" />
<input id="upload_image_button" type="button" value="Upload Image" />
<?php wp_nonce_field( 'deal-new' ); ?>
<?php submit_button( __( 'Add Deal', 'webdevs' ), 'primary', 'submit_deal' ); ?>
</form>
How to add the html code and handle it in php
please help
Thnaks
I have created a custom image upload with metabox, you can set below code as per your need.
What you need is to call new WP's thickbox media uploader CSS and JS on your page. you have to modify condition of adding script for plugin page.
Condition to modify if( 'post' !== $typenow ).
What it will do?
It will allow you to open wordpress media uploader and send your selected image url to textbox then you can save the url in post_meta using update_post_meta() or wherever you want to save it. you can get the url from
Supposeable variable :
$content_img = $_POST['content_img'];
Html
<p>
<label><b>Upload Content Image</b></label><br/>
<input class="upload_image" name="content_img" type="text" readonly="readonly" value="<?php echo $content_img ?>"/>
<input type="button" value="Upload" class="button button-primary button-large" onclick="upload_new_img(this)"/>
Remove
</p>
Admin functions.php
// Enqueue script in admin
function my_admin_scripts() {
# Not our screen, bail out
if( 'post.php' !== $hook )
return;
# Not our post type, bail out
global $typenow;
if( 'post' !== $typenow )
return;
wp_enqueue_media('media-upload');
wp_enqueue_media('thickbox');
wp_register_script('my-upload', get_stylesheet_directory_uri().'/js/metabox.js', array('jquery','media-upload','thickbox'));
wp_enqueue_media('my-upload');
}
// Call thickbox CSS
function my_admin_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_enqueue_scripts', 'my_admin_scripts');
add_action('admin_enqueue_scripts', 'my_admin_styles');
Custom JS metabox.js
function upload_new_img(obj)
{
var file_frame;
var img_name = jQuery(obj).closest('p').find('.upload_image');
if ( file_frame ) {
file_frame.open();
return;
}
file_frame = wp.media.frames.file_frame = wp.media(
{
title: 'Select File',
button: {
text: jQuery( this ).data( 'uploader_button_text' )
},
multiple: false
}
);
file_frame.on('select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
var newwurl = attachment.url.split('/wp-content');
img_name[0].value = '/wp-content'+newwurl[1];
file_frame.close();
// jQuery('.upload_image').val(attachment.url);
});
file_frame.open();
}
function remove_image(obj) {
var img_name;
if (jQuery(obj).closest('p').find('.upload_image').length > 0) {
img_name = jQuery(obj).closest('p').find('.upload_image');
} else {
img_name = jQuery(obj).closest('td').find('.upload_image');
}
if (typeof img_name != "undefined") {
img_name.val('');
}
}
I am working on a small WordPress widget and I am trying to set it up where the user can upload an image. So far, the necessary scripts are loading but when I click the "Media Library Image" button the image uploader doesn't pop up.
Here is my javascript file:
jQuery(document).ready(function($) {
var formfield = null;
$('#upload_image_button').click(function() {
$('html').addClass('Image');
formfield = $('#wp-ss-image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
// user inserts file into post. only run custom if user started process using the above process
// window.send_to_editor(html) is how wp would normally handle the received data
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
var fileurl;
if (formfield != null) {
fileurl = $('img',html).attr('src');
$('#wp-ss-image').val(fileurl);
tb_remove();
$('html').removeClass('Image');
formfield = null;
} else {
window.original_send_to_editor(html);
}
};
});
Here is are my functions to call the scripts:
add_action('admin_print_scripts-widgets.php', 'wp_ss_image_admin_scripts');
function wp_ss_image_admin_scripts() {
wp_enqueue_script( 'wp-ss-image-upload', plugins_url( '/WP-Simple-Social/wp-simple-social-image.js' ), array( 'jquery','media-upload','thickbox' ) );
}
add_action('admin_print_styles-widgets.php', 'wp_ss_admin_styles');
function wp_ss_admin_styles() {
wp_enqueue_style( 'thickbox' );
}
And here is the html to display the input box and image upload button:
<p>Upload Photo: <input id="wp-ss-image" class="widefat" type="text" size="75" name="<?php echo $this->get_field_name( 'image' ); ?>" value="<?php echo esc_url( $image ); ?>" />
<input id="upload_image_button" type="button" value="Media Library Image" class="button-secondary" />
Since all of the necessary files/scripts are loading, could this be a jQuery problem?
If there is any other additional info that would help out please let me know. Thanks for the help.
Best way I found was using live() method even if it deprecated to on() profit.
Worked
jQuery(document).ready(function($) {
$("#testage").live("click", function() {
alert("CLICK!");
});
});
Didn't work
jQuery(document).ready(function($) {
$("#testage").on("click", function() {
alert("CLICK!");
});
});
If anybody has an explication I would be grateful.
Just started with JQuery for AJAX calls and what I thought would be a simple script has had me baffled two days now. Basically I want the form data POSTed to the server, and if data entered by user okay then a "Thank You" message is returned, or a message is returned to say there are errors.
In both events, it's HTML that I want returned. This is happening however, when there are errors in the form data, and the form is submitted again, there is a page refresh (I know this as hitting F5 produces the browsers default dialogue box asking to SEND or CANCEL).
This page refresh only happens once submitted the form (the HTML returned from server on initial AJAX call) a second time. Otherwise there appears to be no other faults. The data entered by user and sent to server by the initial AJAX call is okay too.
It's just what happens after server send the HTML back to the client when there are errors. I've posted the code and HTML below, any thoughts would really be welcome at this moment as I'm really new to this JQuery / AJAX stuff!
<!-- found on the contact page -->
<script type="text/javascript">
$(document).ready( function() {
$( '#submit' ).click( function() {
var payload = $( '#form' ).serialize();
// var name = $('input[name=name]');
// var data = 'name=' + name.val();
$.ajax({
url: '/contact/post/',
type: 'post',
data: payload,
cache: false,
success: function( html ) { console.log( html );
$( '#formbox' ).html( html );
}
});
return false;
}); // close of #submit
});
</script>
<!-- ... ... -->
<div id="formbox">
<form
id="form"
method="post"
accept-charset="utf-8"
action="#">
<!-- using only one field at the moment (debugging purposes) -->
<div class="lft"><p><label for="_name">Name</label> </p></div>
<div class="rgt"><p> <input type="text" id="_name" name="name" size="16" maxlength="32" value="Elizabeth Q" /></p></div>
<div class="lft"><p> </p></div>
<div class="rgt"><p>
<input type="submit" id="submit" name="submit" value="Send Message" />
</p></div>
</form>
</div>
<!-- what is returned from server if no errors with user data -->
<div class="both">
<p>Thank you for contacting us, please expect a prompt reply shortly.</p>
</div>
<!-- what is returned from server if there are errors with user data -->
<form
id="form"
method="post"
accept-charset="utf-8"
action="#">
<div class="both">
<p class="error">Please amend the following error(s) shown below before trying again.</p>
<br />
<ul>
<?php foreach( $this -> get( 'logger' ) -> export() as $error ): ?>
<li><p><?php echo $error; ?></p></li>
<?php endforeach; ?>
</div>
<div class="lft"><p><label for="_name">Name</label> </p></div>
<div class="rgt"><p> <input type="text" id="_name" name="name" size="16" maxlength="32" value="<?php echo $this -> get( 'name' ); ?>" /></p></div>
<div class="lft"><p> </p></div>
<div class="rgt"><p>
<input type="submit" id="submit" name="submit" value="Send Message" />
</p></div>
</form>
<!-- the php file that determines user data is valid or not and returns response -->
final class QPage_Handler_Ajax extends QPage_Handler_Validator {
public function __construct() {
$this -> initialise();
$this -> id = 'site';
}
public function execute( QDataspace_Interface $dataspace ) {
if( !$this -> validate( $request = QRegistry::get( 'request' ), QRegistry::get( 'logger' ) ) ) {
// execute this handler as errors found
$this -> handler -> execute( $dataspace );
} else {
// no errors with data sent to server
$page = new QPage_View( $request = QRegistry::get( 'request' ) );
$page -> render( 'contact/post/body.tpl' );
}
}
protected function initialise() {
$this -> forward( new QPage_Handler_Ajax_Success() );
$this -> addCondition( QValidator::factory()
-> addCondition( new QValidator_Condition_Required( 'name', 'The field "name" is required.' ) )
-> addCondition( new QValidator_Condition_Expression( 'name', '/^[a-zA-Z ]+$/', 'The field "name" has illegal character(s).' ) )
-> addCondition( new QValidator_Condition_Size_Maximum( 'name', 32, 'The field "name" must not exceed 32 characters.' ) )
);
}
}
final class QPage_Handler_Ajax_Success extends QPage_Handler {
public function __construct() {
$this -> id = 'site';
}
public function execute( QDataspace_Interface $dataspace ) {
$page = new QPage_View( $request = QRegistry::get( 'request' ) );
$page -> set( 'logger', QRegistry::get( 'logger' ) );
$page -> render( 'contact/post/error.tpl' );
}
}
Any suggestions to how to fix the issue(s) that I have are very much welcome and appreciated. Please remember I am new to using JQuery but I've been using PHP for a number of years.
I guess, you should use event.preventDefault()
So, try this:
$( '#form' ).submit( function(event) {
event.preventDefault();
var payload = $( '#form' ).serialize();
// var name = $('input[name=name]');
// var data = 'name=' + name.val();
$.ajax({
url: '/contact/post/',
type: 'post',
data: payload,
cache: false,
success: function( html ) { console.log( html );
$( '#formbox' ).html( html );
}
});
return false;
}); // close of #submit
It will be more pretty if you use .submit() (for FORM element not for the submit BUTTON), it will trigger the submit function even if the form is submitted by onother action than the a click on the button.
You must also use event.preventDefault();
Other best practice is to put the url where you want to submit in the action attribute of the form, this will make the site useful for people that deactivate javascript.
This is merely a JavaScript/jQuery problem.
On page load, you are running the jQuery code which binds the click on the submit button. Then, when clicking the submit button and an error occurs, you are returning from PHP the whole form again (unlike in the case of a successful POST, where you are only returning the success message).
The problem here is that, according to jQuery, the old submit button on which the click event was binded has been removed. and replaced by a new button.
Several solution can be done with this, some are a bad choice, others are better. What I would recommend is the following:
Instead of returning the whole form, return only the error message and prepend it to the form.
<div class="both">
<p class="error">Please amend the following error(s) shown below before trying again.</p>
<br />
<ul>
<?php foreach( $this -> get( 'logger' ) -> export() as $error ): ?>
<li><p><?php echo $error; ?></p></li>
<?php endforeach; ?>
</div>
P.S. I would change $( '#submit' ).click( function() { to $("#form").submit(function(){
as this will be fired even if the form was submitted in a different manner, such as clicking Enter in a text field.
A small tip is to return JSON with AJAX from PHP, it will help you accomplish this task in a much easier manner.
json_encode()
json_decode()
Another solution is to use .live() .on()
This is the easy way out, but I do not recommend this.
$(document).ready( function() {
// this can also be replaced by: $('#formbox').on('click', '#submit', function() {
$('#formbox').on('submit', '#form', function(){
var payload = $('#form').serialize();
// var name = $('input[name=name]');
// var data = 'name=' + name.val();
$.ajax({
url: '/contact/post/',
type: 'post',
data: payload,
cache: false,
success: function(html) {
console.log(html);
$('#formbox').html(html);
}
});
return false;
}); // close of #submit
});
EDIT:
.live() was deprecated since jQuery 1.7, and removed since jQuery 1.9