I added this:
<meta name="csrf-token" content="{{ csrf_token() }}">
Its ajax area:
$.ajax({
url: '{{ route('fav.add') }}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: {id},
dataType: 'text',
contentType: false,
processData: false,
success: function(data) {
console.log(data);
}
})
It's my controller:
public function addFav(Request $request) {
return $request->id;
}
I'm not reaching id.
If i change my controller like this:
public function addFav(Request $request) {
return "test";
}
There is no problem, i'm reaching the test text, but when i try to reach id I can not reach. How to fix it? If you help me i will be glad.
I solved this problem. The problem is that 2 rows. I deleted them and it worked fine.
contentType: false,
processData: false,
Related
I'm using ajax to send comments. This is the route
Route::post('/users/add/comment/', 'UsersController#AddComment')->name('AddComment');
The ajax call
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
type: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
and the controller
public function AddComment(Request $request){
dd($request);
}
It always throws that error. I changed the route and the func name a lot of times. but it does the same thing and the dd(); request is always empty.
Thanks in advance!
You have to set the ajax method to post with the attribute 'method', not 'type'.
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
I was trying to send the same data using <form> I tried AJAX to have more control over the request.
my form tag goes like <form method="POST" action="/users/add/comment/">
I removed the last / in the URL and it does work. I don't know how or why.
But It works !!!
Form
<form id="YourForm">
...
your inputs
...
</form>
Button
<button type="button" class="btn btn-success SendButton">Save This</button>
JS
<script type="text/javascript">
$(document).on('click', '.SendButton', function (e) {
e.preventDefault();
var data = $("#YourForm").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method : "POST",
url : "{{ url('users/add/comment/') }}",
data : data,
dataType : "JSON",
})
.done(function(response) {
alert('Success!');
location.reload();
.fail(function(response) {
console.log("Error: ", response);
});
return false;
});
</script>
You need to change type to method, you use the wrong keyword. Now it is a default GET
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post', // it should be method: 'post'
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
Button code
this is my button code with id 123
<button type="submit" class="addto" id="123">Add to cart</button>
ajax code
This is my ajax code
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
$id=this.id;
//alert($id);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/test', //route url
dataType:"json",
type:"POST",
data:{id:this.id},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});
Route code
this is my route code
Route::match(['get','post'],'/test','ajaxcontrol#test'); //route url
Controller code:
How to solve this, i have included all the imports
class ajaxcontrol extends Controller
{
public function test(Request $request){
$valu=$request->id;
echo json_encode($valu);
}
}
Try to change your ajax like this:
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
id=this.id;
//console.log(id);
$.ajax({
url: "{{ url('/test') }}", //route url
dataType:"json",
type:"POST",
data:{
id:id,
"_token": "{{ csrf_token() }}",
},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});
How do I resend the ajax request from getting TokenMismatchException?
Currently, this is my code.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->refresh();
}
This is my ajax request
$.ajax({
url: '/getEventsForRefCode',
type: 'POST',
async: false,
data: {
reference_code: reference_code
},
dataType: 'JSON',
success: function (data) {
}
I didn't pass any token because I already have these
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
]) !!};
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I have a basket where I can have items that I can delete
When I click on the bin icon, it delete it straight from the page with this script
$('.delete').on('click', function (e) {
e.preventDefault();
var value = $(this).attr('data-value');
$.ajax({
url: '{{ path('ajax_app_basket_bill_delete_item') }}',
type: 'POST',
dataType: 'json',
data: {
'itemId': value
},
success: function (data) {
$('#item' + value).remove();
if (data['success'] == 1) {
$.ajax({
url: '{{ path('ajax_app_basket_bill_refresh_price') }}',
type: 'POST',
dataType: 'json',
data: {
'credit_box' : creditBox,
'code' : code
},
success: function (data) {
$('#t1').text(data['totalWithoutTax']);
$('#t2').text(data['tax']);
$('#t3').text(data['total']);
}
});
}
}
});
});
(here is the html in case you need to see this)
<a class="delete" data-value="{{ item.id }}" href="#"><i class="mdi mdi-delete"></i></a>
And my question is, how can I actually create a very simple dialog box to confirm deletion when I click on the bin icon without to remove it instantly.
thank you
The simpliest way would be with the javascript function confirm:
$('.delete').on('click', function (e) {
e.preventDefault();
if (confirm('Really delete this item?')){
var value = $(this).attr('data-value');
$.ajax({
url: '{{ path('ajax_app_basket_bill_delete_item') }}',
type: 'POST',
dataType: 'json',
data: {
'itemId': value
},
success: function (data) {
$('#item' + value).remove();
if (data['success'] == 1) {
$.ajax({
url: '{{ path('ajax_app_basket_bill_refresh_price') }}',
type: 'POST',
dataType: 'json',
data: {
'credit_box' : creditBox,
'code' : code
},
success: function (data) {
$('#t1').text(data['totalWithoutTax']);
$('#t2').text(data['tax']);
$('#t3').text(data['total']);
}
});
}
}
});
}
});
You can get more fancy with jQueryUI's .dialog() or other additional dialog box scripts easily foundable via Google or else.
I am trying to call ajax web method when button is clicked. This is the following code I have written.
$(function() {
$("<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: '{rating: \'' + textrating.val() + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {
},
error: function throwError(data) {
},
});
});
This is asp button I am using
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClick="btnBack_Click" />
The code behind is
[WebMethod]
[ScriptMethod]
public static void SubmitRatings(string rating)
{
if (HttpContext.Current.Request.QueryString["ID"] != null)
{
if (HttpContext.Current.Session["LoginId"] != null)
{
string str = HttpContext.Current.Request.Form["lblRate"];
RatingsBAL bal = new RatingsBAL();
bal.StoreRatings(HttpContext.Current.Session["LoginId"].ToString(), HttpContext.Current.Request.QueryString["ID"], Convert.ToInt32(rating));
}
}
}
But for some reason the web method is not being fired. Can anyone help me please? Thanks in advance.
Change $("<%=btnRatingSubmit.ClientID%>").click to
$('#'+"<%=btnRatingSubmit.ClientID%>").click
You were missing a #, which is used to select elements by their ids in jquery.
Full Code:
$(function () {
$('#' + "<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
});
function Functioncall(){
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
}
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClientClick="Functioncall()" />