Ajax .done() no data - javascript

I am using the following jquery to make an ajax call:
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET",
dataType: "json"})
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
The alert pop up always says that responseText is undefined. The page I am "get"ting is well formatted JSON and if I run these commands in the console one at a time everything works fine. What is wrong?

You're looking for responseText in the response, it won't be there. You'll find it instead on the jqXHR object itself (which is the third parameter passed to your done() function, and also returned by your whole $.ajax() call).
And because you have dataType: "json" the response is already a JSON parsed object.
Change this:
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
To just this:
.done( function(data){
if(data.success){
//stuff here
}
})

When you set the dataType in a jQuery.ajax call it will be returned as a parsed object. So your request object in .done is actually your parsed json string
If you don't want jQuery to automatically parse your JSON you can remove the datatype from the call.
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET"
}).done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})

This is because the first parameter of the done function is not the XHR object but the contents of the responseText as an object already. jQuery handles all that for you and so there's no need to do any manual conversion.
the done function is called whenever the ajax call is successful anyways so no need to re-check it and the fail function is called when a response other than 200 is returned.

Related

Abstracting an AJAX call so I can make my code more dynamic

I am trying to take a typical jQuery AJAX call and wrap it in its own function so I can call it with different parameters to make it more dynamic. I seem to be missing something about the success or with callbacks in general. The basic function is to pass JSON to a Google charts implementation. This works if I hardcode the JSON but I want to pick it up out of my REST API. Right now I have this small bit of code:
var getAjax = function (url){
$.ajax({
url: url,
dataType: json,
success: drawChart
});
}
var drawChart = function (data) {
jsonData = data;
console.log(jsonData);
// Create our data table out of JSON data loaded from server.
var jsonDataTable = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
//var chartPie = new google.visualization.PieChart(document.getElementById('pie'));
//var chartBar = new google.visualization.BarChart(document.getElementById('bar'));
var chartJson = new google.visualization.BarChart(document.getElementById('json'));
//chartPie.draw(trailerData);
//chartBar.draw(chewyData);
chartJson.draw(jsonDataTable);
}
console.log('got here');
getAjax("data/dashboard0");
When I check the console I can see a 200 from jQuery but I get nothing in my window. I also tried using the getAjax(data) to define the function but in my reading I saw I should do it like this but I am not quite sure which approach is the correct one.
I imagine your syntax error is preventing the code from working...
The dataType should be a string:
dataType: 'json',
Note on response data - If you need the raw data, rather than a parsed data object, you can get that from the raw XHR... no need to unwind the parsed data into another string.
var drawChart = function (data, status, jqXHR) {
var jsonString = jqXHR.responseText;
var parsedData = data;
//...
You should instead return a promise in your function, then resolve it via .then(). success: drawChart is not very dynamic. Observe the following...
var getAjax = function (url){
return $.ajax({ url: url, dataType: 'json' });
}
[...]
getAjax('data/dashboard0').then(function(response) {
// callback - do drawing tuff
});
console.log('got here before callback')
Check out the jQuery deferred docs for more information
The success's method first argument is parsed. If you need a JSON string then you have to JSON.stringify(responseData) which will return a JSON string.
Even if you set dataType: 'json', jQuery will still parse the response.
Please read the jQuery Docs for dataType:
dataType: "json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
(See json.org for more information on proper JSON formatting.)

How to call code-behind method from 'success' in ajax callback?

How to modify below code to use 'success' to call testMethod() in code-behind ?
I need to wait for return value from testMesthod() and process it.
$.ajax( {
url : 'myPage.aspx/testMethod',
type : "POST",
contentType : "application/json; charset=utf-8",
data : "{'name':'" + aNb + "'}",
dataType : "json"
}).done(function() {
alert("ok");
}).fail(function() {
alert("not ok");
});
Above code does not work because somehow latest JQuery version (1.10.1) gets overwritten by 1.3.2.
Thank you
You would need to pass the callback function to the function that wraps your $(ajax).
function getData(ajaxQuery, callBack){
var ajaxHREF = 'your url';
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
},
However, a much better way of doing this is the global success event. It is better because you have all of the properties of the call available to you to enable dynamic processing of the results. Create the global success event inline = $(document).ajaxSuccess this gets called for all jquery ajax success events so you need to differentiate which calls apply to your specific handler (to each global handler).
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var mimeType = settings.mimeType;
if (query.match(/ameaningfulvalueforthishandler/)){
if(mimeType.match(/application\/json/)){
var jsonData = $.parseJSON(xhr.responseText);
}
}
}
Thank for replies, but I still do not see how callbacl can help me.
I need to call webmethod in code-behind: testMethod()
Ajax call does it, url = "myPage.aspx/testMethod" will 'call' webmethod testMethod(),
but it's asynchronous and returns quickly into 'success' section of ajax call.
But, I need to Wait for testMethod() to finish processing, retrieve result returned by testMethod() and process it.
Asynchronous ajax will return us into 'success' without waiting for testMethod() to finish,
and we will not get any data in response.
So, how callback helps me to achieve it?
function getData(ajaxQuery, callBack){
var ajaxHREF = "myPage.aspx/testMethod";
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
});
Thank you
#Karen Slon - If I understand the question correctly, I think you need to conceptually separate the client side from the server side. The callback in .success/.done or global ajaxSuccess event enable your web page to initiate the request and keep on processing while the server side is processing your request 'myPage.aspx/testMethod'. When it completes successfully it returns to the success event. Now if testMethod does not return anything then you will find yourself in the success event event without a result. But you cannot get there unless web method testMethod has completed successfully and returned control. The .done event in your example only has alert("ok");. What makes you believe that the web method testMethod is not complete when the .done event occurs?
Look at these posts for better examples:
jQuery.ajax handling continue responses: "success:" vs ".done"?
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
http://api.jquery.com/category/deferred-object/

