Getting only the JSON from an ajax query - javascript

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

Related

AJAX: only error callback is been fired

I have declared success and error callbacks, but in case of status code 200 also it calls error callback only.
I have been making curl call to some other php file too inside registry.php.
Here what i tried:
$.ajax({
type: "POST"
,data: {
action: "blah"
,mobileNo: that.mobNo
,token: that.key
}
,url: "http://90.8.41.232/localhost/registry.php"
,cache: false
,dataType: "json"
,success: function (response) {
console.log("success");
}
,error: function () {
console.log("error");
}
});
I have read in documentation that we don't have to call success callback explicitly, hope it's correct.
Any idea how to call success callback when it is 200 status code.
RESPONSE
hope this will help, this I copied from chrome console, not printed by console.log().
bort: (statusText)
always: ()
complete: ()
done: ()
error: ()
fail: ()
getAllResponseHeaders: ()
getResponseHeader: (key)
overrideMimeType: (type)
pipe: ()
progress: ()
promise: (obj)
readyState: 4
responseText: "{"success":"Mobile No 9535746622 is approved"} {"report":true}"
setRequestHeader: (name,value)
state: ()
status: 200
statusCode: (map)
statusText: "OK"
success: ()
then: ()
As you have mentioned that you are making a curl call to some other php, what happens is whenever you make curl call you have to return the response of the curl to the client. So to transfer the return value of curl call, you have to set an option curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);.
This will sort your problem. Hope so.
First, checkout the real error you get (not certain you really get a 200 status ?)
error: function (err) {
console.error("error");
console.log(err);
console.log(err.stack);
throw err;
}
Show us the resulting log please.
I did that a few weeks ago and for me it works if I call it like
$.ajax(
{
type: "POST",
data: { action: "blah", mobileNo: that.mobNo, token: that.key },
url: "http://90.8.41.232/localhost/registry.php",
cache: false,
dataType: json,
})
.success (function (data, status, jqxhr)
{
// do your stuff
})
.error (function(x, status, jqxhr)
{
// handle your errors
});

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

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

How to optimize (minimize) jQuery AJAX calls

I have over 50 AJAX calls from different functions of my code. All these calls have a similar structure with different data/url/callback params:
var jqXHR = $.post('/dba/port.php', {
mode: "del_wallfunds",
pdata: cdata,
wname: wName
},
function (data) {}, "json")
.done(function (data) {
var msg = data.msg;
if (msg.indexOf("Error") == -1) {
alertify.success(msg);
delSelected(selGroup);
} else {
alertify.error(msg);
}
})
.fail(function () {
alertify.error("Error .....");
});
I am thinking how to write a function that would return that var jqXHR to minimize the total size of the code. It is not a problem to pass all static variables like URL, error strings etc. But the problem is that all callback functions on ".done" are different and I don't know how to pass these callback functions as variables.
One way would be to call a single "universal" function on .done and pass a "switch" variable to that function, but it doesn't seem to be an elegant solution.
Any suggestions how to it in some elegant way?
Thanks
Either pass the done callback function as an argument when calling your function:
function ajaxCall(url, data, doneCallback) {
return $.post(url, data, doneCallback, "json").fail(...);
// or
return $.post(url, data, function() {}, "json").done(doneCallback).fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'}, function(data) {
// do something
});
Or return the jqXhr object from the function, and assign the done callback then:
function ajaxCall(url, data) {
return $.post(url, data, function() {}, "json").fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'});
jqXhr.done(function(data) {
// do something
});
Alternatively switch to using jQuery.ajax() instead, and pass the entire options object in:
function ajaxCall(options) {
return $.ajax(options).fail(...);
}
var jqXhr = ajaxCall({
url: 'yoururl.php',
data: {key: 'value'},
dataType: 'json'
});
jqXhr.done(function(data) {
// do something
});
You can try to :
turn "request successfully returned a treatment error" into a "rejected request",
put the "alertify" processing in a common callback
Here is a sketch of what this could give :
function myAjaxApi(url, data){
var myAjaxCall = $.post(url, data, function (data) {}, "json")
.then(function (data) {
// using .then : change "request succesful with error state"
// to "rejected state"
var msg = data.msg;
if (msg !== undefined && msg.indexOf("Error") >= 0) {
var dfd = $.Deferred();
// try to match the same signature as the "error" option
dfd.reject(this, msg);
return dfd;
} else {
return data
}
});
myAjaxCall.done(function(data){
if (data.msg) {
alertify.success(data.msg);
}
}).fail(function (jqxhr, msg) {
if (!msg) { msg = "Error ....."; }
alertify.error(msg);
});
return myAjaxCall;
}
//usage
myAjaxApi('/dba/port.php', {mode: "del_wallfunds", pdata: cdata, wname: wName})
.done(function (data) {
// the ".done()" queue will not be executed if msg contains "Error" ...
delSelected(selGroup);
});
Some parts should be written with more care ; the above example is meant to illustrate how you can wrap your repeated ajax calls inside a common api.

Wait until Ext.Ajax.request responds with success before setting variable

Below you will see some code to set the currently logged in user for an extjs 4 application. If I have the alert uncommented, the code seems to wait until the alert is accepted before the code continues (it seems). That allows enough time for the asynchronous call to complete with a success. If I comment out the alert, the variable "employeeFilter" never gets set because the AJAX call didn't come back in time. In which case, it sets the "employeeFilter" to null instead. How can I fix this so it waits until the AJAX response comes back in success?
var loggedInUserId = null;
Ext.Ajax.request({
url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
method: 'POST',
jsonData: { 'x': 'x' },
success: function (response, opt) {
loggedInUserId = Ext.decode(response.responseText).d;
},
failure: function (response) {
}
});
//alert(loggedInUserId);
var employeeFilter = loggedInUserId;
var projectFilter = '-1';
I would have done this.
var employeeFilter;
Ext.Ajax.request({
url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
method: 'POST',
jsonData: { 'x': 'x' },
success: function (response, opt) {
employeeFilter = Ext.decode(response.responseText).d;
//Do here whatever you need to do once the employeeFilter is set. probably call a function and pass the employee filter as parameter.
},
failure: function (response) {
}
});
var projectFilter = '-1';

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

Categories

Resources