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.
Related
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 :
I try to sent 2 values from my view to controller by Ajax and get back their results in laravel,
here is my script:
<script>
$(document).ready(function() {
$('body').on('change', '#statehidden', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityname = $("#cityename").val();
var statename = $("#statename").val();
$.ajax({
url: '{{ url('getcityandstate') }}/'+encodeURI(statename)'/'+encodeURI(cityname),
type: "GET",
dataType: "json",
success:function(data) {
// $('#statehidden').empty();
// $('#statehidden').append(data);
alert('worked');
}
});
});
});
</script>
my route:
Route::get('/getcityandstate/{statename}/{cityname}','CartController#flatshippingcostincart');
my controller:
public function flatshippingcostincart(Request $request, $statename,$cityname) {
$state = $request->statename;
$city = $request->cityname;
$shipping = Shipping::where('state', '=', $state)->where('city', '=', $city)->first();
return response()->json($shipping);
}
Errors
in console
SyntaxError: missing } after property list[Learn More] //in line 1200
note: { opened at line 1199, column 15 //in line 1199
debugger
line 1199 = $.ajax({
line 1200 = url: 'http://domain.../getcityandstate/'+encodeURI(statename)'/'+encodeURI(cityname),
Questions
How can i attach my var statename and var cityname to my url?
My $.ajax({ seems to be closed, why i get SyntaxError: missing }
after property list error?
Add a data item to to ajax object your sending.
Data:{"key:"value","key":"value"}
Make sure your sending a post request to your server..
if you insist on using get to send data to the server you have to rewrite the url, like
var item="mini",qty=2
then url:'www.yoursite.com?item="+item+"&quantity="+qty+"
I have a weird problem which I can't find a solution for.
Ajax code:
$("#details-comment-btn").click(function(e){
e.preventDefault();
var functionType = "comment";
var articleid=$('input[name=articleId]').val();
var owner_id=$('input[name=owner_id]').val();
var first_name=$('input[name=owner_first_name]').val();
var last_name=$('input[name=owner_last_name]').val();
var token=$('input[name=_token]').val();
var commentBody = $('textarea[name=commentBody]').val();
console.log(articleid);
$.ajaxSetup({headers : {'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')}});
$.ajax({
type: "POST",
url:articleid,
data:
{
'user_id': owner_id,
'commentBody': commentBody,
'functionType': functionType,
'article_id': articleid,
'_token': token
},
success: function(){
console.log(articleid);
$('#newcomment').append('<div class="comment" id="newCommentDiv">');
$('#newCommentDiv')
.append('' + first_name + " " + last_name + '')
.append('<span class="date">Just Now</span>')
.append('<p class="body">'+ commentBody + '</p>');
$('#newcomment').fadeIn();
}
});
});
However, I always get the same error
POST http://project.dev/articles/1 500 (Internal Server Error)
Here's the route I have for the post
Route::post('articles/{id}', 'DeleteController#deleteWork');
The link it show is fine, so I'm not sure why it's giving me the error.
The weird part is that other ajax calls who need to same URL work without any problems.
For example, here's the code from another AJAX call which does work and uses the same "url".
$('.articleFavo').click(function(e){
e.preventDefault();
var userid= $('input[name=userID]' ).val();
var functionType = 'favorite';
var articleid=$('input[name=articleId]').val();
var token=$('input[name=_token]').val();
$.ajaxSetup({headers : {'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')}});
$.ajax({
url:articleid,
type: "post",
data:
{
'functionType': functionType,
'user_id': userid,
'article_id': articleid,
'_token': token
},
success: function(){
console.log(articleid);
$('#favoriteBtn'+ articleid).css({display: 'none'})
$('#unfavoriteBtn'+ articleid).fadeIn();
}
});
});
On line 378 in your controller, you have the following line:
$article_id = input::get('articleId');
However, you're sending up "article_id" in your AJAX call. It'll probably be better to update this line in the controller (to be consistent with the rest of your code)
$article_id = input::get('article_id');
I have a trouble in using ajax() function. I have an html file with a form and have a segment of JavaScript code:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php/";
var param = $("#streetInput").serialize() + "&";
param += $("#cityInput").serialize() + "&";
param += $("#stateInput").serialize();
htmlobj = $.ajax({
url: url,
data: param,
type: 'GET',
dataType: 'JSON',
success: function(output) {
// parse the data here
},
error: function() {
}
});
});
});
</script>
I want construct an URL pointing to a specified php file by GET method. However, I don't know how to retrieve the parameters sent through URL in xxx.php file. I don't know how to debug. I just type
<?php
echo $_GET("streetInput");
echo $_GET("cityInput");
......
$xml = simplexml_load_file($url);
?>
but it didn't work. Can someone help me out? I want to give three parameters through URL to xxx.php, then print those elements
In xxx.php file, I construct a URL for an API request and get an XML file back. And I want to convert the $xml file to JSON format and return to my html file.
Change your JS code to:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php";
var param = $("#streetInput").serialize() + "&";
param += $("#cityInput").serialize() + "&";
param += $("#stateInput").serialize();
$.ajax({url: url, data: param, type: 'GET'});
});
});
</script>
Or, if you have only these fields in form, use this:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php";
var param = $(this).serializeArray(); //<- Or, .serialize() can also be used
$.ajax({url: url, data: param, type: 'GET'});
});
});
</script>
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