Laravel vs. Ajax: incorrect routing - ajax

I'm trying to populate "position" dropdown based on "department". The Ajax call is triggered on change event of the "department" dropdown.
The problem is that the Ajax call can't reach the correct route:
with url: 'ajax/get-position' - the url is: localhost/public/join/ajax/get-position?dept_id=5
with url: '/ajax/get-position' - the url is: localhost/ajax/get-position?dept_id=5
Both of the URLs are wrong and I have no idea why. Especially this /join/ in the first point is a mystery to me. The correct URL should be localhost/public/ajax/get-position?dept_id=5. I believe there's some kind of a conflict in the routing, however I'm not sure where.
The Ajax call is made on localhost/public/join/editor page.
JS:
...
...
$.ajax({
url: 'ajax/get-position',
data: {
dept_id: value
},
type: 'GET',
dataType : 'json',
success: function(json) {
//
},
error: function(xhr, status, errorThrown) {
//
}
});
...
...
Routes:
Route::get('join/editor',
array(
'uses' => 'DefaultController#showEditorRegistration',
'as' => 'editorRegistration'
)
);
Route::post('join/editor',
array(
'uses' => 'DefaultController#createEditor',
'as' => 'createEditor'
)
);
// ROUTE FOR AJAX CALL
Route::get('ajax/get-position',
array(
'uses' => 'DefaultController#getPositionsByDepartment',
)
);
Any ideas?
EDIT:
The JavaScript is in an external file. If I put the JS directly in blade.php view and use URL::route('routename') as Ajax url value - all works fine. However, simply using url: ajax/get-position - does not. Crazy world.

I'm not completely sure, but based on our conversation about the details of your project I think the issue has to do with the location of your document root. the public directory should never show up in any of your laravel project's urls.
I created a demo project to demonstrate a simple interaction with Laravel and Ajax. It's a vanilla laravel project with slight alterations to the hello view.
Checkout the project, navigate into the public folder, and use the following command to spin up an ad-hoc phpserver:
php -S localhost:8002
You can then go to the url http://localhost:8002 to get to the homepage.
If you inspect the link on the home page and look at the url that is generated with the URL facade for the route tester. The URL doesn't include the public directory:
http://localhost:8003/tester
You can also look at the ajax setup and see that you can use the tester route as well.
$('#getbutton').click( function (){
$.ajax({
url: 'tester'
}).complete(function (a){
alert(a.responseText);
}).error(function (a){
console.log(a);
});
});
Using either the link or the ajax call on button click will hit the tester route in the routes file:
Route::get('tester',[ 'as' => 'tester', 'uses' => function (){
return 'worked';
}]);
The link can hit the route via the route name tester assigned in the routes file, and the ajax request can hit the route from the query string.
The routes in your project look ok and using ajax/get-position as your url in the ajax call shouldn't be an issue.
Give this project a try. Even if the issue isn't a webroot one, hopefully it will help you figure out where your issue is coming from.

Related

Redirect to another page/view by javascript with 2 arrays - Laravel 5

Hi guys I am trying to return/pass 2 arrays after redirect,
This is my ajax
$.ajax({
method: 'POST',
url: urlAvaliarSubordinor,
data: {pval: pval, _token: subToken},
success: function(result) {
location.href = "http://localhost/project/avaliacao";
}
//console.log(data);
});
And this is my Controller
return response()->json([
'list_one' => $list_one,
'list_two' => $list_two
]);
So I want to redirect to the page 'avaliacao' and with access/pass of the 2 arrays.. My knowledge of HTTP Status Codes is weak , I am currently reading materials online but it all sounds like ancient script to me, Please if anyone can just point me to something that might help me or an explanation on how to pass data in url on javascript
Laravel has many different types of responses that you can send back to your application. I usually send back data formatted in json since its super easy to work with for javascript.
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
In the docs you can see all the other types of responses that can be used. https://laravel.com/docs/5.3/responses

Symfony2 send back login form on each AJAX request

I'm doing a back-office image upload form using Symfony 2.5.12 (yeah I know I'm a little out of date, but I will work on that soon :)). I want to upload the images via AJAX, but I get a 302 redirect to the login form on every AJAX request I send.
Here is the JS part on my stuff (it is simplified because for the moment I just want to do a successful AJAX call without 302 redirect to the login page, so I deleted the data related stuff) :
form.addEventListener('submit', event => {
event.preventDefault();
const url = form.getAttribute('action'); // '/admin/uploadImage'
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
});
And here is my action in my controller, bound to /admin/uploadImage URL :
public function uploadAction() {
return new JsonResponse(array('test' => 'hello world'));
}
Every /admin URL requires ROLE_ADMIN role, I defined it in security.yml :
security:
#...
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
This way, it is normal that a login form shows when I want to access to this kind of URL. But when I trigger my AJAX call, I'm already logged in because I'm on /admin/gallery page.
Does anybody can figure out what is wrong with what I'm doing ?
Thank you very much.
I absolutely don't know why, but it seems the issue was related to whatwg-fetch fetch implementation. I replaced it with axios and the problem is gone.

