error 404 while using {{url()}} on laravel ajax - ajax

Greating,
I have some error while using ajax on laravel, the console return 404,
that's my ajax
$('#btn_search_postcode').click(function(e){
let postcode = $('#postcode').val();
if(postcode != ""){
$.ajax({
method: "GET",
url: "{{route('company.postcode')}}",
dataType: "JSON",
data:{
'id':postcode
},
success: function(result){
if(result != ""){
console.log(result.prefectureid);
}
else{
console.log('null');
}
}
})
}
})
I have change the url to "{{url('company/postcode')}}/"+postcode but still error
that's my route
Route::GET('/company/postcode/{id}', 'mycontroller\companyController#getPostCode')->name('company.postcode');
but the code working fine when I change the url into
url: "http://localhost/mylaravel/public/company/postcode/"+postcode,
I can't use the last method because in other pc using different port.
can anybody help me for this issue?
note : i can see the csrf token, when i add the csrf token again in ajax, I see 2 token on error link
EDIT:
I still not resolve that, but now im using url:rootUrl+"/companies/postcode/"+postcode, to resolve that issue, is it ok to do like that?

The problem is that your route has a required parameter {id} and since you don't provide it when you render the url of the route, laravel doesn't find the route.
Two solutions:
make the id parameter optional in your route declaration like so Route::GET('/company/postcode/{id?}', 'mycontroller\companyController#getPostCode')->name('company.postcode'); (note the {id?})
provide the parameters trough php with some defined variable in the view ex: {{route('company.postcode',$id)}}
Cordially

you have to change it like these
url: "{{url('company/postcode')}}"+'/'+postcode
please try these and let me know what happened

If I understand what you are asking, you have a route that is named company.postcode, is that correct? If you do have that route, and now what you are wanting is to get the company by postcode, you will need to take advantage of Laravel's Route Model Binding. What you can do is go into your model and create a function like this:
public function getRouteKeyName()
{
return 'postcode';
}
Yet, I see an issue with that that can cause you some issues down the road. What happens when you have multiple companies with the same postcode? How will Laravel know which one you want?
A much better option is going to be to use the id field and retrieve your company with it. Unless you make the postalcode field in the database a unique field. Which again raises the question of what happens when you have two or more companies wanting access to your website that share the same postal code?

Related

How to setup url in JavaScript to pass multiple parameter to controller in Laravel without using request

I setup the url by JavaScript to call a function in controller with only one parameter($RoleID) like this
$(document).on('change','#role',function(){
$RoleID = $(this).val();
let $url = '{{route("Admin.role.permission.LoadMember",':id')}}'
$url = $url.replace(':id', $RoleID);
$.ajax({
url:$url,
success:function(data)
{
$('#member').append(data);
}// end fucntion success
});
});
It works ok, Now I would like to do the same with more than one parameter without using Request
I tried like this
document.getElementById('function').addEventListener('change', function(e) {
if (e.target.name==='function') {
$FncID = e.target.value;
let $url = '{{route("Admin.role.permission.LoadActionsInRolePermissions",'[$ModuleID,$RolID,$FncID]')}}';
$.ajax({
url:$url,
success:function(data)
{
$('tbody').html(data);
//$('#member').append(data);
}// end fucntion success
});
}
})
But unfortunately, It is not work. Pls help me.
Thank in advance
You haven't shown us how you defined the route, nor what laravel version you're using, but I highly suggest taking a read on the docs on how route parameters work.
As example, say this is your LoadMember route:
Route::get('permission/load-member/{id}', [PermissionController::class, 'loadMember'])->name('Admin.role.permission.LoadMember')
Then, as follows:
{{route("Admin.role.permission.LoadMember",['id' => ':id'])}}.
By passing an associative array with key => value assignment, Laravel knows where to place the given values in the url.
For a multi-parameter route, it works exactly the same:
Route::get('permission/load-actions-in-role-permissions/{moduleId}/{rolId}/{fncId}', [PermissionController::class, 'loadActionsInRolePermissions']) ->name('Admin.role.permission.LoadActionsInRolePermissions')
{{route("Admin.role.permission.LoadActionsInRolePermissions",'['moduleId' => $ModuleID, 'rolId' => $RolID, 'fncId' => $FncID]')}}
Also, may I suggest using camelCase for variable names, and kebab-case or snake_case for route naming? It highly improves readability and future developers who might work on your project will have a better guess at how your route structure works.

axios get passing parameter to laravel route

