Ajax Based Select2 Codeigniter Issue - php

Hi friends I am trying to do a Ajax Based select2 using codeigntier. I am using 4.0.1 Select2 Version. I am getting the response from ajax but the result is not showing in SELECT2. Can you please check the code below and tell me where I have done wrong.
Here is my Model
//Model
class AddServiceAreaModel extends CI_Model
{
//Function for getting suburbs from restaurant
//MAIN FUNCTION FOR DATATABLE
public function get_postcodes($q)
{
$query = $this->db->select('postcode')
->group_by('postcode')
->like('postcode', $q)
->get('tbl_suburb');
$json = $query->result_array();
echo json_encode($json);
}
}
Here is my View
<div id="page-inner">
<div class="row">
<div class="col-md-12">
<!-- Advanced Tables -->
<div class="panel panel-default">
<div class="panel-heading"> Add Service Area</div>
<form id="addFrm">
<div class="panel-body">
<div class="">
<!-- Modal content-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="postcode">Postcode</label>
<select class="selectbox form-control required" id="postcode" name="postcode"></select>
</div>
</div>
</div>
</div>
<button type="submit" id="btnSubmit" class="btn btn-success">Update</button>
</div>
</form>
</div>
<!--End Advanced Tables -->
</div>
</div>
<!-- /. ROW -->
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#postcode').select2({
placeholder: 'Select for tag',
ajax: {
url: '<?php echo base_url('restaurant/addservicearea/get_postcode') ?>',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
});
</script>
Here is My Controller
public function get_postcode()
{
//$_GET['term']. Term is the variable is in jquery-ui.js file.
if(isset($_GET['term']))
{
$q = $_GET['term'];
$this->AddServiceAreaModel->get_postcodes($q);
}
}
The output showing blank result even i got the response in ajax.
Can you please help me where i am wrong? Thanks in advance.

