put data into CKEditor field with ajax - javascript

I have a modal for the modification of a entity in my project. When I put data in the modal, only the CKeditor field is empty.
I have tested different solutions but so far none of them work. I checked, the data I want to put in the CKEditor field is not null or non-existent.
Thank you for your help.
Ajax :
function ($) {
function remplirFormSociete(modal,reponse){
alert(reponse['INFO']);
modal.find('input#edit_form_Id').val(reponse['Id']);
modal.find('input#edit_form_NOM').val(reponse['NOM']);
modal.find('select#edit_form_CATEGORIES').val(reponse['CATEGORIES']);
modal.find('input#edit_form_INFO').val(reponse['INFO']);
modal.find('input#edit_form_HOST').val(reponse['HOST']);
modal.find('input#edit_form_NOM_USER').val(reponse['NOM_USER']);
modal.find('input#edit_form_MDP').val(reponse['MDP']);
}
$(document).ready(function(){
//Lorsque l'utilisateur édit un employé temporaire
$('#EditSociete').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
var modal = $(this);
if(recipient){
$.ajax({
url: BaseURL+"/societe/ajax/Societe",
method: "post",
data: {Id:recipient},
success : function(reponse) {
remplirFormSociete(modal,reponse[recipient]);
}
});
} else {
var reponse = [];reponse['Id']='';reponse['CATEGORIES']='';reponse['INFO']='';reponse['HOST']='';reponse['NOM_USER']='';reponse['MDP']='';
remplirFormSociete(modal,reponse);
}
});
});
}) (jQuery);
in the form :
->add('INFO', CKEditorType::class, array('attr' => array('class' => "form-control"),
'label' => 'Information :',
'required' => false,
'label_attr' => array('class' => 'col-md-2 control-label')))

I think this will resolve your problems:
CKEDITOR.instances.editor1.setData( '<p>This is the editor data.</p>' );
reference

Related

Datepicker is not a function after ajax request

I'm writing simple search engine in Lumen framework.
I have a list of status for example. The user can get one of status from the list and after click search button then in the page, I need to load data with chosen status.
One of the element is datepicker. And this datepicker work great when I refresh the page or go to the page by GET method. But I have a problem when I go on the page by POST method from my click "SEARCH". There is some code from my view where I get status from the list and pass to my controller action:
<script type="text/javascript">
jQuery(document).ready(function ($) {
var clientId = null;
var status = null;
$("[name='deadline']").datepicker(); //there I have this error comunicat
$('#clients').on('change', function () {
clientId = $(this).val();
});
$('#statuses').on('change', function () {
status = $(this).val();
});
$('#searchForPremium').on('click', function () {
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
})
});
</script>
And there is controlelr action:
public function clientsPremium()
{
$premiumTexts = NULL;
$premiumClients = \App\Text::getPremiumClients();
$premiumTexts = \App\Text::getPremiumTexts();
$statuses = \App\Text::getStatus();
if (Request::isMethod('get')) {
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts]);
}
if (Request::isMethod('post')) {
$clientID = Request::get('client_id');
$statusName = Request::get('status');
if ($clientID != NULL) {
$premiumTexts = $premiumTexts->where('text.client_id', $clientID);
}
if ($statusName != NULL) {
$premiumTexts = $premiumTexts->where('text.status', $statusName);
}
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return response()->json(view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts])->render());
}
}
Then I have error "Uncaught TypeError: $(...).datepicker is not a function...". I cant understand how it is work and why I got this message. It appear only when I click to search button.
It is $('body').empty().html(data); or my controller action:
return response()->json(view('admin.clients-premium', ['copywriters' => $copywriters, 'statuses' => $statuses, 'positioners' => $positioners, 'clients' => $premiumClients, 'texts' => $premiumTexts, 'allowedTemplates' => $allowedTemplates, 'section' => 'clients.premium'])->render());
I tried to use $.noConflict(); but there is no effect for me. Can anyone look at my code and try to help me what should I change? I think my return "response()->json(view..." reload all page and get my jquery-ui multiple time. But I can wrong. Can anyone help me?
Reinitialize it after you change content from ajax response.
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$("[name='deadline']").datepicker();
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
After ajax success destroy the datepicker and reinitialize it as below:
$('body').empty().html(data);
$("[name='deadline']").datepicker("destroy");
$("[name='deadline']").datepicker();
you clear entire body so may be possible you include js css in body so please add and remove this div instead of entire body and if you add dynamic datepicker to any text box please use
$("[name='deadline']").datepicker(); on ajax response .

Load Content after specific time by ajax

