Laravel ajax url not working on production server - javascript

I have this ajax request on my Laravel Project (this is a simple version but it is working):
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '/admin/lessons/addMember/licenseMemberId', // This is the url we gave in the route
data: {'licenseMemberId' : id},
success: function(response){
console.log(response);
if ($.trim(response)) {
var actualMembers = document.getElementById("actual-member");
}
$('#membersModal').modal('hide');
},
});
When I work locally and I use php artisan serve the ajax call works, but when i deploy to my production server doesn't (because the path /admin/lessons/addMember/licenseMemberId is not the full path in the server).
The best way shoud be using the route, but I don't know how.
This is the routing table:
web |
| | POST | admin/lessons/addMember/{licenseMemberId} | lessons.addMember | App\Http\Controllers\admin\LessonController#addMember
Is there a way to use the laravel route with the paramether? If not, how can I do?

You shouldn't use URLs in Laravel the way you use it in vanila php or html, use the URL function, this function ensures that your route is pointing currectly to the project root, in your case you can do something like this
$.ajax({
method: 'GET',
url: '{{URL::to('/admin/lessons/addMember/')}}' + id,
// Laravel will print the url and you just need to concat your id to it
success: function(response){
console.log(response);
if ($.trim(response)) {
var actualMembers = document.getElementById("actual-member");
}
$('#membersModal').modal('hide');
},
});
Notice that im using GET as you seem to be retrieving data and not POSTING it, however if you need to post it, the MisaGH answer is the way to go

Do not receive the parameter in route.
URL should be : /admin/lessons/addMember
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '/admin/lessons/addMember', // This is the url we gave in the route
data: {'licenseMemberId' : id},
success: function(response){
console.log(response);
if ($.trim(response)) {
var actualMembers = document.getElementById("actual-member");
}
$('#membersModal').modal('hide');
},
});
And the controller:
$member_id = request('licenseMemberId');

The real route is
admin/lessons/addMember/{licenseMemberId}
so in javascript you need to call
'/admin/lessons/addMember/' + id
where id is a variable. In the controller you can use the id getting
Input::get('licenseMemberId') or $request->get('licenseMemberId');

Related

Laravel: I have some problem posting data with Ajax

Im new to using ajax and I have another post here about my code and they said it was correct.
However Im still facing issues
My code:
body[circle.id] = {id: currentid-1, x: event.offsetX, y: event.offsetY};
// Ajax
for(let i = 0;i < body.length;i++){
$.ajax({
url: 'get.php',
type: 'post',
data : {
data: body[i],
},
dataType: 'json',
});
}
The error:
[Error][1]
I cannot comment.
From the title I guess you are using Laravel.
I see you are hitting the file directly, but looks like you are showing only half the setup. In case Laravel.
What is the route setup?
And if the setup is like Route::get try Route::any.
How are you debugging the issue? Do you have any logs?
Can you check the logs of "web server"?
Either artisan serve or php -S should give at least some hints what your ajax is hitting.
According to the error image you have posted, The error says that the method only accepts the GET request but you are trying to make POST request in your AJAX method, Change your request type to GET like this,
$.ajax({
url: 'get.php',
type: 'get',
data : {
data: body[i],
},
dataType: 'json',
});
I fixed it.The problem was in url and routes

Laravel route is not working in API, returns page 404

In routes/api.php I have the following route:
Route::post('/session/storeValue', 'HomeController#storeValue');
And in controller I have AJAX function:
<script>
function noviArtikal() {
var data = { name: 'User');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '/session/storeValue',
data: data,
success: function() {
console.log("Valueadded");
}
});
};
</script>
But keep getting error page not found when sending AJAX call.
What am I doing wrong?
As it is api.php, it automatically adds /api/ to your URL. Try /api/session/storeValue.
From docs:
Routes defined in the routes/api.php file are nested within a route
group by the RouteServiceProvider. Within this group, the /api URI
prefix is automatically applied so you do not need to manually apply
it to every route in the file. You may modify the prefix and other
route group options by modifying your RouteServiceProvider class.
EDIT:
add name:
Route::post('/session/storeValue', 'HomeController#storeValue')->name('custom_name');
Then modify your javascript:
$.ajax({
type: "POST",
url: '/session/storeValue',
data: data,
to
$.ajax({
type: "POST",
url: '{{ route('custom_name')}}',
data: data,
EDIT 2:
And yes, don't send CSRF_TOKEN (check #Yur Gasparyan answer)
For first you dont need to send CSRF_TOKEN to api. There is no sense to check CSRF-TOKEN because it is an api. Also to send request to api you need to add api prefix manualy.
add this code in your route/web.php
Route::post('/session/storeValue', 'HomeController#storeValue');
simply give any name to the route just like this:
Route::post('/session/storeValue', 'HomeController#storeValue')->name('somename');
and in your ajax call just change the url attribute to:
url: '{{ route('somename')}}',
Laravel attach /api to the api routes automatically through RouteServiceProvider and it is found is /Providers folder.
Also you don't need csrf_token when you are making an Api call.

JavaScript URL issue with Permalinks enabled

I am using the following JavaScript function to fetch the data using ajax call
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
It calls the following php file and works fine.
http://127.0.0.1/osclass/oc-content/themes/bender/ajax-test.php
But when I enable SEO friendly Permalinks in my CMS current page URL is appended in start of link and I get the following error in Chrome Console.
GET http://127.0.0.1/osclass/fashion-beauty/oc-content/themes/bender/ajax-test.php?name=Jhon 404 (Not Found)
Anybody tell me how to solve this issue?
The url you've provided in the ajax call is document relative. When you changed the server's url generation scheme, you also caused the url pointed at by the ajax call to change.
Adjust the ajax url, changing:
url: "oc-content/themes/bender/ajax-test.php",
To:
url: "/osclass/oc-content/themes/bender/ajax-test.php",
Why don't you make the URL server-relative? Something like this:
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "/osclass/oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
As you have not posted the php code. I would mention that any url directly navigated through addressbar of browser causes in the GET request and i can see you have a POST request in the ajax, so, it can't work.
Workaround would be to use $_REQUEST super globals at php end. $_REQUEST would work for $_GET/$_POST requests.

Call post on external Rest API with Ajax

I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};
You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Implementing Ajax calls for a REST API

I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});

Categories

Resources