JSON returned AJAX post jQuery undefined - ajax

I am using jQuery to get a list of Names as JSON string -
`
$.ajax({ type: 'POST', url: "../Names.aspx", dataType: 'json', contentType: "application/json; charset=utf-8", data: "NAME=ALL_PROFILES", success: function (data, textStatus, jqXHR)` {
var html = '';
var obj = jQuery.parseJSON(data);
$.each(obj, function (key, val) {
html += '<option value="' + val + '">' + val + '</option>';
alert("Success" + val);
})
$('#selName').append(html);
$('#selName').selectmenu('refresh');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error ' + jqXHR.val + errorThrown.val + textStatus.val);
}
});
The back end is an asp.net page, and when I debug I get the string as "{"Name":["Maria","John","Raj","Rosh","Tony","Name","test3","test4","test5","test6"]}", which I put in JSONLint and validated. It returns an undefined error in the AJAX request above. If I try with a single string "Name":"John", it works perfectly. The function for adding option is not correct for an array of JSON strings(I will work on it once it enter the success block), but I don't understand why it returns an undefined error when it is returning a valid JSON string. Any help would be appreciated.

If your aspx page returns valid JSON and you are using dataType: 'json', you should not use jQuery.parseJSON() on the returned data, since jQuery already parses the returned JSON string into an object.
If you use "Name":"John" it is not valid JSON, so JQuery enters the error callback.

Put an extra paranthesis around the result and it works.It is strange since JSONLint is not validating it now

Related

Value cannot be null. Parameter name: value, while calling httppost via ajax post

I am trying to receive a post request with some json string
var contentType ="application/x-www-form-urlencoded; charset=utf-8";
$.ajax({
type: "POST",
data: JSON.stringify(fileData),
url: "http://hercules/JsonTest/api/Getjson/sendData",
contentType: contentType,
processData: false,
error: function (qXHR, textStatus, errorThrown) {
alert("failure: " + qXHR.status + ":" + textStatus + errorThrown);
},
success : function(data) {
alert("Success : " + data);
}
});
and in my webapi
[System.Web.Http.HttpPost]
[System.Web.Http.ActionName("sendData")]
public string sendData([FromBody] string jsonString)
{
logData("Entering SendData : " + jsonString);
return "Success";
}
But, my jsonString posted is not received in the webapi. it is throwing error Value cannot be null.
Parameter name: value
What could be the reason.
I was testing the code directly in my visual studio and the same was working fine. but once i published the same in machine, and tried to access via a jsFiddle, then the string is showing empty.
I got the issue resolved.
In my ajax post request i modified
data: JSON.stringify(fileData),
to
data: '=' + fileData,
With equal to added, the data is correctly received in HTTPPOST method of MVC.
Thanks...

JSONP json callback method not called : parsererror

I have the following ajax function using jsonp:
function PopulateDivisions1()
{
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisions?callback=?',
dataType: "jsonp",
//jsonp: false,
jsonpCallback: "myJsonMethod",
success: function(data) {
alert('yes');
$("#divisionSelect").append($('<option></option>').val("-99").html("Select One"));
$.each(data, function(i, item){
$("#divisionSelect").append($('<option></option>').val(item.Name).html(item.Name));
});
},
error: function(xhrequest, ErrorText, thrownError) {
alert("Original: " + thrownError + " : " + ErrorText);
}
});
}
I am getting the following error:
myJsonMethod was not called : parsererror
If I look at Fiddler, I am getting the following data back, I added the callback name to the front, as I saw that suggested, if I take it out it still doesn't work.
"myJsonMethod([{\"Id\":1,\"Description\":\"Executive\",\"Name\":\"Executive \"},{\"Id\":2,\"Description\":\"ASD\",\"Name\":\"Administrative Services Division \"},{\"Id\":3,\"Description\":\"COM\",\"Name\":\"Communications \"},{\"Id\":4,\"Description\":\"CP\",\"Name\":\"Contracts and Procurement \"},{\"Id\":5,\"Description\":\"PMD\",\"Name\":\"Program Management Division \"},{\"Id\":6,\"Description\":\"RED\",\"Name\":\"Research and Evaluation Division \"},{\"Id\":7,\"Description\":\"IT\",\"Name\":\"Information Technology \"}])"
Here is the method in my controller:
public string GetAllDivisions(string callback)
{
var divisions = _DivisionModel.GetAllDivisions();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serializer.Serialize(divisions);
string result = callback + "(" + json + ");";
return result;
}
I'm not getting to my success call, what am I missing or doing wrong?
You dont have to specify a success callback because the jsonp callback will happen automatically as the server side code will return javascript in case of jsonp.
Refer the below answer for working example.
Using jquery jsonp returns error callback function was not called

CRM 2011 json data.d.results undefined but URL shows data

