Simple.... Pass perl variable to ajax success ? - javascript

Can anyone please let me know how can i pass a variable from perl subroutine back to ajax's success part for further manipulation ?
Here is the code for understanding more in detail
sub File_Check {
print header('application/json');
if (-e $filename) {
my #file_check=();
if (open(TXT,">>$filename")){
close TXT;
$file_check[0] = TRUE;}
else {
$file_check[0] = FALSE;
}
my $json->{"entries"} =\#file_check;
my $json_text= to_json($json);
prin $json_text;
}
}
The perl subroutine is File_Check. It will check if the file is open or not. If open, $file_check[0] variable would have TRUE as result. I want to pass this result in the below ajax success method.
$.ajax({
url: perlURL,
data: { action: "File_Check"},
type: 'get',
datatype: "json",
success: function (result) {
// data should be returned here for manipulation.
},
error: function (data) {
alert('Error');
}
});

The first argument to the success callback is the data received from the server:
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
You can specify the dataType as JSON, and send the appropriate content type and response from the Perl side.

i got an answer for this. if it helps anyone, i wld be glad.
sub File_Check {
print $cgi->header('text/plain;charset=UTF-8');
if (-e $filename) {
my $file_check="";
if (open(TXT,">>$filename")){
close TXT;
$file_check="TRUE";
}
else {
$file_check="FALSE";
}
print $file_check;
}
}
The above one is a perl subroutine. heres the ajax call i made to get the data from perl subroutine.
var perlURL= "$thiscode";
\$.ajax({
url: perlURL,
type: 'post
data: form_data,
datatype: "script",
success: function (result) {
console.log(result); // gives true or false depending on value from perl subroutine.
},
error: function(result) {
}
});

Related

Javascript - How to pass data from two API ajax calls to one function