I am trying to get data from database without reloading. So I did this
Code In PasteBin
after doing that this is the ajax part for click
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
}
}
});
}
this is the ed_action.php file
$func = new functions();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$ed_value = $_POST['ed_value'];
$p_authority_id = $_POST['p_authority_id'];
$user_data = array(
'ed_action' => $ed_value
);
$where_cond = array(
'where' => array('p_authority_id' => $p_authority_id),
'cross_check' => 'and',
'return_type' => 'single'
);
$table_name = 'p_authrity_user';
$update = $func->update($table_name, $user_data, $where_cond);
$ed_action_data = $func->select($table_name, $where_cond);
}
I successfully retrive the data by click. But Now I want when I click on the enable button it will show the disable button without reloading and when click on disable, it should be show the enable button. so what should I do?
Please can you help me?
As I mentioned in comments: In your success function of the ajax request you can just toggle the visibilty of the two buttons.
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
toggleButtons();
}
}
});
}
function toggleButtons(){
var enableBtn = $('button.ed_action.ed_action_enable'); // add class ed_action_enable to button so you can get it here
var disableBtn = $('button.ed_action.ed_action_disable'); // add class ed_action_disable to button so you can get it here
enableBtn.toggle(); // toggles visibility of element
disableBtn.toggle(); // toggles visibility of element
/* shorter code for this:
$('button.ed_action.ed_action_enable').toggle;
$('button.ed_action.ed_action_disable').toggle;
*/
}
For this to work you would need to
1: output both buttons into the html (disable btn hidden)
2: add one more class to the buttons so you can get them easily with jquery

function save ajax error

i have made function where i can add a row after confirming. the problem is, after submit button, the tables dont reload and show error function alert.actually data success saved and i have to refresh the page so that the table can reload. here is my ajax jquery code:
function reloadPage()
{
window.location.reload()
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('activity/save')?>";
} else {
url = "<?php echo site_url('activity/update_activity')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form-input').serialize(),
dataType: "JSON",
success: function(data)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
<button id="btnSave" onclick="save()" class="btn green">
"fa fa-save"> save</button>
my controller:
public function save() {
$actype = $this->input->post('actype');
$activity_name = $this->input->post('activity_name');
$project = $this->input->post('project');
$portion = $this->input->post('portion');
$activity = $this->input->post('actid');
$data = array(
'activity_type_id'=>$actype,
'activity_name' =>$activity_name,
'project_id' =>$project,
'portion' =>$portion,
'activity_id' => $activity
);
$this->activity->insertactivity($data);
redirect("activity/input");
}
after i've clicked button save,alert('Error adding / update data'),but actually after reload page data has saved.
where is code error in my ajax code?
Force a reload from the server.
window.location.reload(true);
When you don't specify true the reload may be from the browser cache if available.
Also, in the controller, redirect("activity/input"); is not the appropriate response to an AJAX request. Try something like this instead.
$this->activity->insertactivity($data);
echo json_encode(array('result' => TRUE));
Your controller code could also be much more concise. Consider this
public function save()
{
$data = array(
'activity_type_id' => $this->input->post('actype'),
'activity_name' => $this->input->post('activity_name'),
'project_id' => $this->input->post('project'),
'portion' => $this->input->post('portion'),
'activity_id' => $this->input->post('actid')
);
//Assuming insertactivity returns TRUE if the insert works and FALSE if not
$results['result'] = $this->activity->insertactivity($data);
echo json_encode($results);
}
You can check the "result" in success function
success: function(data)
{
if(data.result === true)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
} else {
//do something to the DOM to tell about the problem
//which probably means you should add that to your controller's response.
}
},

prestashop-create new form with ajax onclick

Hi i'm new with prestashop 1.6 and i use jquery's $.ajax to call a PHP script . what i wan,t is to create new form when i click on button and this is my code :
in the catproduct.php :
public function clickme(){
$html = 'Click me
<div id="myFormm"></div>
<script type="text/javascript">
$( ".displayForm" ).click(function() {
$.ajax({
url: "'._MODULE_DIR_.$this->name.'/ajax.php",
context: document.body,
})
.done(function(data) {
$( "#myFormm" ).html( data );
alert( "Load was performed." );
});
})
</script>';
return $html;
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Add new category'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('FCI'),
'name' => 'FCI',
),
),
'submit' => array(
'title' => $this->l('Save')
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCatForm';
$helper->fields_value['FCI'] = 'ddddd';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='
.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
return $helper->generateForm(array($fields_form));
}
the ajax.php file (the ajax file call the renderForm() function to create new form):
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
include_once('catproduct.php');
$module = new catproduct();
echo $module->renderForm();
the done function return nothing . please help me i spend two days searching for solution
Example of ajax call in Prestashop (front-office) :
$( document ).ready(function() {
var form = $('.MyForm');
form.submit(function(e) {
$.ajax({
type: 'POST',
url: '../modules/MyModule/controllers/front/MyFrontController.php',
data: $(this).serialize(),
dataType: 'json',
success: function(jsonData) {
console.log(jsonData);
}
});
e.preventDefault();
});
});
Console shows results. If not, there is a problem with php file.
Here is a sample of PHP file :
<?php
include(dirname(__FILE__).'/../../../../config/config.inc.php');
include(dirname(__FILE__).'/../../../../init.php');
include(dirname(__FILE__).'/../../classes/MyUsefulModuleClass.php');
if (Tools::getIsset('my_useful_id')) {
echo Tools::jsonEncode('Ajax return fine')); }?>
Check if config.inc.php and init.php are called. Always console.log() your results while working on it.
Then try to separate form creation, you can use only HTML, not sure if you can create forms using helpers, and show it using Ajax. I think that most of modules use HTML only

