Cakephp ajax insert without using cake ajaxhelper - ajax

I am trying to add data in cakephp by ajax without using ajax helper.Here insertion is working fine but problem is after insert data I have failed to see the success massage.Here is my effort.
<script>
$(document).ready(function(){
$('#submit').click(function(){
x=$("#rform").serializeArray();
$.post($("#rform").attr("action"),
x,
function(data)
{
$("#success").html(data);
$("#success").fadeIn();
$("#success").fadeOut(2800);
$("input").val('');
});
$("#rform").submit(function(){
return false;
});
});
});
</script>
Here is the add.ctp code
<?php
echo $this->Form->create('Info',array(
'id' => 'rform'
)); ?>
<fieldset>
<legend><?php echo __('Add Info'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('email');
?>
</fieldset>
<?php
$options = array
(
'label' => 'Add',
'value' => 'Add',
'id' => 'submit'
);
echo $this->Form->end($options);
?>
</div>
<div style="color:green;" id="success">
</div>
Here after add it is repeating insertion page again in bellow.Here I need to show only success massage.If I remove $("#success").html(data); nothing is happening but after insert button name making disappear.How can I add success massage in here ?

I have solved it by little bit change
$("#success").html(data);
to
$("#success").html("Insert Success");
and here I have changed input button tag, I have use direct button here
<button id="submit">Submit </button>

Related

How to get data from wordpress ajax search form?

My form html code, where i set action and the attribute name.
<div class="search_form">
<form action="<?php esc_url( home_url( '/' ) ); ?>" method="POST">
<input type="text" name="s" value="<?php get_search_query(); ?>" placeholder="Search...">
<input type="submit" value="Send">
</form>
</div>
I use localize scripts to connect ajax-search.
wp_enqueue_script( 'wc-estore-ajax-search-js', get_template_directory_uri() . '/assets/js/ajax-search.js', array( 'jquery' ), _S_VERSION, true );
wp_localize_script( 'wc-estore-ajax-search-js', 'search_form', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'search-nonce' )
) );
In ajax-search got nonce, set action and set url.
jQuery(function ($) {
$('.search_form input[name="s"]').on('keyup', function () {
let search = $('.search_form input[name="s"]').val();
if (search.length < 4) {
return false;
}
let data = {
s: search,
action: 'search_action',
nonce: search_form.nonce
};
$.ajax({
url: search_form.url,
data: data,
type: 'POST',
dataType: 'json',
beforeSend: function (xhr) {
},
success: function (data) {
console.log(data);
}
});
});
});
And in functions.php i want to see, what is in $_POST.
The action is the same as in the search-ajax.js.
add_action( 'wp_ajax_search_action', 'esp_search_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_search_action', 'esp_search_ajax_action_callback' );
function esp_search_ajax_action_callback() {
/**
* Проверяем нонсе из массива пости и из wp_localize script
*/
if(!wp_verify_nonce($_POST['nonce'], 'search-nonce')){
wp_die('Данные пришли с левого адреса');
}
$_POST = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
$args = [
'post_type' => ['post', 'product'],
'post_status' => 'public',
's' => $_POST['s'],
];
$query_ajax = new WP_Query($args);
?>
<?php if($query_ajax->have_posts()): ?>
<?php while($query_ajax->have_posts()): ?>
<?php $query_ajax->the_post(); ?>
<h3 class="title-search"><?php the_title(); ?></h3>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
<?php
}
But the console is clear?
Where is my mistake?
Thanks for help.
Looks like you have a few things going on. Try these:
dataType is the type of data you're expecting back. You're not passing valid JSON back, so it is failing with a parse error (i.e. no success, no console.log).
vardump probably should be var_dump unless you've defined it elsewhere. If not, that's probably causing an error and sending back the error string (which again would not be valid JSON)
Although not necessarily the issue you're asking about, but you should also finish your callback with wp_die(); and pass whatever parameters you need for your situation.
If you want, while you're testing you can switch dataType to html.
You can also add in error (to see what the error is) and complete (to see that it actually came back) callbacks.
And just to be safe, you might want to filter your $_POST data with something like this:
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
or whatever filters fit your situation.

How to add load more button ajax button to this wordpress loop?

<main class="main aktualitasu_saraksta_konteineris" role="main">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'group_by' => 'date',
'order' => 'DESC',
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<?php get_template_part( 'parts/loop', 'news' ); ?>
<?php endwhile; endif; wp_reset_postdata();?>
</main>
How to add load more button that load posts with ajax?
You will need to do this in javascript rather than in php look at this https://www.w3schools.com/jquery/jquery_ajax_get_post.asp. You will need to add button in html say
<button id="load_more" type="button">Load More</button>
And then in javascript (this is an example using jQuery)
$("#load_more").click(function(){
$.get("your/route", function(data, status){
//here you can add the data to the page depending on what the data is
});
});
your/route is whatever route you have set in php for fetching more posts

