I have a database table for my saved template. All are in HTML format and I want to get a specific template using an AJAX.
Here's my code:
HTML part
<div class="form-group">
<label>Select Template: <span class="text-info">(*Optional)</span></label>
<select class="form-control" name="load_template" id="load-template">
<?php if(count($templates) > 0) { ?>
<option value="">-- load template --</option>
<?php foreach($templates as $temp) { ?>
<option value="<?php echo $temp['id']; ?>"><?php echo $temp['template_name']; ?></option>
<?php } ?>
<?php } else { ?>
<option value="">There are no saved templates</option>
<?php } ?>
</select>
</div>
JS part
$('#editor').ckeditor();
$('#load-template').on('change', function(){
var id = $(this).val();
//do some ajax to get content...
console.log(id);
$.ajax({
url: "<?php echo site_url('users/user/getLoadTemplate'); ?>",
data: {template_id: id},
dataType: 'html',
type: 'post',
beforeSend: function() {},
success: function(template) {
$('#editor').html(template);
console.log(template); //ok it shows the HTML but how can I load it in my ckeditor?
},
error: function() {
alert('Unable to load template. Error in AJAX');
}
});
});
PHP side
public function getLoadTemplate() {
$type = $this->input->post('template_id');
$get_template = $this->Users_model->getLoadTemplate($type);
echo $get_template['template'];
}
How can I load my ajax response HTML in the CKEDITOR?
Instead of this
$('#editor').html(template);
Try this
CKEDITOR.instances['editor'].insertHtml(template)
or
CKEDITOR.instances.editor.insertHtml(template)
Related
I want to make a dynamic dropdown using selectpicker bootstrap library, codeigniter 4, and AJAX.
I got a problem when I trigger to select the first dropdown, the second dropdown's option appended at third times select. Here I provide the video :
https://youtu.be/AVUBlhajZ_k
Here is my code:
MODEL :
function barangBySupp($namaSupp)
{
$supp = $namaSupp;
$data = $this->db->query("SELECT * FROM tablebarang WHERE supplier='$supp'");
$result = $data->getResultObject();
return $result;
}
CONTROLLER :
public function post()
{
$request = service('request');
if ($request->isAJAX()) {
$namaSupp = $request->getVar('id');
$data = $this->barangMasukModel->barangBySupp($namaSupp);
echo json_encode($data);
}
}
JAVASCRIPT
$("#selectOptSupp").on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue){
const id = $('#selectOptSupp option:selected').data('nama');
const alamat = $('#selectOptSupp option:selected').data('alamat');
const noTelp = $('#selectOptSupp option:selected').data('notelp');
$('[name=namaSupp]').val(id);
$('[name=alamatSupp]').val(alamat);
$('[name=noTelp]').val(noTelp);
$.ajax({
type: "post",
url: "/BarangMasuk/post",
dataType: "JSON",
data: {
id: id
},
cache: false,
success: function(response) {
$.each(response, function(index, data){
$('#selBarang').append('<option data-nama="'+data['namaBarang']+'" data-harga="'+data['harga']+'" data-unit="'+data['unit']+'" value="'+data['namaBarang']+'" data-tokens="'+data['namaBarang']+'">'+data['namaBarang']+'</option>').selectpicker("refresh");
});
SHORT VIEW CODE :
<select id="selectOptSupp" class="form-control selectpicker" data-live-search="true">
<?php foreach ($supplier as $value) : ?>
<option data-nama="<?= $value['namaSupp']; ?>" data-notelp="<?= $value['noTelpSupp']; ?>" data-alamat="<?= $value['alamatSupp']; ?>" data-tokens="<?= $value['namaSupp'] ?>" name="" value="<?= $value['namaSupp'] ?>"><?= $value['namaSupp'] ?>
</option>
<?php endforeach; ?>
</select>
<select id="selBarang" class="form-control selectpicker" data-live-search="true">
// OPTION DATA SHOULD APPEND HERE WHEN #selectOptSupp fires
</select>
I am working on project that uses a dynamic or dependent dropdown list on CodeIgniter. This is my noob logic, the country value from Views passed to Models, then the Models get state data with same country value from Views, then Controllers get state data from that Models and pass it again to Views. And the problem is the state dropdown list show nothing.
Sorry, iam new in coding.
//This is the Controllers (Pkl.php)
$data['all_country'] = $this->Server_Model->get_country_model();
$data['all_state'] = $this->Server_Model->get_state_model();
$this->load->view('contents/page_dashboard', $data);
//This is the Models (Server_Model.php)
function get_country_model(){
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("country");
$que = $db_jarlap->get();
return $que->result();
}
function get_state_model(){
$kakakoko = filter_input(INPUT_POST, 'country_id');
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("state");
$db_jarlap->where(" id_country = $kakakoko ");
$que = $db_jarlap->get();
return $que->result();
}
//This is the Views Content (page_dashboard.php)
<script src="<?php echo base_url() ?>resources/js/jquery-3.3.1.min.js"</script>
<script>
$(document).ready(function(){
$('#formCountry').change(function(){
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ? >application/models/Server_Model.php",
method: "POST",
data: {country_id:country_id},
success: function(data) {
$('#formState').html(data);
}
});
});
});
</script>
<select name="formCountry" id="formCountry">
<?php foreach($all_country as $semua_country): ?>
<option value="<?php echo $semua_country->id_country; ?>"><?php echo $semua_country->nama_country; ?></option>
<?php endforeach; ?>
</select>
<select name="formState" id="formState" >
<?php foreach($all_state as $semua_state): ?>
<option value="<?php echo $semua_state->id_state; ?>"><?php echo $semua_state->nama_state; ?></option>
<?php endforeach; ?>
</select>
Thanks for your help.
You should not directly call model, instead call the Pkl controller, I'm assuming that you are using the index() method on Pkl controller :
$(document).ready(function () {
$('#formCountry').change(function () {
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ?>pkl", // using Pkl controller
method: "POST",
data: {
country_id: country_id
},
success: function (data) {
$('#formState').html(''); // empty the select option element
$.each(data, function(){ // format each option returned from Pkl controller
$("#formState").append('<option value="'+ this.id_state +'">'+ this.nama_state +'</option>');
});
}
});
});
});
I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}
I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
Another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
View
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
Controller
function showCategory() {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
}
My category table contains: category_id, category_name, brand_id.
use ajax onchange. .in your view file..
<select name="brand" class="form-control" id="brand" required onchange="brand(this.value,'divid')">
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<div id="divid">
<select name="category" class="form-control" id="category" required>
<option>Select Category</option>
</select>
</div>
<script>
function brand(id,divid)
{
$.ajax({
type: "POST",
data: "pid="+id,
url: '<?php echo base_url(); ?>receiving/showCategory ?>',
success: function(html){
$('#'+divid).html(html);
}
});
}
</script>
in your function showCategory() :
<div id="divid">
<select name="category" class="form-control" id="category" required>
$brandid = $this->input->post('pid');
//you can pass this brand id to your query and echo the category in option value//
<option>//your result //</option>
</select>
</div>
You need to concat the all values in success function like
options += '<option>'+msg.category[i].category_name+'</option'>;
$('#category').html(options);
Look like your code is correct, but need to change a little bit in ajax request.
You need to parse the data return into parseJson first. The options variable in for loop should concatenate with += code. See example below:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var data = $.parseJSON(msg),options;
for(var i = 0; i<data.length; i++) {
options += '<option>'+data.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
In case you have a problem with this code, you should change variable in codeigniter part for the variable that hold the results. You can see my working code below as an example :
Js Code
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>controller/function_name',
dateType : 'json',
data : {depart_id : _depart_id.val()},
success : function(data){
var json_data = $.parseJSON(data),
options;
for(var i = 0; i<json_data.length; i++){
options += '<option value="'+json_data[i].destination_id+'">'+json_data[i].location+'</option>';
}
_destination_id.html(options);
}
});
Here is codeigniter code(php)
$destination = $this->custom_model->get_destination_distinct($table,$where);
echo json_encode($destination);
I want to create state/city dependent dropdown in wordpress. This is my js file code
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#state').change(function(){
var $location = $(this).val();
alert($location);
$.ajax({
url:'ajaxurl',
type: 'post',
data: ({action : 'getcity'}),
success: function() {
$("#district").removeAttr("disabled");
$("#district").append(results);
}
});
});
});
</script>
I have created function called getcity in function.php and add hooks and action to that function and add this js file to theme js folder and enque it in function file. I m getting empty alert ?? Anybody has any idea??
add_action('wp_head','ajaxurl');
function ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php')."getcity"; ?>';
</script>
this is dropdown code
<p class="half_form half_form_last">
<label for="property_country"><?php _e('State ','wpestate'); ?></label>
<select name="state" id="state" class="select-submit2">
<option value="">Select state</option>
<?php
$result=$wpdb->get_results("select distinct(state) from tblcitylist");
//$wpdb->get_results($query);
foreach($result as $row) {
$state=$row->state;
echo '<option value="">'.$state.'</option>';
}
?>
</select>
</p>
In function.php
function getcity(){
global $wpdb;
if($_POST['state'])
{
$id=$_POST['state'];
$result=$wpdb->get_results("SELECT * FROM tblcitylist WHERE
state='$id'");
//$wpdb->get_results($query);
foreach($result as $row) {
$city_name = $row-
>city_name;
$city_id = $row->city_id;
echo '<option
value="'.$city_id.'">'.$city_name.'</option>';
//echo '<option value="'.'0'.'">'.'New Phase'.'</option>';
}
}
}
add_action("wp_ajax_nopriv_getcity", "getcity");
add_action("wp_ajax_getcity", "getcity");
I have included js file as follows in functions.php
wp_enqueue_script('my_own_js',
get_template_directory_uri().'/js/my_own_js.js',array('jquery'));
I think it's better to post it as an answer. I'd delete the var ajaxurl from the functions.php and use it inside the page. Then I don't see where you pass the location to the ajax. It should look like this:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#state').on('change', function() {
var location = this.value;
alert(location);
$.ajax({
type: "POST",
url:'<?php echo admin_url('admin-ajax.php'); ?>',
data: ({'action' : 'getcity', 'location' : location }),
success: function(results) {
$("#district").removeAttr("disabled");
$("#district").append(results);
}
});
});
});
</script>
then the Dropdown should look like this
<select id="state">
<option value="state1">state1</option>
<option value="state2">state2</option>
...
</select>
And for the getcity you have to get the right $_POST:
function getcity(){
global $wpdb;
if($_POST['location']){
$id=$_POST['location'];
$result=$wpdb->get_results("SELECT * FROM tblcitylist WHERE state='$id'");
$html = '';
foreach($result as $row) {
$city_name = $row->city_name;
$city_id = $row->city_id;
$html .= '<option value="'.$city_id.'">'.$city_name.'</option>';
}
}
}
add_action("wp_ajax_nopriv_getcity", "getcity");
add_action("wp_ajax_getcity", "getcity");