how to send variable from gridview yii to javascript

i need your help. my purpose is update data in modal form, but i get problem and almost one week i didn't find the solution. the problem is i don't know how to send id from gridview to javascript function and in javascript function will throught to controller but in controller I can't get the variable of id. this my code.
//code in admin.php
'class'=>'bootstrap.widgets.TbButtonColumn',
'template'=>'{view} {update} {delete} ',
'buttons'=>array(
'update' => array
(
'click'=>'js:function()
{
var idcab=($(this).parent().parent().children(":nth-child(1)").text());
editCabang(idcab);
$("#dialogClassroom").dialog("open");
}',
),
$this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog
'id'=>'dialogClassroom',
'options'=>array(
'title'=>'Tambah Cabang',
'autoOpen'=>false,
// set to auto open for testing only
'draggable'=>true,
'resizable'=>true,
'closeOnEscape' => true,
// 'show'=>'fade',
// 'hide'=>'fade',
'position'=>array(300,50),
'modal'=>true,
'width'=>'700px',
'height'=>'auto',
'close' => 'js:function(event, ui) { location.href = "./admin" }'
),
));?>
<div class="divForForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
function editCabang(idcab)
{
//alert(idcab); when i alert the id show
<?php echo CHtml::ajax(array(
'url'=>array('Tbcabang/update'),
'data'=> 'js:$(this).serialize(),"idcab2":$(this).idcab', //i want send variable idcab2 to controller
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if (data.status == 'failure')
{
$('#dialogClassroom div.divForForm').html(data.div);
// Here is the trick: on submit-> once again this function!
$('#dialogClassroom div.divForForm form').submit(editCabang);
}
else
{
$('#dialogClassroom div.divForForm').html(data.div);
setTimeout(\"$('#dialogClassroom').dialog('close') \",3000);
}
} ",
))
?>;
return false;
}
//code in controller (update action)
public function actionUpdate()
{
//$id=100;
$id=$_POST[idcab2]; //the id is empty
$model=$this->loadModel($id);
if(isset($_POST['Tbcabang']))
{
$model->attributes=$_POST['Tbcabang'];
if($model->save())
{
if (Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'success',
'div'=>"Tambah cabang berhasil"
));
exit;
}
else
// $this->redirect(array('view','id'=>$model->id));
$this->redirect(array('view','id'=>$model->id_cabang));
}
}
if (Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'failure',
'div'=>$this->renderPartial('_form', array('model'=>$model), true,true)));
exit;
}
else
$this->render('update',array('model'=>$model,));
}
The expression js:$(this).serialize(),"idcab2":$(this).idcab doesn't make any sense..
How is $(this) going to work, and it should be just a javascript object..
To pass the idcab variable passed to the function to the controller you need to use just the idcab not $(this).idcab
There are various ways you can fix it . But what I get you want to show dialog for editing a grid so the best way is to to pass id to that dialog e. g
//code in admin.php
'class'=>'bootstrap.widgets.TbButtonColumn',
'template'=>'{view} {update} {delete} ',
'buttons'=>array(
'update' => array
(
'click'=>'js:function()
{
var idcab=($(this).parent().parent().children(":nth-child(1)").text());
//set the id
$("#dialogClassroom").dialog("option","idcab",idcab);
$("#dialogClassroom").dialog("open");
}',
),
Then add open event to dialog to fetch the data/or set the form :
'close' => 'js:function(event, ui) { location.href = "./admin" }'
'open' => 'js:function(event, ui) {
var idcab=$(ui).dialog("option","idcab");
//fetch the data for idcab and fill the dialog form , is that you want ?
//if yes call the ajax function now
}'
Probably you can set the open event function of dialog to set a hidden form field. You know what you are doing .

Categories