Laravel/Ajax delete function not refreshing my table after success - ajax

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>

Related

Why do I always get undefined value from other data?

I always get undefined values from other data for example: ID:123 the response for this would be the NetAmount: 1000.00 after sending it using AJAX GET REQUEST, so for other data it would just return an undefined value.
MY AJAX
function viewBill(AccountNum){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "GET",
url: "{{ route('view.billing') }}",
data: {AccountNum:AccountNum},
dataType: 'json',
async: true,
beforeSend: function() {$('#userBill').html('Getting Information...')},
success: function(res) {
console.log(res.NetAmount);
$('#checkBill').css('display','block');
$('#userBill').html('₱ '+res.NetAmount);
},
error: function(res) {console.log('Error');},
complete: function() {
}
});
}
My Controller
public function viewBilling(Request $request){
if($request->ajax()){
$viewBilling = Table1::addSelect(['PaymentStatus' => Table2::selectRaw('COUNT(*)')
->whereColumn('AccountNumber','Table1.AccountNumber')
->whereColumn('ServicePeriodEnd','Table1.ServicePeriodEnd')
->where('AccountNumber', $request->AccountNum)
])->where('AccountNumber', $request->AccountNum)
->orderBy('ServicePeriod','desc')
->first();
return Response()->json($viewBilling);
}
}
I tried using dd() and it turns out there are values for the account I tried from the one that returns the NetAmount and from the one that returns an undefined value.
Found the problem, because of the parameter of my viewBill() function, I don't know why would it give me undefined values from other data I did check using the network tools, it just that it wasn't able to send the AccountNumber to the Controller. So I tried removing the parameter. I have an input tag that already has the value of the Account Number so instead of using the above code, I did this
function viewBill(){
var AccountNum = $('#inputAccountNum1').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post({
url: "{{ route('view.billing') }}",
data: {AccountNum:AccountNum},
dataType: 'json',
beforeSend: function() {$('#userBill').html('Getting Information...')},
success: function(res) {
$('#checkBill').css('display','block');
$('#userBill').html('₱ '+res.NetAmount);
},
error: function(res) {console.log('Error');},
complete: function() {
}
});
}

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>

ajax code to check new records at database

I am using laravel, and I want to check if there are new records inserted into the database, I want an Ajax code the returns with the result, I don't know ajax so please help me
this is my controller
public function newrecord($target_id){
$record = Message::where('target_id', $target_id)->get();
return $record->count();
}**strong text**
and this is my ajax code
$(document).ready(function(){
var ajaxCall=function()
{
$.ajax({
url:"{{ url('/record/'.$auth->id) }}" ,
type: "GET",
datatype:"html",
data:{},
success:function(data) {
$('.msgnum').html(data)
console.log('new record);
},
error: function(data) {
console.log('error');
}
});
}
setInterval(ajaxCall,5000);
});
all I get is just a loop or " new record " in the console log
Do I need to return anything to tell that there is a new file, any help?
Try this, of course modify the code to how you want it to work but wrap the whole thing in setInterval, you don't even need the document.ready()
<script type="text/javascript">
setInterval(function() {
$.ajax({
url:"{{ url('/record/'.$auth->id) }}",
type: "GET",
datatype:"html",
data:{},
processData:false,
success: function(data){
$('.msgnum').html(data)
console.log('new record');
error: function(data) {
console.log('error');
}
},
error: function(){}
});
}, 5000);
</script>

Laravel - ajax creates double input

I have made this ajax request to show the validation errors and prevent the page to reload
$(document).on('mousedown', ':submit', function() {
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
All is fine with this code! The problem is that after successfull submit i have 2 inputs in DB...how can i prevent this?
Are you sure the form isn't actually submitting and saving the values once by post and once by ajax? Usually if you're capturing a submit event you listen for the forms submit even not the mousedown event of the submit button e.g.
$('form').on('submit', function(e) {
// Stop the forms default submit action
e.preventDefault();
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
Also the e.preventDefault() will prevent the form from submitting itself along with your ajax action. Also you'd best off selecting your form by an ID or class name.

jquery form validation before ajax request?

this is a simple code to call the form validation function before submit it with ajax request
$(document).ready(function(){
$('#errors').hide();
var serializedData= $("#categoryForm").serialize();
$("#categoryForm").submit(function(){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
beforeSubmit: function(){
return $("#categoryForm").validate();
},
success: function(response) {
$('#status').html(response);
}
});
return false;
});
});
it pass the validation and send the ajax request before validating the form
i tried to make the request if the validation true
$(document).ready(function(){
$('#errors').hide();
var serializedData= $("#categoryForm").serialize();
$("#categoryForm").submit(function(){
if($("#categoryForm").validate()){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
success: function(response) {
$('#status').html(response);
}
});
}
return false;
});
});
but this not working too
Dont submit the form in any case, do the check when the submit button is clicked - and then if it succedeed - do the submiting.
Try to do it as follows:
$("#submitButton").click(function(){
if($("#categoryForm").validate()){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
success: function(response) {
$('#status').html(response);
//if true:
$("#categoryForm").submit();
}
});
}
return false;
});

Resources