JSON object returned but not accessible via $.ajax()

I have an ASP.NET MVC Web API that I am calling from an $.ajax() method. The correct JSON is returned from my API, but the object is not accessible. The error received in my console when trying to log the value for "Name" is:
Uncaught TypeError: Cannot read property 'Name' of undefined
JSON:
[{"id":2,"Name":"thom","Picture":"thom.jpg","About":"I'm a guy. This is my profile. Now quit staring and get out of here.","Location":"London"}]
jQuery:
$.ajax({
cache:false,
type: 'GET',
dataType: 'json',
url: 'http://localhost:3235/Users/searchUsers?callback=?&searchString=' + searchString,
complete: function (data) {
console.log(data[0].Name);
}
});
Any help would be appreciated. Thanks!
I think you mean to use the success function. The complete function doesn't take data as a parameter.
From the docs:
completeType: Function( jqXHR jqXHR, String textStatus )A function
to be called when the request finishes (after success and error
callbacks are executed). The function gets passed two arguments: The
jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
categorizing the status of the request ("success", "notmodified",
"error", "timeout", "abort", or "parsererror").
The method's first parameter is not the received data. You can get it though the jqXHR object but I don't think you really need to use this option. Use success instead:
success Type: Function( PlainObject 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; a
string describing the status; and the jqXHR (in jQuery 1.4.x,
XMLHttpRequest) object.
ya complete fires after the service call is being made and it does not contain data from the service response..
use
$.ajax({
url:'ur url',
type:'GET'
success:function(data){
// way to acces ur object code goes here
console.log(data[0].Name);
},
error:function(){
// Error handling
}
});
happy coding

How to get a value from a JSON hash

In a jquery ajax call I get sent back some JSON from the server and want to use some of it in the success callback. I pass in the data, but how do I get at a specific value (say "id")?
I tried this but I get undefined:
success : function(data) {
alert(data["id"]);
},
Your ajax request should look something like this:
$.ajax({
url: "...",
dataType: "json",
success: function(data){
alert(data.id);
});

Access json data from php

I have a problem accessing JSON data. I'm new to JSON and jquery so there is probably a easy solution to it and I would be glad to find out.
My jQuery:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
}
);
currentPage.php:
$returnArray['left'] = 'test_left';
$returnArray['right'] = 'test_right';
$returnArray['numLeft'][] = 1;
$returnArray['numRight'][] = 2;
$returnArray['numRight'][] = 3;
print json_encode($returnArray);
I tried to access the data like this:
data.left
data['left']
but it returns blank, how is the best way to access the data in the HTML-file?
I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
},
"json"
);
Provide the datatype you expect to get as parameter to the .post() method (in your case json):
$.post("currentPage.php",{'currentPage': 1},
function(data){
$("body").append(data);
},
'json' // <-- add the expected datatype
);
I think the default is to treat the result as HTML. Read the documentation.
jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.
dataType The type of data expected from the server.
In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:
"json": Evaluates the response as JSON
and returns a JavaScript object. In
jQuery 1.4 the JSON data is parsed in
a strict manner; any malformed JSON is
rejected and a parse error is thrown.
(See json.org for more information on
proper JSON formatting.)
You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.
$.ajax({
url: "currentPage.php",
data: {
'currentPage': 1
},
dataType: "json",
type: "post",
success: function(data) {
$("body").append(data);
}
});

Categories

Resources