ajax is not working in laravel - ajax

$(document).ready(function () {
$('#designation').change(function () {
var opt=this.value;
// var login_url = '{{ url("ajax_crud") }}';
alert(opt);
$.ajax({
//alert(opt);
type: "post",
url:'ajax_type' ,
data: {option:opt},
success: function(data){
alert('hiii');
//$("#div_dprtmnt").html(data);
//document.getElementById("department").innerHTML=data;
}
});
});
});
this is my view page.jquery is working.but inside the ajax alert is not working.how to use $.ajax in laravel.please help me

I think this is an issue with your CSRF token. Ensure you are attaching a token on each request to protect from forgery. You can do all this like this in ajax like this:
(document).ready(function () {
$('#designation').change(function () {
var opt = this.value;
$.ajax({
_token: "{{ csrf_field() }}",
type: "post",
url: "ajax_type",
data: {
option: opt
},
success: function(data){
alert('hiii');
}
});
});
});

Related

Laravel/Ajax delete function not refreshing my table after success

when I add my function fetchcategory(); in my delete ajax, my table is not refreshing:
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
alert('Category Deleted!');
// location.reload();
$('#deleteCategoryModal').modal('hide');
fetchcategory();
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
});
});
for a reference, my screenshot shows the alert, showing that the delete function follows through:
another reference is that my add function here reloads the page after a new table is added:
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data,
dataType: "json",
success: function (response){
console.log(response);
if(response.status == 400) {
$('#category_formCheck').html("");
$('#category_formCheck').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheck').append('<li>'+err_values+'</li>');
});
}
else
{
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#createCategory').modal('hide');
fetchcategory();
}
}
});
another problem of mine is that I tried to add the alert and refresh function inside:
$.ajax({
type: "DELETE",
but they do not show up, so I placed them inside on(click
why is my delete ajax not refreshing my table?
UPDATE:
I am aware of location.reload(); but adding this defeats the purpose.
the data does get deleted, I have to manually refresh the whole page to see the changes though.
You can do it in ajax success. I believe fetchcategory() method is populating data to table
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
// location.reload();
$('#deleteCategoryModal').modal('hide');
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
success: function(data) {
alert('Category Deleted!');
fetchcategory();
},
error: function() {
alert('Error occured');
}
});
});
</script>

Error 405 (method not allowed) using ajax method post laravel

There is an ajax script to remove comments under posts. When I click the delete button, I get a 405 error.
The console displays this: DELETE http://127.0.0.1:8000/id2/post/582 405 (Method Not Allowed), although the method is different url
My route Route::delete('/id{id}/post/{postId}/comment/{commentId}/delete', 'CommentController#deleteComment')->name('deleteComment');
And script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "DELETE",
data: {_token: token, id: id},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});
I need that when I press delete, the record disappears, but it does not disappear. To make the entry disappear, you need to reload the page
Under the hood Laravel actually uses POST request within an _method as parameter when you perform destroy operation, so your JavaScript section should looks like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e) {
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "POST",
data: {_token: token, id: id, _method: 'DELETE'},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});

Unable to receive data using AJAX post in Laravel

I am trying to send some variables(data),one is the checkbox text, and other is the value in the textarea field to the controller in Laravel through ajax, below is the script:
<script>
$('#btn1').on('click', function() {
$('input[type="checkbox"]').on('click', function() {
var aa=$(this).next('label').text();
var bb=$('textarea#txt2').val();
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type: "POST",
url: "/masterdata",
//dataType: 'json',
data: {aa,bb},
success:function(){
console.log(data);
}
,error:function(){
console.log("Error!!!!");
}
});
});
});
</script>
On trying to retrieve the request values in the controller, only the request token gets displayed, and the ajax function doesn't display the success or error message either.What am I missing here?
you need to set a variable on ajax success like this:
$.ajax({
type: "POST",
url: "/masterdata",
//dataType: 'json',
data: {aa,bb},
success:function(response){
console.log(response);
}
,error:function(){
console.log("Error!!!!");
}
});
Try your data as in this format:
data:{'posa': aa, 'posb': bb},
and
success:function(data){
console.log(data);
}
Hope this helps.
i found two issue in your ajax request.
you have to change data: {aa,bb}, to object like data: {aa : aa, bb : bb},
Your success response log is wrong. Current code success:function(), it should be success:function(data)
Full output of new code is :
<script>
$('#btn1').on('click', function() {
$('input[type="checkbox"]').on('click', function() {
var aa=$(this).next('label').text();
var bb=$('textarea#txt2').val();
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type: "POST",
url: "/masterdata",
dataType: 'json',
data: {aa : aa, bb : bb},
processData: false,
cache: false,
async :false,
success:function(data){
console.log(data);
}
,error:function(){
console.log("Error!!!!");
}
});
});
});
</script>
To get parameter value in controller use
/**
* Store.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$aa = $request->input('aa');
$bb = $request->input('bb');
//Your code here
}
<script>
$('#btn1').on('click', function() {
$('input[type="checkbox"]').on('click', function() {
var aa=$(this).next('label').text();
var bb=$('textarea#txt2').val();
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type: "POST",
url: "/masterdata",
//dataType: 'json',
data: 'aa=test'+'&bb=test',
success:function(){
console.log(data);
}
,error:function(){
console.log("Error!!!!");
}
});
});
});
</script>

function is callign but Ajax is not calling

Here I am using codeigniter with highchart. Highchart will change after dropdown select by calling ajax.
Here, function is called but ajax is not calling. So, where I go wrong with this.
This is my ajax:
$('.edit').click(function(e)
{
e.preventDefault();
$.ajax({
url: '<?php echo site_url("Chart/branchwiseactivity");?>',
type: 'POST',
data: {
series: []
},
dataType: 'json',
success: function(json)
{
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
chart = new Highcharts.Chart(options);
}
});
e.preventDefault();
});

Laravel - DELETE Ajax request

I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection

Resources