I'm trying to do a simple odata query and the call is successful, but the results are always undefined. I've thrown the URL into the description, copy and pasted it, and it works just fine. I've tested dozens of different ways to see what the object is, and the results are undefined. What am I missing??
UPDATE: As mentioned below, part of the problem was referencing data.d.results. When I referenced data.d.results[0], I actually got the error message "Unable to get property '0' of undefined or null reference." I wanted to add that here because I found almost NO help when searching for that error message.
The final answer was a combination of:
data.d for only one result
correct casing for system fields; "resProd.Description" as opposed to "resProd.description."
Back to orig Question:
Below is the code I'm using:
function setOPDefaults() {
// Create lookup
var lookupItem = new Array();
lookupItem = Xrm.Page.getAttribute("productid").getValue();
if (lookupItem != null)
{
var guid = lookupItem[0].id;
}
var crmOrg = window.location.pathname.split('/')[1];
var serverUrl = window.location.protocol + "//" + window.location.host + (crmOrg == 'userdefined' ? '' : '/' + crmOrg);
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ODATA_PREP = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
// Tried both of the following URLS (obviously not at the same time)
url: ODATA_PREP + "/ProductSet(guid'" + guid + "')",
url: "http://crm/<<orgname>>/XRMServices/2011/OrganizationData.svc/ProductSet(guid'67BA90A3-39D8-E211-8D1E-0050569A6113')",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
var resProd = data.d.results;
alert(resProd.length); // This is undefined
// Below is where I load the URL into description just for testing.
// When I copy and paste this URL into the browser, it pulls up results with correct data
Xrm.Page.getAttribute("description").setValue(ODATA_PREP + "/ProductSet(guid'" + guid + "')");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Ajax call failed: " + textStatus + " - " + errorThrown + " || " + XmlHttpRequest.responseText);
}
});
}
You're acessing just one record, so try put something like that:
data.d
data.d.results is used for multiple results. Another thing you can do to validate the results is put your url directly in browser.
In such cases, I use Fiddler. You can use it to debug your http/https trafic.
Or. If you have crm 2011 RU 12, you can use built-in Chrome debugger. Press F12. In console tab - right click -> Log XMLHttpRequest

How To Use Object Returned By VB.NET Web Service

I have a Javascript function that passes a string into a VB.NET Web Method. Here is the Javascript
function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";
//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
alert("It worked: " + e);
},
error: function (e) {
alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial
Here is the VB.NET web Method. The Web Method simply takes the string and sends it back to the Javascript:
<WebMethod( )> _
Public Function testWebService(str As String) As String
Return str
End Function
When the Web Method returns successfully my AJAX block returns the following message:
"It worked: [object Object]"
So my question is, how do I use the returned object? The object should be a string containing the words "hello world" but how do I access the string value?
ASP.Net WebMethods wrap their return values in a JSON object with a d property. (You can see this in the response body in the browser's developer tools)
You need to write e.d to get the actual value.
if you do:
$(e).text()
You'll get your text;
So change this to be:
function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";
//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
alert("It worked: " + $(e).text());
},
error: function (e) {
alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial

jQuery AJAX response always returns nothing

The following code returns a blank response no matter whether or not the Function exists, or even the Web Service file entirely:
$.ajax({
url: "/ws.asmx/HelloWorld"
, type: "POST"
, contentType: 'application/json; charset=utf-8'
, data: '{ FileName: "' + filename + '" }'
, dataType: 'json'
, success: function (data) {
}
});
Why is this?
Also, might be worth noting, $.load() works fine!
Your error is that you try to construct JSON data manually and do this in the wrong way:
'{ FileName: "' + filename + '" }'
You should fix the code at least to the following
'{ "FileName": "' + filename + '" }'
because correspond to the JSON specification the property names must be also double quoted.
Next problem can you has if the filename has some special characters. For example, in case of
var filename = '"C:\\Program Files"'; // the '\' must be escaped in the string literal
you should has as the data the corresponding JSON string
'{ "FileName": "\\"C:\\\\Program Files\\"" }'
as the corresponding JSON data because of '\' and '"' must be escaped. It looks dificult. So I stricly recommend you to construct JSON strings with respect of JSON.stringify function from the json2.js. Then the code will be
$.ajax({
type: "POST",
url: "ws.asmx/HelloWorld",
data: JSON.stringify({ FileName: filename }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error Occured!" + " | " + XMLHttpRequest.responseText +
" | " + textStatus + " | " + errorThrown);
}
});
which is simple and clear enough. The next advantage of the usage JSON.stringify is that the most modern web browsers has native support of the function and the function work very quickly.
By the way in case of the usage of JSON.stringify you can easy call web service methd having very complex data structures (classes) as the parameters and not only strings.
UPDATED: One more remrk to reduce possible misunderstanding. It you later deceide to use HTTP GET instead of HTTP POST to call the web method you will have to change the data parameter from
JSON.stringify({ FileName: filename })
to
{ FileName: JSON.stringify(filename) }
UPDATED 2: You can download this Visual Studio 2010 project which I used to test all before I posted my answer. I included as "Web-3.5.config" the web.config for .NET 3.5. All different commented data values included in the default.htm work. If you want make tests with HTTP GET you should uncomment the section in web.config which allows HttpGet and use ScriptMethod having UseHttpGet = true. All the lines are included in the demo as comments.
just to try use:
$.getJSON("/ws.asmx/HelloWorld", function(data){
alert(data);
});
Check if you get the data back.
Use AJAX-Enabled Web Service
Make sure you have loaded the jquery.js file properly.
Does the service return a value? If not, it will just POST and not give you back anything, because there is no data to see...
If you want to watch for errors, you can add an error callback
$.ajax({
url: "/ws.asmx/HelloWorld"
, type: "POST"
, contentType: 'application/json; charset=utf-8'
, data: '{ FileName: "' + filename + '" }'
, dataType: 'json'
, success: function (data) {
}
, error: function (a, b, c) {
}
});
From jQuery:
error(jqXHR, textStatus, errorThrown)Function
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery
1.4.x, XMLHttpRequest) object, a string describing the type of error
that occurred and an optional
exception object, if one occurred.
Possible values for the second
argument (besides null) are "timeout",
"error", "abort", and "parsererror".
This is an Ajax Event. As of jQuery
1.5, the error setting can accept an array of functions. Each function will
be called in turn. Note: This handler
is not called for cross-domain script
and JSONP requests.
I read somewhere that the contentType header for POST must be:
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
and I use it blindly: it's always worked.
-- pete

Resources