Select2 The Result Cannot Be Load in CodeIgniter - ajax

When I type in my select box the result always show "The result cannot be load". I am using CodeIgniter for my framework and select2 in my select box and am a newbie in CodeIgniter and Select2. I have already search it through all articles that can be related to my problem but it still can't work. I think I messed my ajax but I don't know how and where I should fix it.
Here is my controller
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('admin_model');
}
function search_book(){
$booksClue = $this->input->get('booksClue');
$data_book = $this->admin_model->get_book($booksClue, 'id_book');
echo json_encode($data_book);
}
}
?>
Here is my model
<?php
class Admin_model extends CI_Model{
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->like('id_book', $booksClue);
$data = $this->db->from('book')->get();
return $data->result_array();
}
}
?>
And here is my view
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('.searchingBook').select2({
placeholder: 'Masukkan ID Buku',
minimumInputLength: 1,
allowClear: true,
ajax:{
url: "<?php echo base_url(); ?>/admin/searchbook",
dataType: "json",
delay: 250,
data: function(params){
return{
booksClue: params.term
};
},
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.id_book,
text: item.id_book
});
});
return{
results: results
};
}
}
});
});
</script>
<table>
<tr>
<td><b>ID Buku</b></td>
<td> : </td>
<td>
<select class="searchingBook" style="width: 500px">
<option></option>
</select>
</td>
</tr>
</table>
<br><br>
</body>
</html>
Big thanks for your help!

Update your model function like below:
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->from('book');
$this->db->like('id_book', $booksClue);
return $this->db->get()->result_array();
}

Related

Google chart does not redraw the chart based on a new Ajax filter

How can I make this code update the google chart with new Ajax call data? When I submit from the dropdown list I see the updated data in the echoed results but the chart does not update. It seems like I have place the submit code in the wrong place.
<title>Google Chart in PHP and MySQL</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var drawChart;
$(document).ready(function () {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
$(".submit").click(function() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
var dataArray = [];
$.each(result, function (i, obj) {
dataArray.push([obj.Gender, parseInt(obj.HowMany)]);
});
data.addRows(dataArray);
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});
</script>
</head>
<body>
<center>
<img src="logo.png" style="width:200px;height:60px;">
</center>
<hr style="border: 4px solid blue;" />
<table class="columns" style="width:120%">
<tr>
<td>
<label>Gender filter</label>
<?php
//Connect to our MySQL database using the PDO extension.
$pdo = new PDO('mysql:host=localhost;dbname=panel', 'root', '');
//Our select statement. This will retrieve the data that we want.
$sql = "SELECT DISTINCT Gender FROM employee GROUP BY Gender";
//Prepare the select statement.
$stmt = $pdo->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$Ngender = $stmt->fetchAll();
?>
<!--Start here -->
<form method="post" action="indexdash2.php">
<select name="filter">
<option value="" disabled selected hidden>Choose a filter</option>
<?php foreach($Ngender as $Ngender): ?>
<option value="<?= $Ngender['Gender']; ?>"><?= $Ngender['Gender']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Find">
</form>
</td>
</table>
<hr style="border: 4px solid blue;" />
<h2>DEMOGRAPHICS</h2>
<table class="columns">
<tr>
<td>
<div id="piechart_div" style="border: 1px solid #ccc"></div>
</td>
</tr>
</table>
</body>
</html>
Any help will be appreciated! I am pretty sure I have missed something basic as I am new to this.
first, google's load method only needs to be called once per page load.
afterwards, you can draw the chart, or charts, as many times as needed.
next, google's load method will also wait on the page to load by default.
so we can use load in place of jquery's ready method.
recommend loading google first,
then make the call to get the data and draw the chart.
see following snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
function getData() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON"
}).done(function (result) {
drawChart(result);
});
}
$('.submit').click(getData);
getData();
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
$.each(result, function (i, obj) {
data.addRow([obj.Gender, parseInt(obj.HowMany)]);
});
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});

POST http://localhost/DemoWebsite/wp-admin/custom_Settings.php 404 (Not Found) after ajax call

