retriev data from controller using ajax - codeigniter

below code returns me blank in ajax response please help me
when i check my controller it also gives me blank.
Can you please check the code below to find out the reason of problem
here is my ajax code:
window.onload = function() {
$.ajax({
type:'json',
url:"http://localhost/myapne/admin/adminMenu/getMsg",
success:function(data){
alert(data);
// PrintSms(data);
},
error: function(error){
console.log(error);
}
});
}
here is my controller:
class AdminMenu extends CI_Controller{
function getMsg(){
$this->load->model('adminGetModel');
$data = $this->adminGetModel->getSms();
return array("status"=>"success","rows"=>$data);
}
}
here is my model:
class AdminGetModel extends CI_Model{
function getSms(){
// $a = $count*10;
// $b = $a + 10;
$this->load->database();
$query = $this->db->get('tblsms');
$rows = array(); //will hold all results
foreach($query->result_array() as $row)
{
$rows[] = $row; //add the fetched result to the result array;
}
return $rows;
}
}

Json_encode the data and use echo instead of return:
echo json_encode(array("status"=>"success","rows"=>$data));
This will return a string. If you want to turn it back into an object, you will then have to use JSON.parse() (or $.parseJSON if you're using jquery) in your ajax success handler.

Related

I could not get the returned value from the controller to the ajax success function inthe view in CI

This is the ajax function in the view
<script type="text/javascript">
$('#name').on('change',function(){
var uid = document.getElementById('name').value;
$.ajax({
url : '<?php echo base_url('index.php/Manager_Settings_Controller/getUsername');?>',
method : 'get',
data : {'uid' : uid },
success : function(result){
console.log(result);
}
});
});
This is the getUsername function from the controller
public function getUsername(){
$uid = $this->input->get('uid');
$this->load->model('Manager_Settings_Model');
$data = $this->Manager_Settings_Model->getUsername($uid);
return $data['username'];
}
And this is the model function
function getUsername($uid){
$this->db->select('username');
$query = $this->db->get_where('user',array('u_id'=>$uid));
foreach($query -> result() as $row){
$data = array(
'username' => $row->username,
);
}
return $data;
}
Its really great if someone can help me. Thanks inadvance
public function getUsername(){
$uid = $this->input->get('uid');
$this->load->model('Manager_Settings_Model');
$data = $this->Manager_Settings_Model->getUsername($uid);
echo $data['username'];
}
You got to echo not return in controller, so you get the error or result whatever in console.log in success function of ajax.

Dropdown using Ajax in Codeigniter

Can't find the error, it has to be with the query at "comunas" data base.
Here are the codes:
1) The 2 tables:
comunas:
comId comNombre comRegion
regiones:
regId regNombre
2) Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Usuarios extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model("regiones_model");
$this->load->model("comunas_model");
}
public function index_get()
{
$data['regionDrop'] = $this->getRegiones();
//loads up the view with the query results
$this->load->view('panel/usuario_agrega_view',$data);
}
public function getRegiones()
{
$this->db->select('regId,regNombre');
$this->db->from('regiones');
$query = $this->db->get();
// the query mean select cat_id,category from category
foreach($query->result_array() as $row){
$data[$row['regId']]=$row['regNombre'];
}
// the fetching data from database is return
return $data;
}
public function getComunaByRegion($regId=string)
{
$this->db->select('comId,comNombre, comRegion');
$this->db->from('comuna');
$this->db->where('comRegion',$regId);
$query = $this->db->get();
return $query->result();
}
//call to fill the second dropdown with the comunas
public function buildDropComunas()
{
//set selected country id from POST
echo $regId = $this->input->post('id',TRUE);
//run the query for the comunas we specified earlier
$districtData['districtDrop']=$this->comunas_model->getComunaByRegion($regId);
$output = null;
foreach ($districtData['districtDrop'] as $row)
{
//here we build a dropdown item line for each query result
$output .= "<option value='".$row->comNombre."'>".$row->comNombre."</option>";
}
echo $output;
}
}
3) Models: I'm not using the querys at models, I can't "touch them" for now, so I'm putting that code direct in the controller.
4) View:
<script type="text/javascript">
$(document).ready(function() {
$("#regionesDrp").change(function(){
/*dropdown post *///
$.ajax({
url:"<?php echo base_url();?>usuarios/buildDropComunas",
data: {id: $(this).val()},
type: "POST",
success:function(data){
$("#comunaDrp").html(data);
}
});
});
});
</script>
<!--country dropdown-->
<?php
echo form_dropdown('regionesDrp', $regionDrop,'','class="required" id="regionesDrp"'); ?>
I tried to follow the example from: http://www.c-sharpcorner.com/uploadfile/225740/cascading-drop-down-in-codeigniter-using-ajax/
But I have a different database (FK comId) and as I told you, I can't use a model file for this. Anyway, I tried with a region_model and comuna_model but it's the same.
Use append() not html()
$("#comunaDrp").append(data);
First of all, the function getComunaByRegion should be:
public function getComunaByRegion($comRegion=string)
{
$this->db->select('comId,comNombre');
$this->db->from('comunas');
$this->db->where('comId',$comRegion);
$query = $this->db->get();
return $query->result();
}
Plus, in the controller, the function public function buildDropComunas_post() wasn't called with POST, that was the main reason of my 404 not found.