Ajax delete request not working on remote website

Using php with the laravel framework. I have a delete request to delete a file entry on my website, it's working fine locally but on my webserver it's failing.
// Ajax call
$.ajax({
url: BASE+'/contests/any/entries/any',
type: 'DELETE',
data: {
entry_id : entry_id
},
success: function() {
$(".entry-item#"+entry_id).remove();
}
});
My route:
Route::delete('contests/(:any)/entries/(:any)', 'entry#destroy');
Controller method:
public function delete_destroy() {
$entry = Entry::find(Input::get('entry_id'));
Entry::find($entry->id)->delete();
File::delete(URL::base() . 'public/uploads/' . $entry->filename);
}
When I check ajax requests viewing the network tab in chrome developer tools I get a status 404 not found on this delete method while it's working fine locally in wamp. Can anyone tell me what is wrong here and what this 404 not found exactly means?
What exactly isn't found here?
Actually, 404 not found means that your file doesn't exist and it could be also because of a wrong path and I think it could be because you are using
File::delete(URL::base() . 'public/uploads/' . $entry->filename);
which returns most probably something like
http://yourdomainpublic/uploads/filename
Instead, you can use
File::delete(path('public').'uploads/' . $entry->filename);
Which will output something like this
http://yourdomain/public/uploads/filename

sencha touch - ajax call to server (url , extra parameter formation)

I am using this to get the result from server
controller.allVisitStore = new Ext.data.Store({
model: 'allVisit',
autoLoad : true,
proxy: {
type: 'ajax',
id: 'allvisit_app_localstore',
url: '/RadMobApp/api',
extraParams:{
action:'query',
queryName:'GET_ALL_VISIT',
authToken: localStorage.getItem("auth_token"),
patTicketId: localStorage.getItem("patientId"),
retFormat:'XML',
keyValuePair:'yes'
},
// the return will be XML, so lets set up a reader
reader: new Ext.data.XmlReader({
// records will have an "T4" tag
record: 'data'
})
}
});
but i am not getting any thing.But i formed this url in browser and checked this i got the correct result. now here i want to check is there any problem in the url formation.How to check the url formation with extra parameter which is pass through ajax. I have checked in Inspect element-> network -> api there is no any api request found there.Is anything wrong in my code. Thanks in advance...
Use Firebug for Firefox or Chrome's developer tools to see what's going on when that store attempts to load itself. My hunch is that your url is incorrect and should be url: '/api' because RadMobApp is probably your app root.

.ajax posts and gets response on local server, no response on web host

I'm using an ajax call to do a minor calculation then return the value and display it in the page same page where the form is submitted. In Firebug it says it calls the function, however doesn't get a response. (I have a similar form that writes to a database that works fine, seemingly because it doesn't need a response - firebug says it fails to get a response on that script as well.) The odd thing is that I wrote this on my local server before implementing it on the site and everything worked as planned. I'm using Code Igniter on both the local server and the web server, but I don't know if that has something to do with it. Anyways, any help would be great. I'm marginally new so this is kinda outta my realm at this moment.
Thanks
EDIT: .js
$(document).ready(function() {
$('#submit').click(function(){
var formdata = {
years: $('#years').val(),
rate: $('#rate').val(),
principle: $('#principle').val(),
periods: $('#periods').val(),
continuous: $('#continuous').val()
}
$.ajax({
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
type: 'POST',
data: formdata,
success: function(data){
$('#replace').replaceWith('<p>'+data+'</p>');
}
});
return false;
});
});
php submit function
function submit(){
$years = $this->input->post('years');
$rate = $this->input->post('rate');
$principle = $this->input->post('principle');
$periods = $this->input->post('periods');
$isCont = $this->input->post('continuous');
$params = array(
'years' => $years,
'rate' => $rate,
'principle' => $principle,
'periods' => $periods,
'isCont' => $isCont
);
$this->load->library('timevalue', $params);
return $this->timevalue->FVFactor();
}
Could it be that the request is being made cross-domain? Remember that mydomain.com is considered a different domain to www.mydomain.com.
I ran into a similar situation recently. I requested a page from mydomain.com which made an AJAX request to a script on www.mydomain.com. The request was not made because it was considered cross-domain. It had the same symptoms that you describe. In Firebug and Chrome Developer Console I saw an empty response and no error message.
The problem is that CodeIgniter generates absolute URLs based on the $config['base_url'] setting. If you access the site using a different domain name to what is configured in $config['base_url'] you can run into this type of problem.
This works on the dev and not on the server because you are calling localhost!
// this will have the client call itself on this particular page (wont work)
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
The above code should be just:
// this is relative to the document ROOT, will work on server but not on dev!
// you can set it relative to the calling page using ../ as needed
url: "/index.php/timevalueshow/submit",

Resources