Ajax form submit for wordpress - ajax

So, here is my codes:
form-checkout.php
<form id="rh_checkout_ajax" name="checkout" method="post" class="checkout woocommerce-checkout" enctype="multipart/form-data">
<?php if ( sizeof( $checkout->checkout_fields ) > 0 ) : ?>
<?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>
<div class="col2-set" id="customer_details">
<div class="col-1">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
</div>
<div class="col-2">
<?php do_action( 'woocommerce_checkout_shipping' ); ?>
</div>
</div>
<?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
<?php endif; ?>
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
<?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_order_review' ); ?>
<input value="send" type="submit" name="buy_product" style="display:none;" id="rh_product_add_done_click"></input>
</form>
my_js.js
//Ajax checkout submit
jQuery('#rh_checkout_ajax').submit(function(e){
var name = jQuery(this).attr('name');
jQuery.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
});
functions.php
//Ajax submit callback
add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');
function contact_form()
{
echo $_POST['name'];
}
What happens normally
So, when a product is purchased, then the user is redirected to order-detail page which shows what he/she just bought.
What I want it to happen:
I am trying to make it so that the form is submitted via ajax and the user is NOT redirected to the order-detail page, but rather stays in the product page (so, no refresh nor redirect).
I attempted to submit the form via ajax as above but not much of luck.
Could someone help me out with this?
Thanks!

You have to prevent the form from submitting normally. In your js file, add e.preventDefault(). Something like this:
jQuery('#rh_checkout_ajax').submit(function(e){
e.preventDefault();
var name = jQuery(this).attr('name');
jQuery.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
});

Related

Adding checked attribute to selected input ajax