Form is not getting submitted when render partial in Yii

I am partially rendering a form in a view in which user can add subaccounts(profiles). The view in which the form is called is another form where all subaccounts are listed as radiolist.
Below is my view.
<div class="inputs">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'selectUser-form',
'enableAjaxValidation' => false,
)); ?>
<?php echo CHtml::activeRadioButtonList($model,'id', $model->getSubAccounts(),array('prompt'=>'Please Select'));?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Book Now' : 'Save'); ?>
<?php echo CHtml::Button('Cancel',array('submit'=>array('cancel','id'=>$model->a_id)));?>
<?php $this->endWidget(); ?>
<div id="data"></div>
<?php echo CHtml::ajaxButton ("Add Users",
CController::createUrl('/user/user/addSubAccount'),
array('update' => '#data'));
?>
Below is my addSubAccount action.
public function actionAddSubAccount()
{
$profile=new YumProfile;
if (isset($_POST['YumProfile']))
{
$profile->attributes = $_POST['YumProfile'];
$profile->user_id=Yii::app()->user->id;
if($profile->save())
$this->redirect(array('/home/create'));}
if(!Yii::app()->request->isAjaxRequest){
$this->render('subaccount_form', array('profile'=>$profile));}
else{
$this->renderPartial('subaccount_form', array('profile'=>$profile));
}
}
Below is subaccount_form.
<?php $this->title = Yum::t('SubAccounts');?>
<div class="wide form">
<?php $activeform = $this->beginWidget('CActiveForm', array(
'id'=>'subaccount-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
));
?>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Firstname');
echo $activeform->textField($profile,'firstname');
echo $activeform->error($profile,'firstname');
?> </div>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Lastname');
echo $activeform->textField($profile,'lastname');
echo $activeform->error($profile,'lastname');
?> </div>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Age');
echo $activeform->textField($profile,'age');
echo $activeform->error($profile,'age');
?> </div>
<div class="row submit">
<?php echo CHtml::submitButton(Yum::t('Add')); ?>
</div>
<?php $this->endWidget(); ?>
My form is rendering. But it's not getting submitted.What am i doing wrong?
After submitting,I need the view to be refreshed and to display the newly added user as an option in the radio list.
EDIT:
I tried like adding the following in the CActiveForm Widget array:
'action' => array( '/user/user/addsubAccount' ),
But still no result.Instead it is saving my data two times when i go through my direct way,meaning render method. :-(
It is because
'enableAjaxValidation'=>true,
Ajax validation is set to true in your form. Set its value to false
'enableAjaxValidation'=>FALSE, and then your form will submit :)
and if you want it to be true only then you should uncomment
$this->performAjaxValidation($model);
in your controller's action
Update 1
if(!Yii::app()->request->isAjaxRequest){
$this->render('subaccount_form', array('profile'=>$profile));}
else{
//change this line
$this->renderPartial('subaccount_form', array('profile'=>$profile),FALSE,TRUE);
}
This link might help you
on renderPartial the action attribute of the form is set to the current page instead of being set to the actual update or create url
My Solution
$form=$this->beginWidget('CActiveForm', array(
'id'=>'country-form',
'action' => Yii::app()->createUrl(is_null(Yii::app()->request->getParam('id'))?'/country/create':'/country/update/'.Yii::app()->request->getParam('id')),

ajax not clearing form on submit

I have a form and want to submit through ajax. It posts but it doesn't clear form onclick success. I've also tried .done(function). I've also tried alert data on success and error (thinking must be error) but it doesn't alert anything either.
<?php echo CHtml::ajaxSubmitButton(
'Comment',
'review/ajaxComment',
array(
'type'=>'POST',
'dataType'=>'json',
'success'=>'js:function(data){
if(data.result==="success"){
document.getElementById("review-form").reset();
alert("this worked");
}else{
console.log(error)
}
}'
)
)?>
form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'review-form',
'enableAjaxValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true),)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="rating-row">
<?php $this->Widget('CStarRating', array(
'model'=>$model,
'attribute'=> 'star',
'minRating'=>.5 ,
'maxRating'=>5 ,
'starCount'=>5 ,
'ratingStepSize'=>.5
));?>
</div>
<div class="rating-row">
<label>Reviews</label>
<?php echo $form->textArea($model,'review'); ?>
<?php echo $form->error($model,'review'); ?>
</div>
Method 1:
Assign a class for all textbox, textarea, Dropdown. For example, frm_inp_ctrl
Then, do $(".frm_inp_ctrl").val(""); in ajax done()
Method 2:
Do reset with form id as below.
$("#review-form :input").val("");

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