Retrive Data from DB in Codeigniter using json - javascript

I want to retrieve data from a database but I can't get any record.
I am using json to fetch record from the database.
Here is the view :
<p id="result"></p>
<script>
$("#txt_category_item_name").on("keyup",function(e)
{
$("#searchSuggestionList").css({"display":"block"});
var input_searchValue=$("#txt_category_item_name").val();
$.ajax({
type: "POST",
url: "search_suggestion_list",
data: {recive_value: input_searchValue},
dataType: 'json',
cache: false,
success: function(recive_result) {
$("#result").html(recive_result[1]);
}
});
});
</script>
The controller :
<?php
class Main_ctrl extends CI_Controller {
function search_suggestion_list() {
$this->load->model('main_model');
$recive_search_value=$this->input->post('recive_value');
$data=array();
$recive_search_value;
$data['recive_search_result']=$this->main_model->search_suggestion_list_model($recive_search_value);
$this->load->view('pages/search_suggestion_list_result',$data);
}
}
?>
And the model :
<?php
class Main_model extends CI_Model {
function search_suggestion_list_model($recive_search_value) {
$this->load->database();
$this->db->select('company_id,company_name,company_address,company_category,company_keywords,company_state,company_city,company_website_address');
$this->db->from('company_information');
$this->db->like('company_category',$recive_search_value);
$query=$this->db->get();
return $query->result();
}
}
?>

Try Bellow
In View
<p id="result"></p><script>
$("#txt_category_item_name").on("keyup",function(e)
{
$("#searchSuggestionList").css({"display":"block"});
var input_searchValue=$("#txt_category_item_name").val();
$.ajax({
type: "POST",
url: "/main_ctrl/search_suggestion_list",
data: {recive_value: input_searchValue},
dataType: 'json',
cache: false,
success: function(recive_result) {
if(recive_result.error){
alert(recive_result.error)
}
else{
$("#result").html(recive_result.success);
}
}
});
});
In Controller :
<?php
class Main_ctrl extends CI_Controller {
function search_suggestion_list() {
if($this->input->post('recive_value')){
$this->load->model('main_model');
$recive_search_value=$this->input->post('recive_value');
$data=array();
$data['recive_search_result']=$this->main_model->search_suggestion_list_model($recive_search_value);
if($data['recive_search_result']){
$data['error'] = 'No Records found';
}
else{
$data['success'] = $data['recive_search_result'][1]['name']; // edit as you wish
}
echo json_encode($data);exit;
}
}
}
In Model :
<?php
class Main_model extends CI_Model {
function search_suggestion_list_model($recive_search_value) {
$this->load->database();
$this->db->select('company_id,company_name,company_address,company_category,company_keywords,company_state,company_city,company_website_address');
$this->db->from('company_information');
$this->db->like('company_category',$recive_search_value);
$query=$this->db->get();
return $query->result_array();
}
}

Related

How can I make a jQuery script aware of a Codeigniter variable?

