I never made an ajax request using laravel so it's different than just plain php.
This is my script that is attached on a dropdown onchange:
function createcomploadtemplate(){
var ifprefix = $("#createcomploadtemplatedropdown").find("option:selected").text();
var getidtemplate = $('#createcomploadtemplatedropdown').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: 'ajaxfixedcompany',
data: {getidtemplate:getidtemplate,ifprefix:ifprefix},
dataType: 'json',
encode : true,
success: function(data){
alert(data.success);
}
});
}
This is my route
Route::post('ajaxfixedcompany',['middleware' => 'auth', 'as' => 'ajaxfixedcompany', 'uses' => 'AjaxController#ajaxfixedcompany']);
And this is the function
public function ajaxfixedcompanyget(Request $request){
$response = array(
'status' => 'success',
'msg' => $request->message,
);
return response()->json($response);
}
If i use ajax url /ajaxfixedcompany instead of ajaxfixedcompany in chrome devtools i get "The page doesnt exist" with error 404
And without the / i get this:
EDIT: OMG...I think i just needed a break from all this. I have 2 controllers. 1 for POST and 1 for GET. i am requesting a POST while in my controller i only have my GET function created... It works again. lmfao
you can do this with csrf token.
$.ajax({
type: "POST",
url: "url/update",
dataType: 'json',
data: 'id=' + id+ '&_token={{csrf_token()}}',
Hope it helps.
Well i just needed a break. After that 1hour break i came back and noticed that i am making a post request, while it is also called in my route, but i had a typo in my controller....silly me... lmfao
Related
To give you a better understanding consider my ajax request:
$.ajax({
url: '{% url "validate-upload-single" %}',
type: "POST",
data: JSON.stringify({
'mainForm': Myform,
'currentForm': 1,
}),
dataType: 'json', // response type
Where:
var Myform = new FormData( $(this)[0] );
The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend
DJANGO VIEW:
print('SORTING THE POST REQUEST')
body = request.body.decode('utf-8')
serialized = loads(body)
print(f'POST: {request.POST}')
print(f'Body: {body}')
print(f'Serialized: {serialized}')
RESULT:
SORTING THE POST REQUEST
POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}>
Body: {"mainForm":{},"currentForm":1}
Serialized: {'mainForm': {}, 'currentForm': 1}
I've tried $("form").serializeArray() but this only return text data, files seem to be missing
I guess the problem is with contentType header - it should be 'multipart/form-data'. Check this link to make it work with jQuery.ajax
In the .js file you HAVE TO add the fist block of csrf token for properly working.
//Getting csrf token
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Then you use json in you ajax, getting the template that you want to display by variable here "html_form":
// Submit post on submit
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
//Send data to server for getting back sorted
$.ajax({
url: '/schedule/sort_group/',
async: true,
type: 'post',
data: { //data sent with the post request
group_field_value: $("#select_group").children("#group-option:selected").val(),
lector_field_value: $("#select_lector").children("#lector-option:selected").attr("name"),
},
dataType: 'json',
success: function (data) {
$("#change_by_select").html(data.html_form);
}
});
});
In the views.py file at the bottom you need to determine the data like that:
data['html_form'] = render_to_string('schedule/select_sort.html', context,
request=request)
return JsonResponse(data)
So I suggest the information that you want to retrieve from the server put into the particular another file, whatever it would be (dictionary or lists or other data structures or html templates).
I hope it would help. Feel free to ask any questions.
Hello i wnat to send my data with ajax to my controller.
My CODE
AJAX
$.ajax( {
type:'POST',
header:{
'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
},
url:"{{route('race.post')}}",
data:{
_token: "{{ csrf_token() }}",
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
CONTROLLER
public function Points(Request $request){
$test = $request->input('data');
return "$test";
}
ROUTE
Route::post('updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);
And there are the errors what i get.
Console
Network-preview
Network-Response
I just removed the slash at the end of url and it began working...
/managers/games/id/push/ to:
$http({
method: 'POST',
url: "/managers/games/id/push",
add this one in your layout.blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
then use this one in your js code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
i hope this will help!!
First thing is we put two routes in one for displaying view and another for post ajax. So simple add both routes in your route file.
routes/web.php
Route::get('ajaxRequest', 'RacesController#Points');
Route::post('ajaxRequest', 'RacesController#Points');
Include this meta tag inside your view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Include javascript code inside your ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Since you are working in a JavaScript file and not in a Blade file, the route() helper method is not working, and the route 'race.post' isn't parsed to an url.
Try to change the url to this:
url: '/updateC'
When you want to use the route() helper in your JavaScript, you have to add the script to a Blade file, and json_encode the value, you can read more about this in this answer.
I have different way to use it:
AJAX
data = {
selectmanufacturer: selectmanufacturer,
categories: selectCategory,
_token: "{{csrf_token()}}",
productName: productName
};
$.ajax({
url: '{{URL::to('/all-products-data')}}',
type: 'POST',
dataType: 'json',
data: data,
success: function (response) {
},
error: function (response) {
alert(response);
}
});
Controller:
public function Points(Request $request){
$test = $request->all();
return "$test";
}
I hope It will be helpful to you
The URL you’re posting to doesn’t look right in the console output you posted. In your AJAX code, you have this:
url:"{{route('race.post')}}"
But that’s just getting interpreted as is, it’s not getting interpreted as the value of that route in Laravel.
You’ll need to make sure that your JavaScript code is in a Blade template if you want Blade tags parsed.
not type: "POST", method :'POST" try the below code i have modified. ref: Reference Link
HTML code
<button onClick="onBtnClick()" data-url="{{route('race.post')}}"></button>
Updated Code
function onBtnClick(){
var token = $('meta[name="csrf-token"]').attr('content');
var url = $(this).attr("data-url");
$.ajax( {
method:'POST',
header:{
'X-CSRF-TOKEN': token
},
url: url,
data:{
_token: token,
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
}
Check if your laravel route is correctly set for this request.
In my case, I had a $.ajax url: "crop-image-upload" and a Route::post('crop-image-upload ', 'CropImageController#uploadCropImage');
But the request was sent to http://127.0.0.1:8000/news/crop-image-upload
So I had to change my route to Route::post('/news/crop-image-upload ', 'CropImageController#uploadCropImage');
So, in your case, try to add a literal url on ajax like this:
url:"/races/updateC"
and add 'races/' in the route like this:
Route::post('/races/updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);
I am sending data via ajax to my controller as
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
contentType: "application/json; charset=utf-8"/*,
success:function(id){
alert(sessionStorage.getItem('user_id'));
}*/
});
and in the controller I am using
public function getUserMessages(){
$id = Input::get('id');
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
echo "id is ",$id;
return $messages;
}
I am getting nothing in $id. I have also tried $_POST['id'] which says undefined index id. How I can retrive the id value?
$request->has('id') returns false too.
You should use the Request class instead of Input:
public function getUserMessages(\Illuminate\Http\Request $request){
$id = $request->id;
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
return $messages;
}
Your ajax call doesn't work and will throw a 500 Server Error because you need to pass laravel's csrf token with it whenever you POST something. Create a meta tag at the top of your blade view like:
<meta name="_token_" content="{{ csrf_token() }}">
and get the value when you are doing the ajax call:
$.ajax({
url: '/test',
type: 'POST',
data: {
id: sessionStorage.getItem('user_id'),
_token:document.getElementsByName('_token_')[0].getAttribute('content')
},
success:function(id){
alert(id);
}
});
Most likely the success function in your ajax call will only alert [object Object], to get a better overview over whats returned, use
console.log(id);
instead.
You may also create an error function for the ajax call so that possible errors will be shown. Just do add
error: function(err){
console.log(err);
}
after the success function.
The problem is that you are setting the application content as json, You don't need to set the content.
jQuery ajax
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
success:function(data){
console.log(data); // always good to output content for debugginn
}
});
Hope this help. Your ajax should work now.
Have you a route for AJAX requests? (I don't see it.)
Please try following code:
In your AJAX code:
$.ajax({
type: "POST",
url: "{{ route('ajax_route') }}",
data: { _token: "{{ csrf_token() }}", data: "sample data" },
success: function(data){
$(".result").html(data);
},
dataType: "json"
});
In your controller code:
public function ajaxAction(Request $request){
if ($request->isXmlHttpRequest() && $request->isMethod('post')) {
$data = $request->input('data', null);
echo json_encode($data);
}
}
In your route code:
Route::post('/ajax_route', ['as' => 'ajax-action', 'uses' => 'YourController#ajaxAction']);
I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int
I'm using jquery to make ajax calls. Basically I don't know how to access the data I'm sending to the server with a post request. I don't know what the variable is called or... something. I don't know!
Ajax functions:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = JSON.stringify({
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
});
return ajax_client(base_url+'ajax_port/gather_records', json);
}
Codeigniter Function:
public function gather_records()
{
$data = json_decode($this->input->post('ids'));
log_message('debug', $data);//null
return json_encode($data);//null :(
}
I'm having no trouble receiving data back from the server here (and accessing with jQuery), my problem is that I can't get the data I'm sending to codeigniter. I'm developing on MAMP if that makes any difference.
I've tried other variable names like,
$this->input->post('data');
$this->input->post('json');
None seem to work.
Thanks very much for any help I can get!
You don't need to do JSON.stringify({..
just pass an object, and everything will be fine. I mean:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = {
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
};
return ajax_client(base_url+'ajax_port/gather_records', json);
}
One more thing. You don't need to json_decode it in your PHP side. Because default contentType in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8'
Change line
$data = json_decode($this->input->post('ids'));
to
$data = $this->input->post('ids');
But if you really want to send JSON, you can add contentType
return $.ajax({
url: url,
type: 'POST',
data: json,
contentType: 'application/json',
dataType: 'json'
});
dataType you have set is "The type of data that you're expecting back from the server." (http://api.jquery.com/jquery.ajax/)