How to post data controller in Laravel 5.4? - ajax

I cannot post my data to my controller, is there something wrong with my ajax call? my setup for the web.php, or is the controller not setup, the error i get is. reminder this is laravel 5.4 running locally
POST http://127.0.0.1:8000/change-rank 500 (Internal Server Error)
JS
$('.rank-select').change(function(){
var id = $(this).val();
var memberId = $(this).closest('.irmember').attr('id');
console.log(id);
console.log(memberId);
$.ajax({
type: "POST",
url: 'change-rank',
data: {id: id, memberId, memberId},
success: function( msg ) {
console.log(msg);
}
});
})
web.php
Route::post('change-rank', 'RankController#changeRank');
RankController.php
namespace App\Http\Controllers;
use App\Rank;
use Illuminate\Http\Request;
class RankController extends Controller
{
public function changeRank()
{
info("hi");
}
}

The JS code you show does not include the CSRF token, which will certainly throw a 500 server error. There are different ways to include your CSRF token in AJAX calls, here's one example.
In your form:
<form>
{{ csrf_token() }}
....
In your JS:
var token = $('input[name="_token"]');
....
$.ajax({
data: {_token: token, id: id, memberId: memberId},
...
There are other approaches here on SO, and the Laravel docs suggest another method.
BTW, 500 server error is just a generic error telling you that, well, there was a server error. You really need to know what the error was if you want to solve it - and you should be able to see that in both the laravel and webserver (Apache/nginx/etc) logs. Your logs probably say something like "CSRF TokenMismatchException" which might have led you straight to the answer! :-)
EDIT
I've just noticed a typo in your Javascript which I initially copied into my answer. It may just be a typo here and not in your real code as it would likely throw JS errors rather than run and generate server error.
data: {_token: token, id: id, memberId, memberId},
should be:
data: {_token: token, id: id, memberId: memberId},
(colon after memberId).

Change your JS code like:
$('.rank-select').change(function(){
var id = $(this).val();
var memberId = $(this).closest('.irmember').attr('id');
console.log(id);
console.log(memberId);
$.ajax({
type: "POST",
url: 'change-rank',
data: {id:id, memberId:memberId},
success: function( msg ) {
console.log(msg);
}
});
});

Its simple change to ajax params its should work fine.
$('.rank-select').change(function(){
var id = $(this).val();
var memberId = $(this).closest('.irmember').attr('id');
console.log(id);
console.log(memberId);
$.ajax({
type: "POST",
url: 'change-rank',
data: {id:id, memberId:memberId},
success: function( data) {
console.log(data);
}
});
});
And controller file is,
public function changeRank(Request $request)
{
return $request->all();
}

Related

Ajax link does not send POST request

I have the following ajax link:
#Html.AjaxActionLink(item.Name, "https://test.testspace.space/storage/Data/stream?tokenValue=e58367c8-ec11-4c19-995a-f37ad236e0d2&fileId=2693&position=0", new AjaxOptions { HttpMethod = "POST" })
However, although it is set to POST, it seems that it still sends GET request.
UPDATE:
As suggested below, I also tried with js functuion like this:
function DownloadAsset() {
alert("downloading");
$.ajax({
type: "POST",
url: 'https://test.testspace.space/storage/Data/stream?tokenValue=add899c5-7851-4416-9b06-4587528a72db&fileId=2693&position=0',
success: function () {
}
});
}
However, it still seems to be GET request. Parameters must be passed as query and not in the body of the request because they are expected like that by the target action. I don't know why (it would be more natural to have GET request) but back-end developer designed it like this due to some security reason.
If I use razor form like this, then it works:
<html>
<form action="https://test.testspace.space/storage/Data/stream?tokenValue=2ec3d6d8-bb77-4c16-bb81-eab324e0d29a&fileId=2693&position=0" method="POST">
<div>
<button>Send my greetings</button>
</div>
</form>
</html>
However, I can not use this because I already have bigger outer form on the page and I'll end up with nested forms which is not allowed by razor/asp.
The only way is to use javascript but for some reason it does not make POST request.
#Html.AjaxActionLink will generate to <a> tag,and tag will only have HttpGet request method.If you want to send HttpPost with <a> tag,you can use it call a function with ajax,here is a demo:
link
<script>
function myFunction() {
$.ajax({
type: "POST",
url: "https://test.testspace.space/storage/Data/stream",
data: { tokenValue: "e58367c8-ec11-4c19-995a-f37ad236e0d2", fileId: "2693", position:0 },
success: function (data) {
}
});
</script>
Since you want to make a POST request, but the values need to be as query string params in the URL, you need to use jquery.Param.
see https://api.jquery.com/jquery.param/.
You should set the params, like below :
$.ajax({
url: 'your url',
type: 'POST',
data: jQuery.param({ tokenValue: "your token", fileId : "2693", position: 0}) ,
...
Try this instead,
First remove the action url from the from
Second put the result in the success function to return response
and for parameters, I always use FormData() interface to post with Ajax
And last don't forget to include dataType, contentType, processData to not get an unexpected behavior
your code will look like this
var form_data = new FormData();
form_data.append('tokenValue' ,'add899c5-7851-4416-9b06-4587528a72db&fileId=2693');
form_data.append('position' ,'position');
$.ajax({
type: "POST",
dataType: 'json',
contentType:false,
processData:false,
data: form_data,
url: 'https://test.testspace.space/storage/Data/stream',
success: function (result) {
}
});

AJAX POST Request in Laravel says url not found

I am trying to post data to a controller through ajax request. But it can't find the route and says the following in console.
POST http://127.0.0.1:8000/addNotification_action 404 (Not Found)
This is my ajax call below.
function editNotification(obj) {
// alert(obj.id);
var obj_id = obj.id;
var id = obj_id.split("_");
$.ajax({
url: "{{ url('addNotification_action') }}",
type: 'POST',
dataType: 'json',
data: {edit_notification_id: id[1]},
})
.done(function(result) {
console.log(result);
$('#title').val(result['title']);
$('#description_notification').val(result['details']);
$('#edit_flag_notification').val(result['notification_id']);
})
.fail(function() {
alert("error");
});
}
And I am just trying to dd() the request I get in the controller. Please help. Thanks
First of all, you should create a route and give this route a name. You have to generate the ajax url as "route('route_name')".
// Route (for Laravel 8)
Route::post('addNotification_action', [NotificationController::class, 'notify_method'])->name('notify');
// Ajax Settings
....
url: "{{ route('notify') }}",
....
Jus Give admin/addNotification_action in Ajax URL

No query results for model [App\Facility] getAllData

i want to ask about this question, because this is make me crazy.
So i want to load datatables using ajax, i got this in view
$.ajax({
type: "GET",
url: "facility/getAllData",
success: function(data) {
console.log(data);
}
});
Then this is my routes
Route::get('/master_data/facility/getAllData', 'FacilityController#getAllData')->name('facility.getAllData');
The last Part is my controller
public function getAllData()
{
$facilities = Facility::all();
return response()->json($facilities);
}
Thats all my code, i already use App\Facility; what is wrong with my code? thanks
You are using a named route so you will need to add something like this to your view:
$.ajax({
type: "GET",
url: {{ route("facility/getAllData") }}, // named route
success: function(data) {
console.log(data);
}
});
or use the full route url url: "/master_data/facility/getAllData"

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

How to call partial view through ajax in mvc3

I need to call a partial view through ajax. I have tried the following, but I am not sure how to complete it.
$("#UserName").change(function () {
var userid = $("#UserName").val();
var ProvincialStateID = $("#State").val();
var Hobbyid = $("#Hobby").val();
var Districtid = $("#DistrictNames").val();
var Homeid = $("#Hobbyhome_EstablishmentId").val();
var urlperson = '#Url.Action("FetchPersonByUserName")';
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
//Dont know what to write here
});
});
Here is the function that I have written in my Controller:
[HttpPost]
public ActionResult FetchPersonByUserName(int userid,int stateid,int districtid,int homeid,int Hobbyid)
{
//Code to fetch the data in the partial using all parameters
return PartialView("_LearnerAssociationGridPartial", list);
}
When I click on a dropdown the ajax gets called and I want the function which is called through ajax to redirect it to the partial view. Please help me because currently I am not able to display my partial view
What you need is something like
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid,
stateid: ProvincialStateID,
hobbyid: Hobbyid,
districtid: Districtid,
homeid: Homeid },
success: function (data) {
var result = data;
$('targetLocation').html(result);
}
});
it is recomended to not use data straight from variable but you can.
Now target location is where you want the result to be displayed to.
See more information in here:
http://api.jquery.com/jQuery.ajax/
As to slow fetching data, try optimalize your query
Update
For nhibernate running slow, try http://www.hibernatingrhinos.com/products/nhprof which is nhibernate profiler, for paid version, or try sql profiler to see what is query is beeing executed, often you can get much more that you would expect and or really slow query due to complexity of the query.
I dont understand what you mean by redirect to the parial view. Usually people use ajax and Partial views to get part of a page without a page refresh ( you might have seen this kind of behaviour in this site/facebook/twitter etc..) So i guess you probably want to show the data you are fetching asynchronosly to be shown in a part of your current page. you can do that in your success handler
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
$("#divUserInfo".html(data);
}
});
Assumung you have a div with id divUserInfo in your current page.
If you really want to redirect after the ajax post, you can do it like this.
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
window.location.href="Why-I-need-Ajax-Then.php";
}
});
Personally, I dont use HttpPost (both in client and server) If it is a method to GET some data. I simpy use the jquery get or load.
$.get("yourUrl", { userid: userid, stateid: ProvincialStateID } ,function(data){
$("#divUserInfo".html(data);
});

Resources