How to pass variables in url using codeigniter? - php

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');
}

Related

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 :

Ajax call in codeigniter not as I expected

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]);
}
});
});

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.

ReferenceError while passing multiple parameters Ajax Codeigniter

I'm getting
ReferenceError: Y1ohe1oTVVG6916 is not defined
response when viewing my console. This happens while trying to pass two parameters via Ajax. Y1ohe1oTVVG6916 is the unique identifier for this input.
AJAX:
function checktickets(val)
{
var myserial = <?= $row['eventserial']?>; //this outputs the unique identifier Y1ohe1oTVVG6916
$.ajax({
type: "POST",
url: "<?php echo base_url();?>welcome/gettickets",
data:{
id:val,
evtsr:myserial
},
beforeSend :function(){
$(".numberoftickets option:gt(0)").remove();
$('.numberoftickets').find("option:eq(0)").html("Please wait..");
},
success: function (data) {
/*get response as json */
$('.numberoftickets').find("option:eq(0)").html("Select Number of Tickets");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
console.log(data);
alert(data);
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.numberoftickets').append(option);
});
/*ends */
}
});
}
CONTROLLER:
public function gettickets() {
$evt =$_POST['evtsr'];
$tkt =$_POST['id'];
$query = $this->db->query("SELECT * FROM events_tickets where event_serial ='$evt' AND tickets_id='$tkt'");
$data=array();
foreach($query->result_array() as $key=> $r)
{
for($i=1; $i<=$r['ticket_max_allowed_buyer']; $i++)
{
$data['value']=$i;
$data['label']=$i;
$json[]=$data;
}
}
echo json_encode($json);
}
If I remove the second parameter evtsr:myserial from ajax function and readjust my query from the controller, everything works, but I need this second parameter to be included so as to sort the selection more.
There is only one possible explanation I guess.
Try using the declaration like this :
var myserial = '<?= $row['eventserial']?>';
Please reply if it works. I'm curious whether that is the problem

Am i passing the value correctly to my controller from jquery?

I am doing a delete on a table using jquery,
$('table#chkbox td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: { 'id': id },
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
I am getting the id value correctly but my data parameter doesn't get passed to my controller,
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Any suggestion...
I am getting the error,
Missing argument 1 for libraryController::librarydelete() and Undefined variable: id
Your are posting the data, so you can get the id like this:
function librarydelete()
{
$del = $_POST['id'];
echo $del;
$this->librarymodel->deletebook_issue($_POST['id']);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Looks like you are using codeigniter, so this would be even better:
$del = $this->input->post('id');
Change id to $id in controller function parameter
means, your function should be
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Perhaps it is because you are using the variable name 'data' twice. Try renaming var data to var mydata.
The way you are passing data is wrong. This is the way you should be setting data.
var data= {id: id };
in your case let me not use the variable in the post action and show you how its done.
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
Edit: After you modified your code to pass data the right way.
Hey I have not followed MVC framwework in php. but since you are doing a post on the action you can always get the data the following way:
$id=$_POST['id']
and then you can use this id.
Also if you still want to use the function:
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
just modify the uri action to existingurl+/ i.e append the id to the end and in your route map (if there exists something like this in php in .nets implementation there is 1) just add that route.

Categories