I am attempting to make two seperate ajax calls to a third party API end point and display both its data on a HighChart graph. I am attempting to pass the data from both calls into my drawHighcharts function in order to display the data.
I am having issues with properly passing the data from both ajax calls. I've attempted to call back my drawHighcharts function in both my ajax calls. When console.logging both data I am only seeing the first stData but the odData is returning undefined. I am returning back stData twice and I believe that is because I am calling my function twice.
What is the proper way of handling both data into one function?
My expected outcome is to be able to access odData and stData in my drawHighCharts function.
function getStData() {
$.ajax({
type: "GET",
url: stUrl,
async: true,
success: function (stData) {
drawHighCharts(stData)
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function getOdData() {
$.ajax({
type: "GET",
url: odUrl,
async: true,
success: function (odData) {
drawHighCharts(odData)
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function drawHighCharts(stData, odData) {
console.log(stData, "st")
console.log(odData, "od")
}
You're getting undefined because in your ajax calls you're only passing one argument. In getStData you're passing only stData to drawHighCharts and for getOdData you're only passing odData. It would make sense why in the drawHighCharts function one of the two arguments (the second one) is undefined since you're only passing one argument. Instead, you can wrap multiple get requests in Promise.all. This way your requests will be made and when they are both finished the promise will resolve and you can access both API results in the then following the Promise.all. See below.
function getStData() {
$.ajax({
type: "GET",
url: stUrl,
async: true,
success: function (stData) {
return stData
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function getOdData() {
$.ajax({
type: "GET",
url: odUrl,
async: true,
success: function (odData) {
return odData
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function drawHighCharts(stData, odData) {
console.log(stData, "st")
console.log(odData, "od")
}
Promise.all([
getStData(),
getOdData(),
]).then(([stData, odData]) => drawHighCharts(stData, odData))
This post is related to fetch requests in React but Promise.all can be used with ajax in regular JS.
You can call getOdData() inside success of getStData() and pass stData to it. And then inside success of getOdData() you will have access to both stData and odData. Now you can call drawHighCharts() with both stData and odData.

TypeScript : Ajax call call always calling Error rather than success on success

In typescript I have a DataAccess Class so that all Ajax calls are routed through a single object to save repetition of code in a lot of places within my application.
In using this approach I have needed to use call backs to get the response back to the calling class so that the success and error can be handled accordingly.
This is the typescript
ajaxCall(retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
}
This is the compiled Javascript
AjaxDataAccessLayer.prototype.ajaxCall = function (retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
};
return AjaxDataAccessLayer;
This calls through to the ASP.Net MVC controllers perfectly fine, however the problem that I have is regardless of Success or Error the call back is always retError.
This is the calling Typescript
var _this = this;
var dataAccess = new DataAccess.AjaxDataAccessLayer(Fe.Upsm.Enums.AjaxCallType.Post,
Fe.Upsm.Enums.AjaxDataType.json,
"../../PrintQueue/DeletePrintQueueItems",
jsonObj);
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, xhr => {
// failure
alert("An Error Occurred. Failed to update Note");
});
When stepping through and looking at this the Status is OK and the response is 200.
So, Problem (as mentioned above) always calling xhr \ retError regardless of success.
Question: How do I get it to go into the right call back?
In your error handler, you were not passing all the parameters, so you are only checking whether the request finished successfully. However, there can be errors after that, like when the response is processed. You can handle errors betters like this:
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, (xhr, errorText, errorThrown => {
// failure
console.log(xhr, errorTest, errorThrown);
alert("An Error Occurred. Failed to update Note");
});
Based on the discoveries using this method, the error is that your controllers are returning empty responses, so you're getting an exception when jQuery tries to parse them, because an empty string is not valid JSON.

Should you check ajax return data or let javascript throw a error on empty data?

So when handling, for example, the success data in jquery, should you check if the return data has the necessary data like this:
success: function (data) {
if (data.new_rank !== undefined) {
$('._user_rank').html(data.new_rank);
}
}
Or let it fail when it is not present?
success: function (data) {
$('._user_rank').html(data.new_rank);
}
in the previous example you can check if something has changed and needs to be fixt because of the error.
What approach is the best?
It's better you check it, for other code that may be you have in complete or other event. If you didn't, they will not run after error. You can check it this too:
success: function (data) {
if (data.new_rank) {
$('._user_rank').html(data.new_rank);
}
}
jQuery ajax requests provide you a way to handle request errors.
$.ajax(url, {
success: function(data) {
// success
},
error: function() {
// error
}
});
If it's not a request error that you are trying to catch you still should handle error by yourself and not let javascript throw them all the way.
One solution I would say is follow strict data type in $.ajax like dataType: json.
Use success and error handler. And if the return data is anything other than json type it will be handled through error handler.
$.ajax(url, {
dataType: 'json'
success: function(data) {
// success
},
error: function() {
// error
}
});

how to determine jquery ajax return value or null

I am using jquery post ajax request to do something. the page submit.php return json value and sometime if fatal error occure it return nothing.
I cant determine the ajax return value or not. So how can this possible.
Here are the code i use:-
$.post( 'submitVoice.php', $('#frmVerify').serialize(), function( data ) {
//some code
}, 'json');
Thanks.
You can add .done and .fail handlers (or .then) in a chain after your $.post call:
$.post(...)
.done(function(data, testStatus, jqXHR) { /* use data here */ })
.fail(function(jqXHR, textStatus, errorThrown ) { /* error handling here */ });
Note that in neither case can you return a value to the caller. If you need to do this, return the result of $.post instead.
Instead use ajax call which has success and error callback as shown:
$.ajax({
url : 'submitVoice.php' ,
data: $('#frmVerify').serialize() ,
type: 'POST',
dataType :'JSON',
error: function() {
alert("error");
},
success: function(data) {
alert(data);
}
});
$.post is a shorthand way of using $.ajax for POST requests, so no difference.
$.ajax is generally better to use if you need some advanced configuration.
see reference here.
You can use error callback to know exact error.
$.post('wrong.html', {}, function(data) { })
.fail(function(xhr) { alert('Internal Server Error'); console.log(xhr)});
FIDDLE

Getting only the JSON from an ajax query

I'm using this script :
var test = $.ajax({ url : ("/areas/list"), type : 'GET', dataType : 'json', success : function(e) {
} });
I get this result in var text :
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Object
responseText: "{↵ "kind": "fusiontables#sqlresponse",↵ "columns": [↵ "INSEE_COM",↵ "KML",↵ "NOM_COMM"↵ ]}"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
The problem, is in this object, i would like get only the object in response JSON. I tried with test.responseJSON, but it doesnt work...
How can i get only the JSON ?
Thanks for your help !
F.
You're not doing anything with the returned data in the success callback.
This should work:
var test;
$.ajax({
url: "/areas/list",
type: 'GET',
dataType: 'json',
success: function(response) {
// Do what ever with the response here
console.log(response);
// or save it for later.
test = response;
}
});
If you decide to save the response in a variable you won't be able to access it straight away. The ajax request wont't be complete. Best to do your processing of the JSON object in the success callback.
The test variables value will be the value returned by the $.ajax() function call, not the result. $.ajax will not immediately return the value from the call, its asynchronous, that's why a callback (success: function(e) {}) is used. The success callback will be called when the ajax call have successfully fetched whatever it is asked to fetch.
Check what e is in the success callback!
$.ajax({url: ("/areas/list"), type: 'GET', dataType: 'json', success: function(e) {
console.log(e); // e == result from the ajax call.
}});
1. Are you returning JSON data?
In your AJAX, you're sending a request to a link at /areas/list - how are you handling that request in the Rails controller?
For it to return JSON data, it should read something like this:
#app/controllers/areas_controller.rb
def list
respond_to do |format|
format.json { return :json => "hello".to_json }
end
end
Posting your controller's code will be a big help for us all
2. Are you handling the JSON data correctly?
JSON data is different than "normal" javascript data. It has to be parsed when it is returned from the server, using the JSON parse functions:
$.ajax({
url : ("/areas/list"),
type : 'GET',
dataType : 'json',
success : function(data) {
var json_data = JSON.parse(data);
//do what you need here with the new array
}
});
you are trying to fetch value synchronously, which is not a good practice. You should try the following way:
var test;
$.ajax({
url:"/areas/list",
type:"GET",
dataType:"JSONP",
success:function(testdata){
console.log(testdata);
test=testdata;
}
});

Categories

Resources