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+"
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.
In Laravel -Controller name is ProductController, method is showproductinmodal .
I tried this, javascript code it worked.
Web Route:
Route::get('admin/product/show/{id}', 'Admin\ProductController#showproductinmodal');
JS:
<script>
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$(".modal-body").load("{{URL::to('admin/product/show/')}}"+"/"+productid);
});
</script>
Url loaded and returned some text to modal.
But this Javascript code not worked, i want to use code below:
$(document).ready(function(){
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$.ajax({
url: '{{route('admin.showproductinmodal')}}',
type: 'post',
data: {id: productid},
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
My web route code
Route::post('admin/product/show/', 'Admin\ProductController#showproductinmodal')->name('admin.showproductinmodal');
My Controller code:
public function showproductinmodal(Request $id)
{
return "Your test id:" . $id;
}
My a tag
Any ID test
Modal works normal, pops up when I use first javascript code everything works ok data loading, but second javascript code is necessary for me. I inserted alert also in $.ajax request but it didn't work.
Might be you are missing crsf token in you case:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Set csrf token for ajax call once then call N number of ajax:
$(document).ready(function () {
$('.showinfo').click(function () {
var productid = $(this).data('id');
let url = "{!! route('admin.showproductinmodal') !!}"
// AJAX request
$.ajax({
url: url,
type: 'post',
data: {
id: productid
},
success: function (response) {
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
And it will me more better, if you will use bootstrap model event, and use base url with javascript global variable.
I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}
You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.
OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});
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 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');