Why do I always get undefined value from other data? - ajax

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() {
}
});
}

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>

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>

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

Error in the returned jsonp

$.ajax({
type: 'GET',
url: 'http://api.xhanch.com/islamic-get-prayer-time.php?lng=34.4366455078125&lat=31.48957771850194&yy=2013&mm=5&gmt=3&m=json',
dataType: 'jsonp',
success: function () {
console.log('Success!');
},
error: function () {
console.log('Uh Oh!');
},
jsonp: 'jsonp'
});
when I run this code I get an error in the return json object
Uncaught SyntaxError: Unexpected token:
Why?
The problem is jsonp: 'jsonp' is calling the method jsonp that doesn't exist in your code. If you really need this, just create the method or remove it.
Remove
$.ajax({
type: 'GET',
url: 'http://api.xhanch.com/islamic-get-prayer-time.php?lng=34.4366455078125&lat=31.48957771850194&yy=2013&mm=5&gmt=3&m=json',
dataType: 'jsonp',
success: function () {
console.log('Success!');
},
error: function () {
console.log('Uh Oh!');
},
});
Or create the method
$.ajax({
type: 'GET',
url: 'http://api.xhanch.com/islamic-get-prayer-time.php?lng=34.4366455078125&lat=31.48957771850194&yy=2013&mm=5&gmt=3&m=json',
dataType: 'jsonp',
success: function () {
console.log('Success!');
},
error: function () {
console.log('Uh Oh!');
},
jsonp: { jsonp: false, jsonpCallback: "callbackName" }
});
function callbackName(){
/*do something*/
}
Reference: http://api.jquery.com/jQuery.ajax/
jsonp
Type: String Override the callback function name in a jsonp request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }

How do I get JSON result from jquery .ajax call in done()?

I am trying to use the newer .done() syntax for a call to .ajax(), but I don't see how to get the data returned from the server into my .done() function. Here is my code:
function checkLink(element) {
var resultImg = $(element).parent().parent().find("img");
resultImg.attr("src", "/resources/img/ajaxLoad.gif");
$.ajax({
type: 'POST',
url: '/services/Check.asmx/CheckThis',
data: '{somedata: \'' + whatever + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: onSuccess,
error: onFailure
}).done(function () { success2(resultImg); });
}
function success2(img) {
img.attr('src', '/resources/img/buttons/check.gif');
}
function onSuccess(data) {
// The response from the function is in the attribute d
if (!data.d) {
alert('failed');
}
else {
alert('hurray!');
}
}
checkLink is called from a simple button push. Both onSuccess() and success2() are firing just fine. But... what I need is the "data" parameter from onSuccess passed to success2... or alternately, be able to pass "resultImg" to onSuccess (although I would prefer using .done instead of the deprecated method). It seems I can either pass my own parameters, or access the JSON result from the AJAX call... but not both. How do I accomplish this?
You can close over the resultImg variable:
function checkLink(element) {
var resultImg = $(element).parent().parent().find("img");
resultImg.attr("src", "/resources/img/ajaxLoad.gif");
$.ajax({
type: 'POST',
url: '/services/Check.asmx/CheckThis',
data: '{somedata: \'' + whatever + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: onSuccess,
error: onFailure
}).done(success2);
function success2(data) {
resultImg.attr('src', '/resources/img/buttons/check.gif');
// do whatever with data
}
function onSuccess(data) {
// The response from the function is in the attribute d
if (!data.d) {
alert('failed');
}
else {
alert('hurray!');
}
}
}

Resources