codeigniter send id and get database values without refresh - php

I need to send id and get database values according to the id without page refresh.and display data in my view,
here is my view,
<div>
Click on me
</div>
<script type="text/javascript">
function getSummary(id)
{
$.ajax({
type: "POST",
url: '<?php echo site_url('ajax_controller/getBranchDetails'); ?>',
cache:false,
data: "id=" + id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
controller
public function getBranchDetails(){
$b_id = $this->input->post('branch_id');
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
//echo json_encode(array('data'=>$data));
}
I need to display $data['results'] in my view
model
<?php
class Ajax_model extends CI_model{
function getRecords($id)
{
$this->load->database();
$query = $this->db->query("SELECT * FROM companydetails WHERE id='$id'");
return $query->result();
}
}

Try this code ,It is working .
<script type="text/javascript">
function getSummary(id)
{
$.post("<?php echo site_url('ajax_controller/getBranchDetails'); ?>",
{branch_id:id},function(data,status){
$('#summary').html(data);
});
}
</script>
Note : Check whether you have included jquery.min.js . If not mention the below code in view part header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

Try this instead:
<script type="text/javascript">
function getSummary(id) {
$.ajax({
type: 'POST',
url: "<?php echo site_url('ajax_controller/getBranchDetails'); ?>", // <-- properly quote this line
cache: false,
data: {branch_id: id}, // <-- provide the branch_id so it will be used as $_POST['branch_id']
dataType: 'JSON', // <-- add json datatype
success: function(data) {
// if you need to present this in a html table,
// likely, you need to use $.each() and build the markup using the json response
$('#summary').html(data);
}
});
}
</script>
Model: (Don't directly use variables inside the query string)
$sql = 'SELECT * FROM companydetails WHERE id = ?';
$query = $this->db->query($sql, array($id));
Controller:
public function getBranchDetails()
{
$b_id = $this->input->post('branch_id', true);
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
echo json_encode($data); // <-- uncomment
}

Related

i have 2 role in codeigniter admin and user when using admin then ajax gives response but in other role it goes in success but controller not response

Script code
<script>
$('#room_type_id').on('change', function()
{
var id=this.value; //or alert($(this).val());
$.ajax({
url: "<?php echo site_url('admin/bookings/get_room_plans') ?>",
type: 'POST',
cache: false,
data: {'id':id},
success: function(result) {
$("#room_type_plan").find('option').remove().end().append(result);
}
});
});
</script>
Codeigniter controller code
public function get_room_plans()
{
$id = $this->input->post('id');
$plans = $this->room_type_model->get_plans($id);
$data="<option value='0'>-- Select Plan --</option>";
foreach($plans as $p)
{
$data .= "<option value='".$p['price']."'>".$p['plan_name']." - ".$p['price']."</option>";
}
echo $data;
}
I can not understand while code is same for both roles.Please slove it.
url: "<?php echo site_url('admin/bookings/get_room_plans') ?>",
If you have an user controller please make sure you are calling it. if get_room_plans() is only supposed to be in admin controller, then var_dump $plans to see whats the issue

$Ajax request in codeigniter also check if request is correct

I have tried a lot and search a lot and i did the same as i see but i do not know where i am going wrong i am new to codeigniter. Can you please tell me where i am going wrong on the code ? I want to set the product name in my input field according to the barcode selected. I am trying to fetch the product name and try to set it using AJAX but it is not working. Please you tell where is the bug in my code?
Here is my Controller Function in Main.php
public function get_product()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
echo $barcode;
exit;
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
print_r($data);
exit;
}
My Ajax Code in js file :
$("#brcode").each(function(){
$("#brcode").change(function(){
let value = $("#brcode").val();
$.ajax({
url: '<?php echo site_url("main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
dataType: 'json',
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
Model Function :-
public function get_product_using_barcode($barcode){
$query = $this->db->get_where('items',array('barcode' => $barcode));
$result = $query->row();
return $result;
}
Please tell me where i am going wrong in my code?
Try this code Its works for me. Hope this will help you.
JQuery:
$(document).ready(function() {
$("#brcode").change(function(){
let value = $("#brcode").val();
$.ajax({
// URL should be include index.php
url: '<?php echo site_url("index.php/main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
dataType: 'json',
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
Controller:
public function get_product()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
return json_encode $data;
}
Model:
public function get_product_using_barcode($barcode){
$query = $this->db->get_where('items',array('barcode' => $barcode));
$result = $query->row();
return $result;
}
Greetings!
Can you change js code as like this. and try to see on console.
$(document).ready(function() {
$("#brcode").change(function(){
var value = $("#brcode").val();
$.ajax({
url: '<?php echo site_url("main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
You are going wrong in this section as you are using dataType: 'json', Your ajax should return a json object.
PHP Tag won't work in js file, so you should put your ajax request either in footer of the page or hardcode your url. For example : url:"http://localhost/retail/main/get_product"
Also i think let value = $("#brcode").val(); should be var value = $("#brcode").val();
So your controller code should be
public function get_product()
{
$data = array();
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
echo json_encode(array("posted_data"=>$_POST,"database_data"=>$data['result']));
exit;
}
And in success of ajax use this
success: function(data) {
console.log("Posted data");
console.log(data.posted_data);
console.log("Database data");
console.log(data.database_data);
}

calling controller function from view and retrieving rows from db using AJAX in codeigniter

I am trying to retrieve rows from database by making an AJAX call to the controller function. I have no error messages and the code is executing properly upto $("#msgbox").html("Type the name of someone or something...");
I think the controller is not called properly from the view. Below is my MVC code.
My view: welcome_message.php
<div id="centersearch">
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var start=/^((?!PART).)*$/
var word=/^((?!PART).)*$/
$("#contentbox").live("keyup",function()
{
var content=$(this).text(); //Content Box Data
var go= content.match(start); //Content Matching #
var name= content.match(word); //Content Matching #abc
var dataString = 'searchword='+ name;
//If # available
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
//if #abc avalable
if(name.length>0)
{
$.ajax({
type: "POST",
url: "<?php $this->load->helper('url'); echo base_url();?>index.php/Welcome/ ?>", // Database name search
data: dataString,
cache: false,
success: function(data)
{
$("#msgbox").hide();
$("#display").html(data).show();
}
});
}
}
return false();
});
//Adding result name to content box.
$(".addname").live("click",function()
{
var username=$(this).attr('title');
var old=$("#contentbox").html();
var content=old.replace(word," "); //replacing #abc to (" ") space
$("#contentbox").html(content);
var E="<a class='red' contenteditable='false' href='#' >"+username+"</a>";
$("#contentbox").append(E);
$("#display").hide();
$("#msgbox").hide();
});
});
</script>
My controller: Welcome.php
public function search()
{
$this->load->database();
//load the model
$this->load->model('select');
//load the method of model
$data['s']=$this->select->search();
$this->load->view('welcome_message', $data);
}
My model: Select.php
public function search($datastring)
{
$query = $this->db->select('*')
->from('country')
->where('from', $datastring)
->get();
return $query;
}
You can call your helper in your constructor
function __construct() {
parent::__construct();
$this->load->helper('url');
}
And your ajax url is
url: "<?php echo base_url();?>index.php/Welcome/search?>",
You should include the URL helper in the constructor of the class.
function __construct() {
parent::__construct();
$this->load->helper('url');
}
It looks like you're on CI, so unless you have a route specified your ajax URL is incorrect.
<?php echo base_url();?>index.php/welcome/search ?>
Load the url helper somewhere above in the PHP code itself like in the constructor function of your controller
url: "<?php $this->load->helper('url'); echo base_url();?>index.php/Welcome/ ?>" ==> This line is wrong
So this how your ajax request should be
$.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/Welcome ?>", // Database name search
data: dataString,
cache: false,
success: function(data)
{
$("#msgbox").hide();
$("#display").html(data).show();
}
});
Load url helper in your controller
$this->load->helper('url');
And use this for your ajax call.
url: "<?php echo site_url('welcome');?>",
Please refer this documentation
http://www.codeigniter.com/userguide3/helpers/url_helper.html#site_url
If you want to call a function of the current controller, you have to create a instance of the current controller in following way:
<?php
$CI =&get_instance();
$CI->method($param);
?>

Get a single row from the database using AJAX in CodeIgniter?

I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.

Unable to retrieve variables from ajax post in codeigniter

I am new to using ajax and I am having trouble with posting variables and accessing those variables in my controllers.
Here is the Controller Code
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
/* $this->load->model('product_model');
$q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
$data = $this->product_model->get_record_specific($q);
echo json_encode($data[0]->quantity);
*/
echo $product;
}
function index()
{
$this->load->view('autocomplete_view');
}
}
If I change the echo to a string inside single quotes like this 'Hello World', it will return the hello world back to the view correctly. But it will not do the same if I try it as it currently is. Also if I use echo json_encode($product); it then returns false.
Here is view code with ajax.
$( document ).ready(function () {
// set an on click on the button
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: 'productName',
success: function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<h1> Get Data from Server over Ajax </h1>
<br/>
<button id="button">
Get posted varialbe
</button>
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
//echo $product;
//in ajax dataType is json -here You have to return json data
echo json_encode($product);
}
...
}
//javascript file
var productName = $('#productName).val();//get value of product name from form
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: {productName:productName},//You have to send some data from form
success: function(msg){
alert(msg);
}
});

Categories