I have been developing a blogging application with CodeIgniter 3.1.8 and Twig. I am currently working on making a newsletter subscription system.
I have created a table named newsletter with 3 columns: id, email and subscription_date.
The newsletter subscription form:
<div id="messags" class="is-hidden h-text-center">
<div class="success is-hidden alert-box alert-box--success">You have successfully subscribed to our newsletter</div>
<div class="fail is-hidden alert-box alert-box--error">Sorry, the newsletter subscription filed</div>
</div>
<form name="newsletter" method="post" action="{{base_url}}newsletter/subscribe" id="newsletterForm" class="group" novalidate>
<input type="email" value="{{set_value('email') | striptags}}" name="email" class="email" data-rule-required="true" placeholder="Your Email Address">
<input type="submit" name="subscribe" value="subscribe">
</form>
The Newsletter_model model:
class Newsletter_model extends CI_Model {
public function subscriber_exists() {
$query = $this->db->get_where('newsletter', ['email' => $this->input->post('email')]);
return $query->num_rows() > 0;
}
public function add_subscriber() {
$data = [
'email' => $this->input->post('email'),
'subscription_date' => date('Y-m-d H:i:s')
];
return $this->db->insert('newsletter', $data);
}
}
As you can see above, I use the subscriber_exists() to make sure there are no duplicate emails.
The Newsletter controller is quite simple:
class Newsletter extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function subscribe(){
$data['is_new_subscriber'] = true;
if (!$this->Newsletter_model->subscriber_exists()) {
$this->Newsletter_model->add_subscriber();
} else {
$data['is_new_subscriber'] = false;
}
}
}
The problem
I use jQuery AJAX to submit the form and the script is unaware of the is_new_subscriber variable:
(function($) {
// Add subscriber via AJAX
$("#newsletterForm").validate({
rules: {
email: {
email: true
}
},
submitHandler: function(form) {
var form = $("#newsletterForm"),
$fields = form.find('input[type="email"]'),
url = form.attr('action'),
data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function() {
$('#messags').slideDown(250).delay(2500).slideUp(250);
if (is_new_subscriber == true) {
$fields.val('');
$('#messags .success').show();
} else {
$('#messags .fail').show();
}
}
});
}
});
})(jQuery);
UPDATE
Adding echo json_encode($data) to the subscribe() and changing the submitHandler to the below ddi not splve the issue:
submitHandler: function(form) {
var form = $("#newsletterForm"),
$fields = form.find('input[type="email"]'),
url = form.attr('action'),
data = form.serialize();
$.ajax({
dataType: "json",
type: "post",
url: url,
data: data,
success: function() {
$('#messags').slideDown(250).delay(2500).slideUp(250);
$fields.val('');
if (data.is_new_subscriber == true) {
$('#messags .success').show();
} else {
$('#messags .fail').show();
}
}
});
}
How can I fix this issue?
Your code doesn't do anything with the $data variable, after you populate it. You could for example return it JSON-encoded.
public function subscribe(){
$data['is_new_subscriber'] = true;
if (!$this->Newsletter_model->subscriber_exists()) {
$this->Newsletter_model->add_subscriber();
} else {
$data['is_new_subscriber'] = false;
}
echo json_encode($data);
}
Then, in the success callback of your JS code you need to reference it:
...
success: function(data) {
$('#messags').slideDown(250).delay(2500).slideUp(250);
if (data.is_new_subscriber == true) {
$fields.val('');
$('#messags .success').show();
} else {
$('#messags .fail').show();
}
}
...
Here is what worked for me:
In the controller, I added echo json_encode($data):
class Newsletter extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function subscribe(){
$data['is_new_subscriber'] = true;
if (!$this->Newsletter_model->subscriber_exists()) {
$this->Newsletter_model->add_subscriber();
} else {
$data['is_new_subscriber'] = false;
}
echo json_encode($data);
}
}
The script:
(function($) {
// Add subscriber via AJAX
$("#newsletterForm").validate({
rules: {
email: {
email: true
}
},
submitHandler: function(form) {
var form = $("#newsletterForm"),
$fields = form.find('input[type="email"]'),
url = form.attr('action'),
data = form.serialize();
$.ajax({
dataType: "json",
type: "post",
url: url,
data: data,
success: function(response) {
$('#messags').slideDown(250).delay(2500).slideUp(250);
$fields.val('');
if (response.is_new_subscriber === true) {
$('#messags .success').show();
$('#messags .notnew').hide();
} else {
$('#messags .notnew').show();
}
},
error: function() {
$('#messags .fail').show();
}
});
}
});
})(jQuery);
The HTML:
<div id="messags" class="is-hidden h-text-center">
<div class="success is-hidden alert-box alert-box--success">You have successfully subscribed to our newsletter</div>
<div class="notnew is-hidden alert-box alert-box--info">You are already subscribed</div>
<div class="fail is-hidden alert-box alert-box--error">Sorry, the newsletter subscription filed</div>
</div>

highlight the keywords in autocomplete search

i want to highlight the keywords according to its autocomplete search, like if i type a then the results it gives:
java
javascript
so in this java
javascript
and then if i type av then java
javascript should get highlight or bold according to the search.
Below is my code:
javascipt
$(this).ready( function() {
$("#id").autocomplete({
minLength: 1,
source:
function(req, add){
//alert("xdhf");
$.ajax({
url: "<?php echo base_url(); ?>/trainer_dashboard/autocomplete_batchsearch",
data: req,
dataType: 'json',
type: "post",
cache: false,
success: function (data){
//alert(data);
if(data.response =="true"){
add(data.message);
console.log(data);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError);
}
});
},
});
});
controller
public function autocomplete_batchsearch()
{
//$user_id=get_cookie('trainer_login_user_id');
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->trainer_dashboard_model ->batchsearch($keyword); //Search DB
//echo"";print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->id,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('trainer_dashboard_view',$data); //Load html view of search results
}
}

jquery ajax call in codeigniter