I am trying to pass an id through axios.get in vue.js to laravel route.
my axios code plus parameter are as following,
axios.get('http://localhost/laravel_back/public/api/bpaper',{
params: {
id:12
}
and my laravel route is as follows,
Route::get('bpaper/{id}', function($id)
{
return 'Paper '.$id;
});
when executing this code i get a 404 error on my browser console. and the request url is,
Request URL:http://localhost/laravel_back/public/api/bpaper?id=12
I have already given the access-control allow methods to allow communication through axios. And the code runs when not providing a parameter. any one know a fix.
Considerind server-side is Route::get('bpaper/{id}', function($id) { ..., the id is part of the path, not a parameter. Add it to the URL. Do:
var myId = 12;
axios.get('http://localhost/laravel_back/public/api/bpaper/' + myId)
Added it to a myId variable for clarity, you don't have to do it. Using:
axios.get('http://localhost/laravel_back/public/api/bpaper/12')
would work just as well.
Also, if you have access to newer versions of JavaScript, you can profit from template strings:
var myId = 12;
axios.get(`http://localhost/laravel_back/public/api/bpaper/${myId}`)

How do I pass data from my controller to a view in Laravel 5.5?

I have a function that I'm trying to pass some data to a view. I can't get the Route to recognize the data, it just keeps saying my variables are undefined. Here's what I'm trying to do:
return redirect('confirm')->with([
'name'=>$name,
'service'=>$service,
'$email_address'=>$email_address
]);
Then in my web.php file, I have:
Route::get ('confirm', function($name,$service,$email_address){
return view('confirm',compact('name','service','email_address'));
})->name('confirm');
Laravel just throws an error "Missing argument 1 for Illuminate\Routing\Router::{closure}()"
I'm at a complete loss, I've tried this a bunch of different ways. If I call the view right from my controller, it works fine, but then URL isn't what I want it to be, so it seems like I have to return the redirect and reference the data in my route definition. Can anyone enlighten me?
If it's ok to show the email in the route then you can correct the problem like this :
Route::get ('confirm/{name}/{service}/{email_address}', function($name,$service,$email_address){
return view('confirm',compact('name','service','email_address'));
})->name('confirm');
And in the controller :
return \Redirect::route('confirm', [
'name'=>$name,
'service'=>$service,
'email_address'=>$email_address
]);
Ps : this is not recommended i just answer you problem but there is a better way to do it, passing just an id for exsample then find the user by id then take his email and other stuff.

MVC: How to serialize a knockout object into a JSON property through AJAX

I'm trying to serialize a knockout object and pass it into a JSON property called multipleCharge.
This is the ajax code to send data though Get method to a mvc controller
$.ajax({
url: _url,
type: 'GET',
//data: { multipleCharge: ko.mapping.toJS(_vm)},
data: { multipleCharge : { AccountId : 2 } },
dataType: 'json'});
And this is the method
[HttpGet]
public HttpResponseMessage GetSalesInvoiceMultipleCharge
([FromUri]MultipleChargeDto multipleCharge)
{
...
}
Please, note that the ajax method has a comment line. Using the hardcoded line, it works, multipleCharge object is not null, but if I uncomment the another line, it's a bad request in my browser.
Look at this.
Any idea about what's happening. Using the Chrome console, it looks ok; so I can't identify the error.
It is may be IIS problems with very long URL.
See this Issue with URL length in IIS7 (Windows Server 2008) question and related answers.
Also see this http://www.iis.net/configreference/system.webserver/security/requestfiltering documentation.
You could try to solve this problem by editing web.config. But also you could use POST method instead of GET and send your data in request body.

Ajax request, should it be POST or PUT

I have created a Spring MVC web app.
The app makes a few calls to the controller. These calls are close/open/end game.
I make these calls using Ajax, so I can handle a response on the top of the page.
ajaxPost = function (url, action, id, onSuccess, onError) {
$.ajax({
type: "POST",
url: url + "?" + action + "=" + id,
success: function(response) {
if(onSuccess !== null) {
onSuccess(response);
}
},
error: function(e) {
if(onError !== null) {
onError(e);
}
}
});
};
The question I have is that I'm using 'POST' for the Ajax request, is that correct, or should it be 'PUT'?
My controller has a default URL, and I'm using the param attribute to decide which method to call, as I have many buttons on the page.
#RequestMapping(params = "open", method = RequestMethod.POST)
#RequestMapping(params = "close", method = RequestMethod.POST)
It doesn't sit well with me that I'm using 'POST' for these calls. Maybe it should be 'PUT'...
Any suggestions? Does it matter?
It depends on what your request should do. So there's no general rule that you should use one over the other, they have different use cases.
POST for creating a record.
PUT for updating an existing record (or putting a record at a specified location/id).
See this wikipedia article for the definitions.
One thing to note is that PUT should be idempotent, doing the same PUT request multiple times should ideally produce the same result as doing a single PUT request. However, POST is not idempotent, so doing several POST requests should (or will) create multiple new records.
So after having read this you should check what your method does, and select the corresponding request method.
Both PUT and POST may create a new record; PUT may also update/change an existing record.
The difference between POST and PUT is that PUT is expected to address the record with it's ID, so that the server knows what ID to use when creating (or updating) the record, while POST expects the server to generate an ID for the record and return it to the client after the record has been created.
Thus, a POST is addressed to the resource as a collection: POST /resource, while PUT is addressed to a single item in the collection: PUT /resource/1
Use POST. Always use POST, unless you're absolutely rock-solid certain that PUT is properly supported by your hosting system.

Resources