Ajax call in codeigniter not as I expected - php

When I call ajax in codeigniter 3.1.7 than it can take automatically base url in ajax url
AJAX CALLING CODE :
$(document).on("click",".btn_edit",function(){
var id = $(this).attr("id");
$("#btnsave").attr("mode","update");
$("#myModal").modal("show");
console.log(id);
$.ajax({
type :"post",
url :"Home/get_emp",
data :{"id":id},
dataType : "json",
success : function(edit_feed){
$("#txtempid").val(edit_feed.e_id);
$("#txtempname").val(edit_feed.e_name);
$("#selempskill option:contains('"+edit_feed.e_skill+"')").prop('selected',true);
$("#prev_img").attr("src",base_url+edit_feed.e_img);
var lbl = edit_feed.e_img.split("/");
$("#pic_label").html(lbl[3]);
}
});
});
Controller :
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('Emp_model');
}
public function index(){
//$this->load->view('index');
$this->load->view('home');
}
public function get_emp(){
$id=$_POST['id'];
$data = $this->Emp_model->get_emp($id);
echo json_encode($data);
}
ERROR :
jquery.3.2.1.js:3049 POST http://localhost/cod_std/Home/get_emp 404 (Not Found)
Here I want call only Controllers Home and its function get_emp please give me some solution I use codeigniter3.1.7

You can try:
url:"<?php echo site_url("Home" . '/get_emp'); ?>",

You have to use:
url:"<?php echo base_url(); ?>index.php/Home/get_emp",

Use like below code may solve your problem it work for me
$(document).on("click",".btn_edit",function(){
var id = $(this).attr("id");
$("#btnsave").attr("mode","update");
$("#myModal").modal("show");
console.log(id);
$.ajax({
type :"post",
url:"<?php echo base_url(); ?>index.php/Home/get_emp",
data :{"id":id},
dataType : "json",
success : function(edit_feed){
$("#txtempid").val(edit_feed.e_id);
$("#txtempname").val(edit_feed.e_name);
$("#selempskill option:contains('"+edit_feed.e_skill+"')").prop('selected',true);
$("#prev_img").attr("src",base_url+edit_feed.e_img);
var lbl = edit_feed.e_img.split("/");
$("#pic_label").html(lbl[3]);
}
});
});

Related

How to pass variables in url using codeigniter?

I am passing multiple variables like window.location.href="<?php echo base_url(); ?>search?result="+state1+"&c="+city1; instead of window.location.href="<?php echo base_url(); ?>search/"+state1+"/"+city1;
Now, the problem is when I define route i.e. $route['search?(:any)'] = "test/search?$1"; after a click on submit button then it shows an error on search page and print nothing. So, How can I resolve this issue? Please help me.
view:
<script>
$(".submit").click(function(){
state1 = $("#state1").val();
city1 = $(".city1").val();
window.location.href="<?php echo base_url(); ?>search?result="+state1+"&c="+city1;
});
</script>
controller:
public function search($raw)
{
echo $raw;
}
config/route.php
$route['search?(:any)'] = "test/search?$1";
Thank You
Your routing is wrong. No need to route the url for access the $_GET values.
Try below code.
Change $route['search?(:any)'] = "test/search?$1"; to $route['search'] = "test/search";
To get it values:
$this->input->get('result');
$this->input->get('c');
Try this,
POST:
$(".submit").click(function(){
var state1 = $("#state1").val();
var city1 = $(".city1").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('controller/cmethod'); ?>",
data: ({state: state1 ,city: city1}),
success: function (data) {
}
});
});
GET:
$(".submit").click(function(){
var state1 = $("#state1").val();
var city1 = $(".city1").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "GET",
url: "<?php echo site_url('controller/cmethod/'); ?>"+state1+"/"+city1 ,
success: function (data) {
}
});
});
PHP:
POST
function search(){
echo print_r($_POST);die;
}
GET
function search($state,$city){
echo $state;
echo $city;
die;
}
Currently what you are doing is sending $_GET Data to the controller, you will need to access the data by using
$this->input->get();
It is an array so you will automatically get all the variables you've sent.
Alternatively you can send the data via segments as CI3 is designed to work with. In your controller you can pass the parameters as arguments to the function. e.g
function search($param1,$param2,$param3){
}
Using this method this information can then be access by using your site URL plus the segment of data.
www.test.com/index.php/controller/param1/param2
You will also need to change your JS code to
window.location.href="<?php echo base_url(); ?>search/" + state1 + "/" + city1;
Your trying to use Get method values like Url parameter,
Please try this code
Jquery Code
$(".submit").click(function(){
state = $("#state").val();
city = $(".city").val();
window.location.href="<?php echo base_url(); ?>search?state="+encodeURIComponent(state)+"&city="+encodeURIComponent(city);
});
Route
$route['search'] = "test/search";
Controller
public function search()
{
$state = $this->input->get('state');
$city = $this->input->get('city');
}

Ajax function call: parameter passing to controller function in codeigniter