Earlier I thought you need a success function, but select2 uses the processResults function. It turns out, you just need that to look like this:
processResults: function (data) {
return {
results: data.items
};
},
Then, in PHP when you send back your response, select2 expects an items element, and then arrays that contain "id" and "text":
// This is just a sample, of course yours will be dynamic
echo json_encode(array(
'items' => array(
array('id' => '0', 'text' => '12345'),
array('id' => '1', 'text' => '12346'),
array('id' => '2', 'text' => '12347')
)
);
I tested this out locally, and I was getting results after making these changes. Should work for you now.

Related

Refresh table after request Ajax is success

I am beginner with Ajax. I try refresh a table when user select an option in form-select filter. I use Symfony and Twig.
I get the new datas in the Json format in my console when i select a new filter, but the table does'nt show with the new datas. I failed to find the solution when my request ajax is success.
My Select filter :
{{ form_start(form) }}
<div class="container-fluid">
<div class="row">
<div class="col-fluid">
{{ form_row(form.isAttending) }}
</div>
<button type="submit" class="btn btn-outline-success mb-2">{{ button_label|default('Envoyer') }}</button>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-1-fluid">
{{ form_row(form.active) }}
</div>
</div>
</div>
{{ form_end(form) }}
In my Controller :
/**
* #Route("/ajax", methods={"GET", "POST"})
*/
public function testAjax(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array(
'status' => 'Error',
'message' => 'Error'),
400);
}
if($request->request->has('isAttending')) {
$preSelect = $request->request->get('isAttending');
return new JsonResponse(
$this->queryFollowingFilter($preSelect),
200);
}
}
In my Template :
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data['isAttending'] = $field.val()
console.log(data)
$.ajax({
type: "POST",
url: "/campagnestel/ajax",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
</script>
Any ideas ?
According to your question and comments your problem is not Symfony, not Ajax and also not Twig related. You get the correct data and you just do not know how to manipulate the DOM. DOM manipulation is a basic capability of JavaScript.
Here you can learn how to manipulate the DOM: https://www.w3schools.com/js/js_htmldom.asp
And here you can learn how to easily can manipulate it with jQuery which you are obviously using: https://www.w3schools.com/js/js_jquery_dom.asp
Sample:
$('#my-table').append(response.myWhatever);

Data not being updated in CI

I am designing CI application and is stuck in ajax query. Basically the function which i have written is taking id as null when save button is pressed even though when i click on edit button it shows its picking up the correct id. Looks like I have some error in function. BELOW IS THE FUNCTION WHICH i HAVE WRITTEN :
public function ajax_update()
{
$this->_validate();
$data = array(
//'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
//'gender' => $this->input->post('gender'),
//'address' => $this->input->post('address'),
//'dob' => $this->input->post('dob'),
//'tid' => $this->input->post('tid'),
'name' => $this->input->post('tname'),
);
$this->transport->update(array('tid' => $this->input->post('tid')), $data);
var_dump( $this->input->post());
echo json_encode(array("status" => TRUE));
}
the update function is
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
View is
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><html lang="en">
<head>
<?php include_once("header.php"); ?>
</head>
<body class="fixed-nav sticky-footer bg-dark">
<!-- Navigation-->
<?php include_once("sidebar.php"); ?>
<div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
Home
</li>
<li class="breadcrumb-item active">Manage Transport</li>
</ol>
<!--Button to add Client
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2"><i class="fa fa-plus" style="color:white"></i> Add Transport</button>-->
<button class="btn btn-success" onclick="add_transport()"><i class="glyphicon glyphicon-plus"></i> Add Transport</button>
<br>
<br>
<!-- Example DataTables Card-->
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-table"></i> View Transport Details</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th style="width:90%;">Transport Detail</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Transport Detail</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid-->
<!-- /.content-wrapper-->
</div>
<!-- Modal to add Transport-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Transport Details</h4>
<button type="button" class="close" data-dismiss="modal">x</button>
</div>
<div class="modal-body">
<!--<form role="form" name="form1" action="<?php echo base_url('search/add_trans'); ?>" method="post" autocomplete="on">-->
<form action="#" id="form" class="form-horizontal">
<div class="row">
<div class="col-md-2">
<label>Transport Details</label>
</div>
<div class="col-md-10" id="new_data">
<textarea name="tname" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<!--<input type="submit" name="submit" class="btn btn-primary" value="Submit">-->
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal Finishes-->
</div>
<?php include_once 'footer.php'; ?>
<script type="text/javascript">
var save_method; //for save method string
var table;
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_transport()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Transport'); // Set Title to Bootstrap modal title
}
function edit_transport(id)
{
//var table = $('#dataTable').DataTable();
// console.log( table.row( id ).data() );
// $("#tid").val(data.tname);
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('transport/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
// $('[name="id"]').val(data.id);
//$('[name="tid"]').val(data.tid);
$('[name="tname"]').val(data.tname);
// $('[name="firstName"]').val(data.firstName);
//$("#tid").val(data.tname);
//alert(data.tname);
// $('[name="lastName"]').val(data.lastName);
// $('[name="gender"]').val(data.gender);
// $('[name="address"]').val(data.address);
// $('[name="dob"]').datepicker('update',data.dob);
// $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Transport'); // Set title to Bootstrap modal title
// new_data
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> <input type="text" name="row_id" value="'+id+'" readonly hidden >');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
//function reload_table()
//{
// table.ajax.reload(null,false); //reload datatable ajax
//}
function reload_table() {
table.api().ajax.reload(null, false); //reload datatable ajax
}
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('transport/ajax_add')?>";
} else {
url = "<?php echo site_url('transport/ajax_update')?>";
}
// console.log($('#form').serialize());
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#myModal').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> ');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>');
}
});
}
function delete_transport(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('transport/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function reload_table()
{
//console.log(table);
table.api().ajax.reload( null, false );
}
$(document).ready(function() {
//datatables
table = $('#dataTable').dataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('transport/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
Any pointers please ?

How to pass the button value in ajax url and display the json response in bootstrap panel body?

Laravel View code:
<div class="container" style="display:none;" id="panel1">
<div class="panel panel-default">
<div class="panel-heading" style="color:#0000FF" data-toggle="tooltip" title="Gateways!">
<input type="button" value="Haghway Lite" style="background-color:transparent;border:none;width:100%;height:100%;" name="button1" id="button1"><font size="5"></font>
</div>
<div class="panel-body" align="center">
<img src="haghwaylitecontroller.jpg" width="100" height="100">
</div>
</div>
</div>
This my view code.
Script(ajax):
<script type="text/javascript">
$(document).ready(function() {
$("#button1").click(function(){
var button1 = $(this).val();
if(button1) {
$.ajax({
url: "{{url('panelview').'/'}}"+button1,
type: "GET",
dataType: "json",
success:function(data) {
$.each(data, function(key,value) {
$("#panel1").append('<div "'+ value.panel1 +'"></div>');
});
//alert("success");
}
});
}else{
alert("failed");
}
});
});
In this script code, I calling the ajax function with the button id and trying to pass the value of button to be redirected to the mentioned url and the returned json response to be displayed on the panel body. Here if I am trying to print the button value it alerts NaN
Route:
Route::get('panelview/{button1}','viewController#newProduct');
Controller:
public function newProduct($button1)
{
$users=addModel::select('Desc')->where('Pname',$button1 )->first();;
return json_encode($users);
}
The controller code should fetches the correspoding record based on the value of button and return the response.

jQuery Load function not loading inside a div but loads new page

I have following html markup:
<button class="btn btn-success" id="search"><span class="glyphicon glyphicon-search"></span> Search</button>
<div class="row text-center" style="margin-top: 50px;">
<div class="col-md-12">
<div id="content-area"></div>
</div>
</div>
I want to load a page.php inside #content-area. This is the jQuery I used for this:
$("#search").click(function(){
$("#content-area").load("page.php");
});
The problem is page.php is not loading inside #content-area but it loads as a new page itself. I want page.php to load inside #content-area. Please help.
//you have to make ajax call to get content without page load.
$("#search").click(function(){
$.ajax({
url: 'page.php', // point to server-side PHP script
dataType: 'json', // what to expect back from the PHP script, if anything
type: 'POST',
success: function (data) {
if (data.status === 'success')
{
$("#content-area").html(data);
}
else if (data.status === 'error')
{
alert(data.message);
}
},
error: function (e) {
return false;
Msg.show('Something went wrong, Please try again!','danger', 7000);
}
});
});
I have tried below code its working fine for me.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<button class="btn btn-success" id="search"><span class="glyphicon glyphicon-search"></span> Search</button>
<div class="row text-center" style="margin-top: 50px;">
<div class="col-md-12">
<div id="content-area"></div>
</div>
</div>
<script>
$("#search").click(function(){
$("#content-area").load("test1.php");
});
</script>

Laravel Ajax Success Message: Returning Contact Form Name Input

Thanks guys for looking into my question. I have this form that I use ajax to submit to the mysql database using laravel. I'm trying to pull the most recent entry which would be the user's submission. I am error free, however I'm getting the most recent before the user submitted form. I wrote the code in the IndexController. Maybe i should use Jquery/Java? Here is what I have:
Route:
Route::resource('/', 'IndexController');
IndexController:
public function index()
{
$recent = Contact::orderby('created_at', 'desc')->first();
return view('index', compact('recent'));
}
Html:
<div class ="row">
<div class ="col-lg-12 contact">
<div id = "ctn-box" class = "row pad-med">
{!!Form::open(array('url' => 'contacts', 'class' => 'contacting')) !!}
<h1 class = "txtc">CONTACTO</h1>
<div class = "form-group col-xs-3">
{!!Form::label('name', 'Nombre:')!!}
{!!Form::text('name', null, ['class'=> 'form-control area'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::label('email', 'Email:')!!}
{!!Form::email('email', null, ['class'=> 'form-control area', 'placeholder' => 'example#gmail.com'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::label('phone', 'Número de Teléfono:')!!}
{!!Form::text('phone', null, ['class'=> 'form-control area', 'placeholder' => '657-084-052'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::submit('Contacto', ['class'=> 'btn btn-danger outline form-control contact', 'id' => 'fuck'])!!}
</div>
{!! Form::close() !!}
<div id = "thankCtn" class = "txtc">
<h1>Muchas Gracias {{$recent->name}}!</h1>
<p>Siguemos en contacto. Mientras tanto, visítanos en nuestro officina abajo.</p>
</div>
</div>
<div class = 'contact-info'>
<iframe class = "googimg" frameborder="0" scrolling="no" src="https://maps.google.com/maps?hl=en&q=Passatge hort dels velluters, 5&ie=UTF8&t=roadmap&z=15&iwloc=B&output=embed"><div><small>embedgooglemaps.com</small></div><div><small>multihoster premium</small></div></iframe>
<div class = "address txtc">
<h1 class = "contacts">Passatge Hort dels Velluters<br> 5, 08008 Barcelona</h1>
<h2 class = "contacts">657-084-052</h2>
</div>
</div>
</div>
</div>
Ajax:
//INDEX CONTACT SUBMISSION//
$('.contacting').on('submit', function(e) {
var base_url = 'http://rem-edu-es.eu1.frbit.net/';
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: "POST",
url: base_url + "contacts",
data: data,
success: function (data) {
$('.contacting').css('opacity', '0');
$('.contacting').animate({
top: '50px'
}, 100, function(){
$('#thankCtn').fadeIn(500);
$('#thankCtn').css('top', '-100px');
});
}
});
});
Before suggesting anything, I should tell you that there could be a little issue with the site. I clicked the "Contact" button without filling the fields. Guess what? I got a response: "Muchas Gracias New Guy..." I guess the last person used "New Guy" as his name. Sounds insecure?!
Now, to my answer, I'll suggest you do it with jQuery, in the success callback of $.ajax(). Something like this:
IndexController
public function index()
{
$recent = Contact::orderby('created_at', 'desc')->first();
return json_encode(compact('recent')); // Returning view(...) means the ajax call will receive HTML page content
}
HTML
<div id = "thankCtn" class = "txtc">
<h1>Muchas Gracias <span id = "newGuy"></span>!</h1>
<p>Siguemos en contacto. Mientras tanto, visítanos en nuestro officina abajo.</p>
</div>
jQuery
success: function (res) { // note that I'm changing "data" to "res". It is the result of the ajax call
$('.contacting').css('opacity', '0');
$('.contacting').animate({
top: '50px'
}, 100, function(){
$('#newGuy').text(res.name);
$('#thankCtn').fadeIn(500);
$('#thankCtn').css('top', '-100px');
});
}

Categories