My server giving me the response as following
when my ajax call to the same page. Before Ajax call everything is working fine on console but after ajax call and updating database, this error is occurring. I think my Ajax_url is not correct but I want to get ajax data on same page that name is "custom_Settings.php" as mentioned in url.
Please help me to solve this error.
Thanks!
jquery-3.4.1.min.js:2 POST
http://localhost/DemoWebsite/wp-admin/custom_Settings.php 404 (Not
Found)
JS
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function(){
saveNewPositions();
});
function saveNewPositions(){
var positions = [];
$j('.updated').each(function(){
positions.push([$j(this).attr('data-index'), $j(this).attr('data-position')]);
$j(this).removeClass('updated');
});
$j.ajax({
url: 'custom_Settings.php',
method: 'POST',
dataType: 'text',
data: {
update: 1,
positions: positions
}, success: function(response){
console.log(response);
}
});
}
</script>
PHP
function wp_pageOrdering_field_settings(){
global $wpdb;
if (isset($_POST['update'])) {
foreach($_POST['positions'] as $position){
$index = $position[0];
$newPosition = $position[1];
}
$wpdb->update(
'wp_page_settings',
array('page_order' => $newPosition),
array('ID' => $index)
);
wp_die();
}
HTML
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title></title>
</head>
<body>
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-4 col-md-offset-4">
<table class="table table-stripped table-hover table-border">
<head>
<tr>
<td>Page Title</td>
</tr>
</head>
<tbody>
<?php
$var = get_option('Accessable_Pages');
$list = implode(",", $var);
$newRes = $wpdb->get_results("SELECT ID, post_title, page_order FROM wp_page_settings WHERE ID IN ($list) ORDER BY page_order ASC",ARRAY_A);
if($newRes){
foreach ($newRes as $value1 ) {
echo '
<tr data-index="'.$value1['ID'].'" data-position="'.$value1['page_order'].'">
<td>'.$value1['post_title'].'</td>
</tr>
';
}
}
?>
</tbody>
</table>
</div>
</div>
</div>

Laravel 5.2 ajax code doesn't work

I developed a simple ajax code.According to this image when click+ qty increase and when click - qty decrease
Code in online _help.blade.php
<head>
<title>Ajax Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>
$(document).ready(function(){
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var increment = $(this).data('increase');
var itemId = $('.cart_quantity_input').val();
$.ajax({
type:'post',
url:'getmsg',
dataType:'json',
data:{
'item_id': itemId,
'increase': increment
},
success:function(data){
$("cart_quantity_input").val(data.qty);
} });
});
});
</script>
</head>
<body>
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-increase="1" > + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{1}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-increase="0" > - </a>
</div>
</body>
<footer>
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
</script>
</footer>
Code in controller function
public function ajaxl(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
if ($request->increase) {
//$cart->increment('qty');
$qty = 2;
} else {
//$cart->decrement('qty');
$qty = 0;
}
//echo"hello ajaxlara:";
return response()->json(array('qty'=> $id), 200);
}
}
And this routes.php
Route::get('/ajax',function(){return view('online_help');});
Route::post('/getmsg','Hello#ajaxl');
When I click + or - the value doesn't change and no error.
Please any one help me
The problem is very small.
This line:
$("cart_quantity_input").val(data.qty);
just you forgot to add . before cart_quantity_input
So change it to be :
$(".cart_quantity_input").val(data.qty);

dynamic codeigniter select not working