i have two function one is for delete and another for update . My delete function is working correctly but when i have written update function that is not working . Also update not working.
Here is the view
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$('table#delTable td button.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/delete');?>",
data:'id='+id,
cache: false,
success: function()
{
parent.fadeOut('slow', function()
{$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
function update(str){
var id=str;
var nm=$('#nm'+str).val();
var em=$('#em'+str).val();
var st=$('#st'+str).val();
var ph=$('#ph'+str).val();
var dp=$('#dp'+str).val();
var un=$('#un'+str).val();
var datas="id="+id+"&nm="+nm+"&em="+em+"&st="+st+"&ph="+ph+"&dp="+dp+"&un="+un;
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/update');?>,
data:datas,
cache: false,
success: function(msg) {
alert(msg);
}
});
}
</script>
<button type="button" class="delete>Delete</button>
<button type="button" onclick="update(<?php echo $row['id']; ?>)">Save</button>
Controller
public function update(){
$id=$_POST['id'];
$userName=$_POST['nm'];
$tokens=explode("",$userName);
$fName=$tokens[0];
$lName=$tokens[1];
$userEmail=$_POST['em'];
$userUni=$_POST['un'];
$userState=$_POST['st'];
$userDept=$_POST['dp'];
$userPh=$_POST['ph'];
$array = array(
'first_name' => $fName,
'last_name' => $lName ,
'email' => $userEmail,
'phone_number' => $userPh,
'varsity_name' => $userUni,
'state' => $userState,
'dept_name'=> $userDept,
);
$this->load->model('Prime_Model');
$result=$this->Prime_Model->updateProfile($id,$array);
if($result){
return "Data has updated";
}
else{
return "Nothing";
}
}
You miss double quote after ?> below:
$.ajax({
type: "POST",
url: "<?php echo base_url('Welcome/update');?>", // here
data: datas,
cache: false,
success: function(msg) {
alert(msg);
}
});

how to call ajax function from controller...in codeigniter

i need to create country drop down list in codeigniter. onchange event im calling a another controller of project thats name is ajax.php i need to know that how to get url and send data to url in codeigniter.
my ajax function is
var base_url = "<? echo base_url()?>";
function getstate(value) {
if (value !== '') {
//alert('test');
$.ajax({
type: "POST",
url:base_url+"adminzone/ajax/ajax.php",
data: "do=getstate&value=" + value,
success: function(msg) {
alert(msg);
//$('#psid').html("<img src='images/spacer.gif'>");
$('#reg1').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
}
my ajax controller is
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
//error_reporting(0); class ajax extends CI_Controller {
public function __construct() {
parent::__construct();
if (!$this->session->userdata('admin_logged_in')) {
redirect('adminzone');
}
$this->load->model('doctor_model');
}
public function getstate(){
echo $this->input->post();exit;
}
}
ajax function in view
$('#countryfield').change(function() {
var passedvalue = $('#countryfield').val();
var path = base_url+"ajax/getState";
$.ajax({
type: "POST",
url: path,
data: {'passedvalue': passedvalue},
success: function(data) {
if (data) {
alert(success);//task done on success
}
},
error: function() {
alert('some error occurred');
},
});
})
Now you can write function in ajax.php controller .
name of function should be getState
public function getstate(){
echo $this->input->post('passedvalue'); //now here you can perform your task
exit;
}
Now you can perform your task in controller and echo the value that you want to pass to the view.

How to return success in a ajax call

I have an ajax call to delete a page from my database, but I'm not quite sure how to return success and use it:
My ajax call looks like this:
$('.delete_button').click(function() {
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
succes:function() {
alert('something');
if (s.Err == false) {
window.location.reload(true);
}
}, error:function(e){
}
});
});
And in my delete_page.php I have this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
$delete_page = DB::getInstance()->delete('pages', array('id', '=', $page_id));
if ($delete_page) {
$output['Err'] = false;
} else {
$output['Err'] = true;
}
return json_encode($output);
It does delete the page, but it doesn't run the if statement and it is not alerting anything. How do I fix this?
Dont use return, actually output the data, with the correct header:
//return json_encode($output);
header('Content-Type: application/json');
echo json_encode($output);
In your PHP script, you need to output the data instead of returning it:
header('Content-Type: application/json');
echo json_encode($output);
Then in your javascript file you need to retrieve the data:
success: function (data) { // It's success not succes, and you need the parameter
alert('something');
if (data.Err == false) {
window.location.reload(true);
}
}
If that's the entire delete_page.php, it needs to echo the output, not just return it.
Here's a slightly more elegant way of handling this.
Update your delete_page.php script like this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
// Init
$output = array(
'IsDeleted' = false,
'LastError' = ''
);
// Delete
try {
$output['IsDeleted'] = DB::getInstance()
->delete('pages', array('id', '=', $page_id));
}
catch (Exception $ex) {
$output['LastError'] = $ex->getMessage();
}
// Finished
echo json_encode($output);
?>
Then update your ajax code like this:
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
dataType: 'json',
succes: function(result) {
if (result.IsDeleted) {
window.location.reload(true);
} else {
alert('Failed to delete. Last error: ' + result.LastError)
}
},
error:function(e) {
}
});

Categories

Resources