ajax jquery an empty error callback on success server operation - ajax

I make an ajax call:
$.ajax({
url: 'Login.aspx/AuthenticateRegularUser',
type: 'POST',
contentType: 'application/json; charset=utf-8',
async: true,
dataType: "json",
data: '{ "emailAddress": "' + emailAddress + '","password": "' + password + '","verificationCode": "' + verificationCode + '" }',
success: function(Result) {
if (Result != "") {
var ClientResponse = JSON.parse(Result.d);
if (ClientResponse.Success) {
//DO SUCCESS
}
else {
//DO FAIL
}
}
},
error: function(xhr, textStatus, errorThrown) {
//DO ERROR
}
});
Most of the times everything is working fine, and I get success callback.
But one of my clients has a problem that sometimes the operation completed successfully on the server, but I get an error callback with an empty error.
jqXHR is empty, textStatus = "" and null errorThrown.
any idea why?

Could it be the different type of browser?? Could be an IE related issue. Maybe ask the client to use firefox instead.
Could be IE interpret javascript differently to firefox, I had similar sort of issue before at work. Microsoft always try to have its own standard for javascript, html, css. Also check data: '{ "emailAddress": "' + emailAddress + there are seems to have too many Quotation mark.
Thanks

Try, need to remove ' infront of data and syntax like as mentioned below
data: { "emailAddress": emailAddress, "password": password, "verificationCode": verificationCode },
instead of
data: '{ "emailAddress": "' + emailAddress + '","password": "' + password + '","verificationCode": "' + verificationCode + '" }',
Ref: http://api.jquery.com/jQuery.ajax/

Related

Formdata is null on backend (ajax, react, asp.net)?

I went through countless similar questions but I just don't get it.
It seems that the data I send is correct but the backend recieves empty formData.
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(IFormFile formFile)
{
//logic throws nullreference at formFile
}
Ajax:
console.log($('#fileTest')[0].files[0]);
var fd = new FormData();
fd.append('files', $('#fileTest')[0].files[0]);
$.ajax({
url: 'https://localhost:44348/api/user/UploadFiles',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);},
error: function (jQXHR, textStatus, errorThrown) {
console.log("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
The console.log result:
So I'm completly stuck. Can anyone suggest something I can try? Thank you very much in advance.

How do you make an Ajax call to Google Drive API?

My code can get an auth2.0 token...but the examples I've found don't show the final piece of taking a GET, provided here, and turning it into a working request.
Here is the specific URL from that link:
GET https://www.googleapis.com/drive/v3/files/fileId
Here is my AJAX call with the attempt at getting the token (that works) into a hardcoded fileId that I know my Google account has access to.
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer" + token);
},
// url: "https://www.googleapis.com/drive/v2/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI/permissions",
url: "https://www.googleapis.com/drive/v3/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI",
dataType: 'application/json',
processData: true,
success: function(msg) {
console.log('Got File Metadata: ' + msg) + console.log(msg);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Error: ' + errorThrown + ' / ' + textStatus) + console.log(jqXHR);
}
});
I don't understand how to include the token and the pages and pages of Google documentation do not include any examples of going this route.
I get "invalid credential" errors in the server response.
I don't want to use GAPI because I ran into invalid cookie issues running locally and my code is in a Chrome Extension and it isn't clear whether that approach will work there.
Thank you for any help or direction.
In your code, this line:
request.setRequestHeader("Authorization", "Bearer" + token);
You should have a space after Bearer
request.setRequestHeader("Authorization", "Bearer " + token);

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...

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

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