controller
car.php
<?php
class Car extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('company_model');
}
public function index()
{
//starts by running the query for the countries
//dropdown
$data['companydrop'] = $this->company_model->company();
//loads up the view with the query results
$this->load->view('car_view', $data);
}
//call to fill the second dropdown with the cities
public function car_model()
{
//set selected country id from POST
echo $company_id = $this->input->post('company_id',TRUE);
//run the query for the cities we specified earlier
$cardata['cardrop']=$this->company_model->car($company_id);
print_r($cardata);
$output = null;
foreach ($cardata['cardrop'] as $row)
{
//here we build a dropdown item line for each
// query result
$output .= "<option value='".$row->car_model."'>".$row->car_model."</option>";
}
echo $output;
}
}
?>
model
company_model
<?php
class Company_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
//fill your contry dropdown
public function company()
{
$this->db->select('company_id,company_name');
$this->db->from('company');
$query = $this->db->get();
// the query mean select cat_id,category from
//category
foreach($query->result_array() as $row){
$data[$row['company_id']]=$row['company_name'];
}
// the fetching data from database is return
return $data;
}
//fill your cities dropdown depending on the selected city
public function car($company_id=string)
{
$this->db->select('car_id,car_model');
$this->db->from('car');
$this->db->where('company',$company_id);
$query = $this->db->get();
return $query->result();
}
}
?>
view
car_view
<html>
<head>
<title>car dealers</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#companydrop").change(function(){
/*dropdown post *///
$.ajax({
url:"<?php echo base_url();?>index.php/car/car_model",
data: {id:$(this).val()},
type: "POST",
success:function(data){
$("#cardrop").html(data);
alert(data);
}
});
});
});
</script>
<style>
body{
no-repeat;
background:url(../../../video-fallback-background.jpg)
}
</style>
</head>
<body>
<!--company dropdown-->
<?php echo form_dropdown('companydrop',$companydrop,'','class="required" id="companydrop"'); ?>
<br />
<br />
<!--car dropdown-->
<select name="cardrop" id="cardrop">
<option value="">Select</option>
</select>
<br />
</body>
</html>
dynamic dropdown is not working as the first select which is the
company name is working as it is fetched from database,but car model is not working,it not fetched to the dropdown.i need to fetch the car company model from database and then after selecting the company the model of that specified company has to be listed in the second dropdown.i have created database in phpmyadmin and created two table car and company,in company copany_id and company_name where as in car has car_id,car_name and company_id
Check this sample code for creating dropdown in codeigniter.
<?php
$js = 'id="unicode" class="form-control"';
$unicode = array(
'2' => 'No',
'1' => 'Yes'
);
echo form_dropdown('unicode', $unicode, set_value('unicode'), $js);
?>
Here Dropdown id is unicode,class is form-control.
Html will look like :
<select name="unicode" id="unicode" class="form-control">
<option value="2">No</option>
<option value="1">Yes</option>
</select>
You can get you values from db in an array and then store it in a variable like $unicode.Hope this helps.Check this ref link
For setting another dropdown based on first dropdown:
$("#dropdown1").change(function () {
var end = this.value;
$('#dropdown2').val(end );
});
In Your Car Controller Please remove print_r($cardata); first.
Then see in your console what response you are getting from the call. I suggest you to get data in json format and parse it on client end. It is the best practice.
i corrected the code and finally it worked,i will post the correct code, if it helps anyone in future.thanks to everyone who tried to help me..
controller
car.php
<?php
class Car extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('company_model');
}
public function index()
{
$data['companydrop'] = $this->company_model->company();
$this->load->view('car_view', $data);
}
public function car_model()
{
$company_id = $this->input->post('company_id',TRUE);
$cardata['cardrop']=$this->company_model->car($company_id);
$output = null;
foreach ($cardata['cardrop'] as $row)
{
$output .= "<option value='".$row->car_model."'>".$row->car_model."</option>";
}
echo $output;
}
}
?>
model
company_model
<?php
class Company_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function company()
{
$this->db->select('company_id,company_name');
$this->db->from('company');
$query = $this->db->get();
foreach($query->result_array() as $row){
$data[$row['company_id']]=$row['company_name'];
}
return $data;
}
public function car($company_id)
{
$this->db->select('car_id,car_model');
$this->db->from('car');
$this->db->where('company_id',$company_id);
$query = $this->db->get();
return $query->result();
}
}
?>
view
car_view
<html>
<head>
<title>car dealers</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#companydrop").change(function(){
/*dropdown post *///
$.ajax({
url:"<?php echo base_url();?>index.php/car/car_model",
data: {company_id:$(this).val()},
type: "POST",
success:function(data){
$('#cardrop option[value!=0]').remove()
$("#cardrop").append(data);
}
});
});
});
</script>
<style>
body{
no-repeat;
background:url(../../../video-fallback-background.jpg)
}
</style>
</head>
<body>
<center><font color="#333366"><strong></strong><h2>CR Motors</h2></font></center>
<center><font color="#FF8000"><h3>Select the car to purchase...</h3></center></font>
<!--company dropdown-->
<tr>
<td>
<font color="#00FF99">
Select the company</font>
<?php echo form_dropdown('companydrop',$companydrop,'','class="required" id="companydrop"'); ?> </td>
</tr>
<br />
<br />
<!--car dropdown-->
<tr>
<td>
<font color="#00FF99">
Select the model</font>
<select name="cardrop" id="cardrop">
<option value="0">Select</option>
</select>
</td>
</tr>
<br />
</body>
</html>

Anti Forge Token and Ajax JSON Post Does not Work

I am running MVC3, .Net 4 and VS2010. I have following sample project to illustrate the problem.
My controller code
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
My view and JavaScript code
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
Here I have 2 buttons, the first one triggers form post, the second one triggers Ajax post. The form post works fine, but the Ajax one does not, the server complains A required anti-forgery token was not supplied or was invalid. even though I have included the token in my JSON already.
Any idea what is wrong with my code?
This code works.
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>

Resources