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 :
Related
I need to pass a ajax variable as route parameter, but it is showing an error.
This is the error:
Too few arguments to function App\Http\Controllers\PermissaoController::status(), 0 passed and exactly 1 expected
This is the script:
<script type="text/javascript">
$(document).ready(function() {
$('#status_id').change(function(){
var usuario = (location.pathname).split('/');
var status = this.value;
$.ajax({
type: 'get',
url: "{{route('permissao.status', "+status+")}}",
data: {status: status, usuario: usuario[2]},
dataType:"json",
success:function(html){
$('#projeto_id').find('option').remove();
$('#projeto_id').append('<option value="">Selecione...</option>');
for(var i = 0; i< html.length;i++){
$('#projeto_id').append('<option value="'+html[i]['id']+'">'+html[i]['titulo']+ '-' + html[i]['codigo']+ '</option>');
}
}
})
})
})
This is my function in controller:
public function status($sd) {
$usuario = Usuario::where('id', $sd)->get();
return $usuario;
}
How can I do it?
You cant pass JavaScript to laravel route method.
It should be
url: "permissao/status/"+status,
if you face base url issue then you can do the following
var url="{{url('/')}}/";
then in ajax
url: url+"permissao/status/"+status,
If you want to use route.
var status = this.value;
var url ="{{route('permissao.status', ":status")}}";
url = url.replace(":status", status);
Use variable url with ajax call.
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');
}
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.
My ajax method call on drop-down change event (view page)
$('#drp').change(function(e){ //dropdown change event
var costcenter = $('#costcenter_id :selected').val(); //parameter 1
var location1 = $('#location_id :selected').val(); //parameter 2
var department = $('#department_id :selected').val(); //parameter 3
$.ajax({
cashe: false,
type: 'POST',
data: {'costcenterid':costcenter,'locationid':location1,
'departmentid':department},
url: 'http://local.desk.in/mycontroller/contollerfunction',
success: function(data)
{
alert("success");
}
});
});
This is my controller method (method in controller)
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 :
Your ajax should be like this :
$.ajax({
url: "<?=site_url('mycontroller/contollerfunction');?>",
cache: false,
type: 'POST',
data: {'costcenterid':costcenter, 'locationid': location1, 'departmentid':department},
success: function(data)
{
alert("success");
}
});
And your controller method controllerfunction should be like this :
Use CI inbuilt $this->input->post() to access the post items 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;
}
I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.