Made a ajax filter with custom taxonomy on WordPress, everything works fine but problem is that checkbox doesn't get checked attribute when click and new results are shown. I don't know what I'm missing here?
HTML
<div class="categories">
<?php
$cat_args = get_terms(array(
'taxonomy' => 'position',
'orderby' => 'name',
));
$categories = $cat_args;
foreach($categories as $cat) : ?>
<label class="hotel-service block mb-2 font-montserrat text-altumTitle text-lg font-medium">
<input type="checkbox" value="yes" class="checkbox" data-category="<?php echo $cat->term_id ?>" href="<?php echo get_category_link($cat->term_id); ?>"> <?php echo $cat->name; ?></label>
<?php endforeach; ?>
</div>
Ajax call
(function($) {
$(document).ready(function(){
$(document).on('click', '.hotel-service > input', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url: wpAjax.ajaxUrl,
// filter here is handler for add_action callback function in ajax-filter.php
data: { action: 'hotelService', category: category},
type: 'post',
success: function(result) {
$('#response').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);

Woocommerce mini-cart ajax apply coupon

I have been going in circles with this I have added an apply coupon field to mini-cart.php and am trying to get it to run without refreshing the whole page. Any suggestions would be amazing help.
functions:
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
Input:
<?php if (empty (WC()->cart->get_coupons())): ?>
<span id="coupon-form">
<?php if ( wc_coupons_enabled() ) { ?>
<form class="widget_shopping_cart_content" action="<?php echo $cart_url ?>" method="post">
<?php } else { ?>
<form id="apply-promo-code" class="widget_shopping_cart__coupon">
<?php } ?>
<label id="promo-code" for="coupon-code">Promo Code:</label>
<input id="minicart-coupon" class="input-text" type="text" value="" name="coupon_code"/>
<button type="submit" id="minicart-apply-button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply', 'woocommerce' ); ?></button>
<?php do_action( 'woocommerce_cart_coupon' ); ?>
<?php do_action( 'woocommerce_cart_actions' ); ?>
</form>
<?php endif; ?>
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
<span id="widget-shopping-cart-remove-coupon" class="mini_cart_coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
Promo Code: <?php echo esc_attr( sanitize_title( $code ) ); ?>
<?php $remove_url = $cart_url.'?remove_coupon='.$coupon->code; ?>
<?php wc_cart_totals_coupon_html( $coupon ); ?>
</span>
<?php endforeach; ?>
jQuery:
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
You can get the new mini cart HTML inside your ajax callback on the server and then return that as a response to the jQuery ajax call then simply replace the whole mini cart HTML on the front-end with the updated HTML.
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
ob_start();
woocommerce_mini_cart();
$cart_html = ob_get_clean();
return $cart_html;
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
The output buffer is used here as woocommerce_mini_cart uses wc_get_template which just echoes out the content. The output buffer will allow you to capture this as a string.
Now you need to tell jQuery that you're expecting HTML back from the server...
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
Now response will have the new HTML for the mini-cart, so you can replace it using jQuery's html() function...
success: function (response) {
console.log(response);
jQuery('.mini-cart-wrapper').html(response);
},

how i can call joomla module with ajax?

i create new joomla module
and i want call this module with ajax in easyblog component when client click on button
for this work i use com_ajax but this way dont help me
please check my code
my module name is mfk_following
$(document).ready(function(){
SitePath= $(location).attr('hostname')+"/\analyze";
$('body').on('click','span', function() {
$.ajax({
url: SitePath+"index.php?option=com_ajax&module=mfk_following&format=raw&authorid=" + 1,
type: 'get',
success: function(response){
alert(response);
}
});
alert('check clicked');
});
});
<div class="btn_follower" tabindex="<?php echo $user->userID; ?>" >
<a class="pluginButtonContainer" title="<?php echo $user->userID; ?>" href="#" >
<span class="pluginButtonLabel" title="<?php echo $user->userID; ?>">
<?php echo JText::_('Follower'); ?>
</span>
</a>
</div>
// in view.html.php
<?php
defined( '_JEXEC' ) or die;
$doc = JFactory::getDocument();
$authorid = JRequest::getVar('authorid', 'authorID', '', 'int');
echo $authorid;
require JModuleHelper::getLayoutPath('mod_mfk_following','default');
?>
i am not sure this url is true please help me

Ajax modal form validation and submit

I am new to MVC and currently working on a basic website setup. I am trying to have a modal window open where one can input some data and then press submit to submit it back to the database.
Using CodeIgniter and this Jquery Modal (doesn't necessary have to be this one thou).
Again I am very new to MVC so having some trouble visualizing the flow of data.
The modal opens correctly, but I'm trying to display the validation/errors in the same modal without opening a new window. What would I place near echo("error-ajax");, opening a view seems to result in opening a new window.
View -- Opens Modal:
...
...
View -- Actual Form:
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h3>New</h3>
<p>
<label>ID: <input class="pull-right" type="text" name="idnumber" value="<?php echo set_value('idnumber'); ?>" size="9"/></label>
</p>
<div><input type="submit" value="Submit" /></div>
</form>
<script>
$(function(){
$('form').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
async: false,
url: "<?php echo site_url("bondform/save_form"); ?>",
success: function(){alert('Succes');},
error: function(){alert('Error');}
});
});
});
</script>
Controller:
<?php
class Bondform extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$config = array(
array(
'field' => 'idnumber',
'label' => 'Id Number',
'rules' => 'trim|required|min_length[9]|max_length[9]|xss_clean'
)
);
$this->form_validation->set_rules($config);
}
public function view_form()
{
$this->load->view('bond/form');
}
public function save_form()
{
if ($this->form_validation->run() == FALSE)
{
if ($this->input->is_ajax_request())
{
echo("error-ajax"); //placeholder, debug
}
else
{
echo("error-noajax"); //placeholder, debug
}
}
else
{
echo("succes-close"); //placeholder, debug
}
}
}
Thank you very much,
To start, move your ajax function from the modal view to the view that opens it, then you can control the contents of the modal without losing your form view.
Opens Modal:
<script>
$(function(){
$('body').on('submit', 'form', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url("bondform/save_form"); ?>",
data: $(this).serialize();
success: function(response){ $('#form_container').html(response); alert('Succes');},
error: function(){alert('Error');}
});
});
});
</script>
Actual Form:
<div id="form_container">
<?php echo validation_errors(); ?>
<?php echo form_open('bondform/save_form'); ?>
<h3>New</h3>
<p>
<label>ID: <input class="pull-right" type="text" name="idnumber" value="<?php echo set_value('idnumber'); ?>" size="9"/></label>
</p>
<div><input type="submit" value="Submit" /></div>
</form>
</div>
Should get you started in the right direction.

