I'm working on Laravel and trying to send a variable to a controller using AJAX, but the request is changing to GET!
AJAX
function fetchTasks(email) {
$.ajax({
method: 'POST',
dataType: 'json',
url: '/teamwork',
data: {_method: 'POST', email : email},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
Routes.php
Route::any('/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
When i change the route method to post, it shows a 405(Method Not Allowed)
When i dd($request) in my controller, this is what i get
image
So, why my Ajax request doesn't work ?
EDITED:
I've modified my code to the following
function fetchTasks(email) {
console.log(email);
var token = "{{ csrf_token() }}";
$.ajax({
method: "POST",
url: "teamwork",
data: {
_token:token,
'email': email
},
contentType: "application/json",
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
},
complete: function () {
window.location.href = '{{route("testTRoute")}}';
}
});
}
It's still sending an empty GET request. Output from console is the following:
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
Based on ajax documentation you should use type param instead method.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Have u tried this?
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url:'teamwork' ,
type:'post',
data: { email : email},
method: 'POST',
dataType: 'json',
success:function(result){console.log(result);}
});
Route
Route::match(array('GET','POST'),'/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
If you want to send 'email' as a route parameter but don't want to show it in browser's address bar, you can do it as below.
Sending data through a form
At you blade.php
<form action="{{route('testPRoute')}}" method="POST">
#csrf
<!--
Set your email name or variable in input's value attribute. Like
<input type="text" name="email" value="email">
or
<input type="text" name="email" value="{{$email}}">
or -->
<input type="hidden" name="email" value="email">
<button type="submit">Go to Route</button>
</form>
At your Web.php
Route::post('/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
At your Controller
public function teamwork(Request $request)
{
$email = $request->email;
return $email;
}
After a long time of debugging, i have found that my problem was with the routing. I had two routes, GET and POST with the same name. That's why it was always sending a GET request.
Related
Can someone please show a Laravel 5.7 post ajax example with a full-working minimum example in a blade template? I know there are some resources in the web, but I miss a concise, straight-forward minimum example.
You can do something like this,
web.php
Route::post('/admin/order/{id}', 'OrderController#edit')->name('admin.order.edit');
blade.php
$(document).on('click', '.delete-button', function (e) {
e.preventDefault();
var orderId = 1
$.ajax({
type: 'post',
url: '/admin/order/' + orderId,
data: {
'_token': $('input[name=_token]').val(),
'data_one': 'dataone',
},
success: function () {
toastr.success('Order Has Been Deleted Successfully.');
},
error: function(XMLHttpRequest) {
toastr.error('Something Went Wrong !');
}
});
});
$.ajax({
url: 'http://some.working/url',
type: "POST",
data: $('#formContainer').serialize(),
success: function (response) {
console.log('Success', response);
},
error: function (response) {
console.log('Error', response);
}
});
The data can be produced in many ways for example
1. Using serialize() method as shown in the above example.
2. Using FormData():
for example
var data = new FormData($('#formContainer'));
In both of the above example, one thing compulsory is that your form
must contain csrf field. which can be provided using any of the
following methods:
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
or
{{ csrf_field() }}
or even more simply by just using
#csrf
in some where in your form.
In case you are not using any form, you can create the data object by
yourself like this
var data = {
_token: '{{ csrf_token() }}',
data1: 'Value1',
data2: 'Value2',
data3: 'Value2'
}
Define a Web Route
Route::get('currencies/fiat/changeStatus','FiatCurrencyController#changeStatus')->name("currencies.fiat.chanageStatus");
Call this function on click onclick="changeStatus(1,0)"
function changeStatus(id,status){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
/* the route pointing to the post function */
url: '/currencies/fiat/changeStatus',
type: 'GET',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN,cid:id,status:status},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data);
}
});
}
That's it all Done.
$(document).ready(function(){
/* In laravel you have to pass this CSRF in meta for ajax request */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
/* change in website layout base on click */
$('#user_view').on('click',function (e){
e.preventDefault();
$('.loading_screen').show();
var val = $(this).data('id');
$.ajax({
url: base_path + 'user/changeview/'+val,
type: "POST",
success: function (data) {
var obj = jQuery.parseJSON(data);
if (obj.SUCC_FLAG == 0){
window.location.href = site_url;}
else{
/* for console error message. */
console.log(obj.MSG);}
$('.loading_screen').hide();
},
error: function () {
alert("server error");
}
});
});
});
Hey it's a working code and i hope this will works for you.
im sending a form data via ajax to the server using laravel 5.6
when sending the data to the server, i have specified the method of ajax to POST and the routing method in web.php to post too, the problem is, ajax sendS the form data with GET method not POST. what should i change???
ajax code
var form = $('#personPersonalInfoForm')[0];
var formData = new FormData(form);
$.ajax({
url:"/addNewPerson",
Type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data)
{
alert(data);
}
});
web.php code
Route::post('/addNewPerson', 'adminController#addNewPerson');
Here is an example of working code using the FormData.
Using the "method" configuration instead of "type".
var form = document.getElementById("ajaxForm");
var formData = new FormData(form);
var url = form.action;
$.ajax({
method : 'POST',
url : url,
data : formData,
contentType: false,
processData: false
}).done(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
Dont forget to add the CSRF token in the form.
<form method="POST" action="/addNewPerson" id="ajaxForm">
#csrf
...
</form>
Or configure the ajax method from the start with it.
in the < head> add
<meta name="csrf-token" content="{{ csrf_token() }}">
and in the JavaScript add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
web.php
Route::post('/addNewPerson', 'adminController#addNewPerson')->name(admin.add_new_person);
in your adminController :
public function addNewPerson(Request $request){
// you can check request parameters
//return response()->json($request->all());
// add new person code here ...
return response()->json(array('status'=>'success','message'=>'person added'));
}
your ajax code should be :
$.ajax({
url:"/addNewPerson",
type: "POST",
data:$('#personPersonalInfoForm').serialize(),
dataType:'json',
contentType: 'application/json',
success: function(data)
{
alert(data);
},
error:function(){
alert('ERROR');
}
});
When I use a POST method with the following ajax request, it throws a "Method not allowed" error. If I use the form POST without using ajax, it goes to the proper method.
In Router.php:
$this->post('TestPost','DashboardController#TestPostMethod');
In View, the ajax request is:
$.ajax(
{
type: "POST",
url: 'TestPost',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
alert('hid post');
SetHotandWorstData(data,'hotquantity');
},
error: function (msg) {
alert('error');
alert(msg.responseText);
}
});
In Controller:
function TestPostMethod(Request $request)
{
$hotworstsalesdata = DB::table('100_INVOICEDETAIL')
->select( '100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME',
DB::raw('SUM("100_INVOICEDETAIL"."QTY") as
salesqty'), DB::raw('SUM("100_INVOICEDETAIL"."AMT") as salesamt'))
->groupBy('100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME')
->orderBy('salesqty')
->take(10)
->get();
return Datatables::of($hotworstsalesdata)->make(true);
}
you should pass "_token" in POST data. Laravel use token for cross-site request forgery (CSRF) attacks. use following code in your AJAX request
data: { _token: "{{ csrf_token() }}" }
Updated answer:
I have re-create same scenario on my system with laravel 5.4 and it's working for me.
my route (web.php) code is:
Route::post('/test_post', 'DashboardController#getData');
Javascript code is:
<script type="text/javascript">
$.ajax({
type: "POST",
url: '{{ url('/') }}/test_post',
data: { _token: "{{ csrf_token() }}" },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
console.log(data);
},
error: function (msg) {
console.log(msg.responseText);
}
});
</script>
DashboardController file is:
public function getData(Request $request) {
print_r($request);
}
Recently I got error with DELETE method ! I fixed by setting csrf token in html header and get in ajax . Hope this can solve your problem ..
<html>
<header>
<meta name="csrf-token" content="{{ csrf_token() }}" />
In ajax,
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I'm trying to post an array through ajax to php file on form submit.
<form action="echo.php" method="post">
<input name="qwerty[]" type="text">
<input name="qwerty[]" type="text">
<input type="submit"/>
</form>
Basically, I use this to post to php file:
function getlist(alt) {
$.ajax({
type:'POST',
url: 'markattlist.php',
data:{today:alt},
success: function(data){
$('#helloflist').html(data);
},
error:function (){}
});
}
Above is an example of what I'm trying to do. I've searched, but unable to find the solution to that. How can I post an array through ajax.
You can serialize the form data using data:$('#form').serialize() function and can send it using ajax or you can use JSON data type to send an array.
var Data = $('#yorFormName').serializeArray();
var JSONData = JSON.stringify(convertToJSON(Data));
$.ajax({
url: your_url,
type: "POST",
dataType: "json",
data: JSONData,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.status == 'success') {
// success logic
}
},
error: function () {
var errMsg = "Unexpected Server Error! Please Try again later";
}
});
Hope this will help you.
Instead of bothering how to send what you need, I advise you to use jquery serialize() method:
function getlist(alt) {
$.ajax({
type:'POST',
url: 'markattlist.php',
data: $("form").serialize(),
success: function(data){
$('#helloflist').html(data);
},
error:function (){}
});
}
And check on server-side with
print_r($_POST);
data: JSON.stringify({d:c}),
Encode it as json and decode it on the server:
$data=json_decode($_POST["data"]);
I am trying to send some data on button click to a controller and display the response in a content div back in the view. However i am facing problem while sending the data to the controller. Here is what i am trying to do :
test.php
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "1"
},
success: function(response){
$('#content').html(response.first);
}
});
});
$("#btn2").click(function(event){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "2"
},
success: function(response){
$('#content').html(response.first);
}
});
});
});
</script>
<input type="button" id="btn1" value="Button1 Content" />
<input type="button" id="btn2" value="Button2 Content" />
<br>
<div id="content"></div>
route.php
Route::get('ajax-example', function(){
return View::make('test');
});
Route::get('get-response/{id}', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
AjaxController.php
public function getResult($id){
if($id==1){
$content = "Hello";
}
else if($id==2){
$content = "World";
}
return Response::json(array('first'=>$content));
}
Error
Can anyone please help me out here. I am a bit confused right now. Thanks :)
if you need to get the parameter do this,
Input::get('id');
and route
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
because your ajax request is something like, host/get-response?id=5 and this is not compatible with Route::get('get-response/{id}'.., because this route needs something like host/get-response/5
Another way, you can keep your route as u declared and change the ajax request url,
$.ajax({
type: 'GET',
url: 'get-response/'+1,
dataType: 'json',
data: {},
success: function(response){
$('#content').html(response.first);
}
});
ok so i guess i figured it out what was causing the problem.
I changed my route to
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
and in controller i added
public function getResult(){
$id = $_GET['id'];
Now it seems to working just fine :)