Update meta_key with ajax in Wordpress - ajax

I want to update meta_key with ajax in wordpress i use this form
this is my code but not work for me
<?php
add_action( 'wp_head', 'ajax_the_clike' );
function ajax_the_clike() {
?>
<script>
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var formd = "#like";
$(formd).submit(function(event) {
event.preventDefault();
$.ajax({
url: $(formd).attr('action'),
type: $(formd).attr('method'),
data: $(formd).serialize(),
success: function(data) {
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
});
</script>
<?php
}
add_action('wp_ajax_the_clike', 'the_clike'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_the_clike', 'the_clike');
function the_clike() {
echo '<form action="'.site_url() .'/wp-admin/admin-ajax.php" method="post" id="like">';
echo '<input type="submit" value="VoteUp" id="submit" name="submits">';
if(isset($_POST['submits'])){
$postsid = get_the_ID();
$addone = get_field('like');
$addone++;
update_field('field_5f009fe6d7067' ,$addone, $postsid);
}
echo '</form><p> Like : '; if(get_field('like')) { the_field('like');}else{echo '0';} echo '</p>';
}
?>
I using a Advanced custom field plugin
Where is wrong? How do I solve this problem?
Thanks for any help

Related

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);
},

Select2 event after ajax replace

I'm trying to create filters using a Select2 dropdown and I do not know why the Select2:select event stop working after updating the html with the data that comes via Ajax.
Please help - My PHP is:
<div class="select-yellow fecha-container">
<select id="fecha" class="select2 fecha-addon" data-minimum-results-for-search="Infinity">
<?php foreach($fechas as $fecha): ?>
<option value="<?php echo $fecha; ?>"><?php echo formatDate($fecha); ?></option>
<?php endforeach; ?>
</select>
</div>
The JS file:
$('#fecha').on("select2:select", function(e) {
// here it's working
var fecha = $('#fecha').val();
var provincia = $('#provincia').val();
var request = $.ajax({
url: app.base_url + "/ajax-gallery/",
method: "GET",
data: {
provincia: provincia,
fecha: fecha,
tag: provincia
},
dataType: "html"
});
request.done(function (msg) {
if($.trim(msg).length) {
$('.gallery-container').html(msg);
var $filter = $('.gallery-container').find('.fecha-addon');
$('.fecha-container').html($filter);
$("#fecha option").each(function(){
if($(this).val()==fecha){
$(this).attr("selected","selected");
}
});
$('#fecha').select2({
minimumResultsForSearch: -1
});
//after rebind the event doesn't work
}else{
$('#gallery-notices').html('<strong>No hay más imagenes con esta fecha</strong>');
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

I can't update status by use the checked box

Please help i can't update the status by use the checked box.
When i selected the check box and select delete button, status will change to 'deleted' but now i can't update the data.
This is my view
<a href="javascript:;" id="delete" class="myButton" >Delete</a>
<div>
<input type="checkbox" class="cb_invoice" id="<?php echo $r->INVOICENUMBER;?>" value="<?php echo $r->INVOICENUMBER;?>">
</div>
This my script
<script>
$('#delete').click(function() {
var _url = "<?php echo site_url('commission/delete_invoices');?>";
var d_obj = $(".cb_invoice");
var d_val = [];
for (var i = 0; i < d_obj.length; i++){
if(d_obj[i].checked){
d_val.push(d_obj[i].value);
}
}
$.ajax({
url: _url,
data: {data: d_val},
type: 'post',
success: function(data) {
//console.log(data);
location.reload();
}
});
});
</script>
This my controller
function delete_invoices(){
$invoice = $this->input->post('data');
foreach ($invoice as $invoice) {
$this->m_commission->delete_invoice($invoice);
}
}
This is my model
function delete_invoice($invoice){
$this->db->update('salesinvoiceheader');
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
}
Change the order of update as follows in your modal:-
function delete_invoice($invoice){
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
$this->db->update('salesinvoiceheader');
}

dropdown is not working i ajax form submit in yii 1x

My drop down is not working in ajax form submit but its working on normal form.
When i do ajax submit i get error in firebug
"NetworkError: 404 Not Found - http://example.com/yii/def/state/create"
But when i do the normal submission the form works.
Please help me to solve this issue
My ajax view is _ajax_create_form.php. Code:
<div class="form">
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'state-create-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'method'=>'post',
'action'=>array("state/create"),
'type'=>'horizontal',
'htmlOptions'=>array(
'onsubmit'=>"return false;",/* Disable normal form submit */
),
'clientOptions'=>array(
'validateOnType'=>true,
'validateOnSubmit'=>true,
'afterValidate'=>'js:function(form, data, hasError) {
if (!hasError)
{
create();
}
}'
),
)); ?>
div class="row"> <?php echo $form->labelEx($model,'country_id'); ?> <?php echo $form->dropDownList($model,'country_id',
CHtml::listData(Country::model()->findAll(),'id','name')); ?> <?php echo $form->error($model,'country_id'); ?> </div>
<div class="modal-footer">
<div class="form-actions">
<?php
$this->widget('bootstrap.widgets.TbButton', array(
'buttonType'=>'submit',
'type'=>'primary',
'icon'=>'ok white',
'label'=>$model->isNewRecord ? 'Create' : 'Save',
));
?>
</div>
</div>
<?php
$this->endWidget(); ?>
</div>
Scipt for ajax submit
<script type="text/javascript">
function create()
{
var data=$("#state-create-form").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php
echo Yii::app()->createAbsoluteUrl("state/create"); ?>',
data:data,
success:function(data){
//alert("succes:"+data);
if(data!="false")
{
$('#state-create-modal').modal('hide');
renderView(data);
$.fn.yiiGridView.update('state-grid', {
});
}
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'
});
}
function renderCreateForm()
{
$('#state-create-form').each (function(){
this.reset();
});
$('#state-view-modal').modal('hide');
$('#state-create-modal').modal({
show:true,
});
}
</script>
My Controller code is
public function actionCreate()
{
$model=new State;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model,"state-create-form");
if(Yii::app()->request->isAjaxRequest)
{
print_r($_POST['State']);
if(isset($_POST['State']))
{
$model->attributes=$_POST['State'];
if($model->save())
{
echo $model->id;
}
else
{
echo "false";
}
return;
}
}
else
{
if(isset($_POST['State']))
{
$model->attributes=$_POST['State'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
}
Chnage your AJAX url
try by this
var href = window.localion.href.split('/');
var SITE_URL = href[0] + '//' + href[2] + '/';
$.ajax({
url: SITE_URL + 'controller/action',
........
........
});

Resources