Ajax changing the entire sql query

http://rimi-classified.com/ad-list/west-bengal/kolkata/electronics-and-technology
The above link has a filter in the left. I am trying to use ajax to get city from state. but as the ajax is triggered the entire query is changing.
SELECT * FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'pages'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
It is taking the controller name in the query (controller name is pages).
The actual query is:
SELECT *
FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'electronics-and-technology'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
// Controller
public function ad_list($state,$city,$category,$sub_cat=FALSE)
{
if($state===NULL || $city===NULL || $category===NULL)
{
redirect(base_url());
}
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category,$sub_cat);
$this->load->view('templates/header1', $data);
$this->load->view('templates/search', $data);
$this->load->view('ad-list', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
// Model
public function get_adlist($state,$city,$category,$sub_cat=FALSE)
{
if ($sub_cat === FALSE)
{
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
}
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('sub_cat_slug', $sub_cat);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
return $query->result_array();
//echo $this->db->last_query();
}
//ajax
<script type="text/javascript">
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
alert(selState);
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data : "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
$("#location_id").html("<option value=''>--Select location--</option>");
}
})
});
});
</script>
Please help me how to solve this issue. Please check the url I have provided and try to select a state from the filter section the problem will be more clear.
In .js what is the value of selState ?
In your model, you should if() else() instead of just a if, because your query will get override.
Where is the get_cities function ? Can we see it ?
On your url, the problem is that your ajax url doesn't return a real ajax call but an entire HTML page which is "harder" to work with. Try to change it into json (for dataType's ajax()) You should only do in your php something like this :
in your controller :
public function get_cities()
{
$state = $this->input->post('state');
//Do the same for $cat
if (!$state) {
echo json_encode(array('error' => 'no state selected'));
return 0;
}
$get_cities = $this->model_something->getCitiesByStateName($state);
echo json_encode($get_cities);
}
You should definitely send with ajax the $cat info

Controller must return a response in Symfony2

I have an ajax call in my code. What I want to achieve with the call works fine. I want to delete some records from the database which is actually deleted when the method is called via ajax but as in symfony method it must return a response and thats why when the method is executed its gives me the error
My Ajax call is
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false,
success: function(){
document.location.reload(true);
}
});
And the method that is executed is
public function trashpatentAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("pid");
$em = $this->getDoctrine()->getEntityManager();
$patent_group = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')->find($id);
if($patent_group){
$patentgroup_id = $patent_group->getId();
$em = $this->getDoctrine()->getEntityManager();
$patents = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')
->findBy(array('patentgroup' => $patentgroup_id));
if($patents){
foreach($patents as $patent){
if($patent->getIs_deleted()==false){
$patent->setIs_deleted(true);
$em->flush();
}
}
}
$patent_group->setIs_deleted(true);
$em->flush();
}
else{
$em = $this->getDoctrine()->getEntityManager();
$patent = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')->find($id);
if ($patent) {
$patent->setIs_deleted(1);
$em->flush();
}
}
return true;
}
}
How can I successfully return from this method ?
Any ideas? Thanks
Replace return true; with return new Response();. Also don't forget to write use Symfony\Component\HttpFoundation\Response; at the top.
You can also pass error code 200 and the content type like below.
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
Here is the full example of the controller
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class WelcomeController extends Controller
{
public function indexAction()
{
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
}
}

How to post multiple data through $.ajax to Codeigniter controller method

this is the method I want to send data to it
function get_lesson($reshte,$poodeman){
$this->load->model('dropdown_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->dropdown_model->get_lessons($reshte,$poodeman)));
}
and this is the get_lessens() function in the model file.
function get_lessons($reshte = null, $poodeman=NULL){
$this->db->select('rlessid, title');
if($reshte != NULL AND $poodeman!= NULL ){
$this->db->where('reshteid', $reshte);
$this->db->where('poodemanid', $poodeman);
}
$query = $this->db->get('tbllessons_root');
$lessons = array();
if($query->result()){
foreach ($query->result() as $lesson) {
$lessons[$lesson->rlessid] = $lesson->title;
}
return $lessons;
}else{
return FALSE;
}
}
and this is my ajax call at the view file
var reshteid = $('#reshte').val();
var poodemanid = $('#poodemanha').val();
$.ajax({
type:"POST",
url:"http://localhost/crud-grocery/index.php/examples/get_lesson/",//+reshte+"/"+poodeman,
data: "reshte="+reshteid+"&poodeman="+poodemanid,
success: function(lessons)
{
$.each(lessons,function(rlessid,title){
var opt = $('<option />');
opt.val(rlessid);
opt.text(title);
$('#lessons').append(opt);
});
}
});
as you see I am trying to chain options in the form
but The problem comes up when I try to post (send) two parameters to the controller method
any idea?
In your controller, you need to get POST values not as parameters:
//in controller
function get_lessons(){
...
//get POST values
$reshte = $this->input->post('reshte');
$poodeman = $this->input->post('poodeman');
You have to pass data as a javascript object literal:
...
data: {
reshte: reshteid,
poodeman: poodemanid
}
....

Resources