CakePHP: Rendering view after ajax

I am building an app in CakePHP and I have a jquery dialog window and every time the user opens it I want to perform a jquery request that will populate the content with the result of the request.
I have an js file that is in the webroot/js folder, with the following script:
$.ajax({
url:'/projects/getAssets',
type:"POST",
data:assetData,
//dataType:'text',
update: '#assetManagerContent'
});
In my controller file (ProjectsController) I have the following function:
function getAssets($id = null) {
// Fill select form field after Ajax request.
if(!empty($this->data)){
$this->set('assetsFilter',
$this->Project->Asset->find('list',
array(
'conditions' => array(
'Asset.project_id' => '23'
)
)
)
);
$this->render('elements/assets', 'ajax');
}
}
And finally I have the view (elements/assets):
<?php $assetsFilter = $this->requestAction('projects/getAssets'); ?>
<?php foreach($assetsFilter as $assetFilter): ?>
<div class="assetManager-asset">
<div class="thumb"></div>
<div class="label-name"><?php echo $assetFilter['AssetType']['type'] ?></div>
<div class="label-date"><?php echo $assetFilter['Asset']['layer'] ?></div>
<?php //echo $assetFilter['Asset']['id'] ?>
</div>
<?php endforeach; ?>
When the user opens the dialog the ajax request is triggered but nothing seems to happen in the #assetManagerContent div.
I hope someone can tell me what I am doing wrong
As far as I know, there is no update option in the jQuery ajax api. Instead, you should add the success callback and populate the data there:
$.ajax({
url:'/projects/getAssets',
type:"POST",
data:assetData,
//dataType:'text',
success: function(data) {
$('#assetManagerContent').html(data);
}
});
There is no update-option, just as jeremyharris already pointed out.
If you only want to fill an element with HTML loaded via AJAX, you can also use $.load():
$('#assetManagerContent').load('/projects/getAssets', assetData);
It's basically a shorthand for the corresponding $.ajax() call, and will automatically issue a POST request if the data parameter is present.
See: http://api.jquery.com/load/
to make your action faster, cleaner and reusable you could write it this way.
function getAssets($id = null) {
// Fill select form field after Ajax request.
if(!empty($this->data)){
return $this->Project->Asset->find('list',
array(
'conditions' => array(
'Asset.project_id' => '23'
)
)
);
}
}
Ajax
$.ajax({
url:'/projects/getAssets/'+id,
type:"POST",
success: function(data) {
$('#assetManagerContent').html(data);
}
});
OR
$('#assetManagerContent').load('/projects/getAssets/'+id);
It works but shows result in text mode.
e.g.
<form action="/amit/tour-writer/derivedItineraries/getHotelDetail/1230"
id="DerivedItineraryGetHotelDetailForm" method="post" accept-charset="utf-8">
<div style="display:none;"><input type="hidden" name="_method" value="POST"/>
</div>
<div class="required"><label for="DerivedItineraryInclusion">Inclusion</label>
<textarea name="data[DerivedItinerary][inclusion]" class="ckeditor"
required="required" style="width:200px;" cols="30" rows="6"
id="DerivedItineraryInclusion">Test data</textarea></div></td></tr>
</form>

Resources