I am working on codeigniter. I am calling ajax function in a view page. Ajax
function is calling controller method. Ajax function is containing 3
parameters which i want to pass to controller method but due to some reason i
am not able to access parameter which is coming from ajax function.
Below is the my view code :
<script>
$('#drp').change(function(e){
var costcenter = $('#costcenter_id :selected').val();
var location1 = $('#location_id :selected').val();
var department = $('#department_id :selected').val();
$.ajax({
cashe: false,
type: 'POST',
data: {'costcenterid':costcenter,'locationid':location1,
'departmentid':department},
url: 'http://local.desk.in/mycontroller/contollerfunction',
success: function(data)
{
alert("success");
}
});
});
</script>
// controller method
public function controllerfunction($costcenterid,$locationid,$departmentid)
{
echo "costcenter= ". $costcenterid;
echo "location= ". $locationid;
echo "department= ". $departmentid;
}
Getting error message :
Message: Missing argument 1 for assetcontroller::controllerfunction(),
Message: Missing argument 2 for assetcontroller::controllerfunction(),
Message: Missing argument 3 for assetcontroller::controllerfunction()
Why not able to send ajax parameter values to controller method?? Thanks in
advance
Hope this will help you :
You are passing data as post in ajax so you have to access your data by using $_POST or using CI input class like $this->input->post() and for url path use site_url()
Your ajax code should be like this :
$('#drp').change(function(e){
var costcenter = $('#costcenter_id :selected').val();
var location1 = $('#location_id :selected').val();
var department = $('#department_id :selected').val();
$.ajax({
cache: false,
type: 'POST',
data: {'costcenterid':costcenter,'locationid':location1,
'departmentid':department},
url: "<?=site_url('mycontroller/contollerfunction');?>",
success: function(data)
{
alert("success");
}
});
});
And your controller controllerfunction method should be like this :
public function controllerfunction()
{
$costcenterid = $this->input->post('costcenterid');
$locationid = $this->input->post('locationid');
$departmentid = $this->input->post('departmentid');
$posts = array('costcenterid' => $costcenterid,
'locationid' => $locationid,
'departmentid' => $departmentid);
print_r($posts);die;
}
Note : see your browser's network tab to see the output :

how to return the value using jquery ajax in opencart

This is my OpenCart code I don't know what the problem in this code is, but it cant return the value from php ajax page. I tried many ways it wont work so please help me for this problem .
Here is my ajax in OpenCart:
<script type="text/javascript">
$('.list-group-item').on('click', function () {
var href = $(this).attr("href");
var arr = href.split('path=');
var cat_id = arr[1];
//alert("hai");
$.ajax({
type: 'post',
url: 'index.php?route=ajax/ajaxcat/index',
data: format_data,
dataType: 'json',
success: function (json) {
if (json['success']) {
//$('#messages').html(json['success']);
alert(json['success']);
}
}
});
});
</script>
Here is my php code:
<?php
class ControllerAjaxAjaxcat extends Controller {
function index() {
$json['success'] = 'This is the returned results color_adjust.php';
$this->response->setOutput(json_encode($json));
}
}
?>
I don't know what is wrong with that code it cant return the value.

php codeigniter ajax post

I have a problem with ajax post to codeigniter controller. It is get in to function but not post the data. Why ajax is not successfully post data ?
Here is my controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller{
public function index(){
$this->load->helper('url');
$this->load->view('index');
}
public function login(){
if ($_POST) {
$kAdi = $this->input->post('kAdi');
echo json_encode("done!");
}
}
}?>
my Ajax code :
function girisYap(){
var kAdi = $("#username").val();
var parola = $("#password").val();
$.ajax({
type:"POST",
url: "<?php echo base_url(); ?>" + "/main/login",
data: "kAdi="+kAdi,
dataType: 'json',
success : function(cevap){
alert("successfull");
}
});
}
Am I missing something ?
I solve the porblem, thank you guys. Here is the works code :
The controller
public function login(){
if ($_POST) {
$kAdi = $this->input->post('kAdi');
echo json_encode("done!");
}
Ajax function :
function girisYap(){
var $_base_url = '<?=base_url()?>';
var kAdi = $("#username").val();
var parola = $("#password").val();
alert($_base_url+"main/login");
$.ajax({
type:"POST",
url: $_base_url + "main/login",
data: {kAdi: kAdi},
dataType: 'json',
success : function(cevap){
alert(cevap);
}
});
}
Don't put the / before main/login because base url = localhost/codeigniter/ has a slash in the end. If you put slash it become codeigniter//main....
So, thanks for all the answers.
Try with this one
function girisYap(){
var kAdi = $("#username").val();
var parola = $("#password").val();
$.ajax({
type:"POST",
url: "<?php echo base_url(); ?>/main/login",
data:{kAdi: kAdi},
dataType: 'json',
success : function(cevap){
alert("successfull");
}
});
}
Post data should be like below one
data: { name: "John", location: "Boston" }
Not like
data: "kAdi="+kAdi,
Also Print the URl and check it access or not
Use this
$.post("<?php echo base_url() ?>main/login",
{
kAdi: kAdi
},
function(cevap){
console.log(cevap.trim());
if(cevap){
alert(cevap);
alert("sucessful");
}
});
On the other hand in controller,use this
$this->input->post('kAdi');

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);
?>

Categories