I have ajax connection with controller
function changeEmail() {
$.ajax({
...
contentType: "application/json",
dataType: "json",
...
error: function (error) {
var obj = error.responseText;
console.log('Error: ' + obj);
console.log('Obj length: ' + obj.fieldErrors.length);
}
});
}
Which in case of error returns a list of errors in json.
However, he is not able to refer to this list.
https://zapodaj.net/e6354b8c71f4c.png.html
I do not know, for example, how to refer to the first element of a list to the
message
variable
Depending on the content-type response from your server, the default response type is probably text/html or some other incorrect content-type.
You have two ways to fix this.
First, you can set obj = JSON.parse(error.responseText)
or, you can make sure that the server sets the correct content-type on errors as well.
Related
I have the following JavaScript:
var ids = [
"ed4bbe0e-d318-e811-a95f-000d3a11f5ee",
"386c9468-d11b-e811-a95d-000d3a11ec14",
"2913f317-991d-e811-a95d-000d3a11ec14"
];
$.ajax({
method: 'POST',
url: `/Jobs?handler=CreateJobsInQBO`,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
// contentType: 'application/json',
data: { jobIds: ids }
})
POSTing to the Razor Page handler below
public async Task<JsonResult> OnPostCreateJobsInQBO(IEnumerable<string> jobIds) {
Result<List<Job>> result;
if (jobIds == null || !jobIds.Any()) {
result = "No jobs were submitted.";
} else {
result = await DoStuffAsync(jobIds);
}
return new JsonResult(result);
}
This works without issue.
The problem is that when my JavaScript array is large, roughly 3000 items, I get null for the incoming handler parameter value. I've tried setting the ajax contentType to application/json and also using JSON.stringify on the object before it's sent, but they don't seem to make a difference. I also tried setting [FormBody] on the parameter in the handler function, but again, it didn't work.
I know I'm missing something simple here. I just need a way to POST an array of string to a handler method that has roughly around 5000 items. Preferably without using the application/x-www-form-urlencoded content type as I think that is what's causing the large array to not work.
The default value of ValueCountLimit is 1024. It is a limit for the number of form entries to allow.
If the value count exceed 1024, you should increase it in Startup.cs
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
});
I'm trying to remove the value of a custom field on an asana task via a PUT request.
Based on the original json data I sent over to create the task with a custom field value and the documentation here this is my best guess for how this should look:
let data = {custom_fields: { ASANA_CUSTOM_FIELD_ID_NUMBER: null }}; //struggling here
updateTask(ASANA_TASK_ID_NUMBER, data);
function updateTask(id, data) {
return put(`https://app.asana.com/api/1.0/tasks/${ASANA_TASK_ID_NUMBER}`, data);
}
function put(url, data) {
return makeRequest({
"url": url,
"headers": {"Authorization": "Bearer " + accessCode()},
"type": "PUT",
"data": data
})
}
But I get the error:
status:400 Bad request
custom_fields: Value cannot be an array: []
Which seems verbose enough to solve except I've tried every format i can come up with and I've had no luck working it out. I know that the put function works fine for updating other fields for a task and I see the same error with an actual number other than null.
You will need to send your content in JSON rather than urlencoded data. This is a bit of a bug in Asana API in my opinion. They say that they support form-encoded content however it doesn't like it when you try to send an object as it thinks it's an array.
I'm not sure why, but setting custom fields seems to be different from the rest of the API requests.
Here is some code that works for setting it, you can probably figure out how to apply this to whatever language you're using:
function SetCustomField(taskId, fieldId, value) {
// not sure why, but to set the custom task you have to tell it your content type is json,
// then send json as a string instead of letting it serialize it for you
var headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer API-KEY'
};
var formData = '{"data": { "custom_fields": { "' + fieldId + '": ' + value + '} } }';
var options = {
'method': 'put',
'headers': headers,
'payload': formData
};
var response = UrlFetchApp.fetch('https://app.asana.com/api/1.0/tasks/' + taskId, options);
//Logger.log(response.getContentText());
}
I'm a complete newby to JS. Trying to use SharePoint REST API to display a link list in a footer. Keep getting this error no matter what I do. It is for this line LoadFooterLinks(results.d.results);
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
LoadFooterLinks(results.d.results);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}
A few things:
How do you know you have an "error"?
Is is a Javascript Exception?
WHAT IS the error or Exception?
How do you know the error isn't with your LoadFooterLinks() function?
Most likely your results are NOT what you are expecting. You're obviously:
Successfully making a connection and request
But, you can't be sure what's coming back. It could be:
empty string
null
malformed
Hitting F12 in most browsers will bring up that browser's Developer mode/built-in JS console
My code changes below should help you debug by outputting to the console for you.
Things to NOTE about the code changes:
The difference between:
catching a JavaScript runtime exception/error using try-catch vs.
outputting the string variable arbitrarily named "error" in the failure callback method of the $.ajax object
Print an exception to to the console doesn't require console.err()
If you want to show a string as an error in the console use console.err(), not console.log.
Null is an object, not a datatype or primitive like the other ones in JavaScript. For Example,
boolean
string
undefined
number
New Code
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl +
"/_api/lists/getbytitle('Footer Links')/items/?
$orderby=Display_x0020_on_x0020_Homepage"
;
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
if (!results) { // should handle null and empty strings
try{
LoadFooterLinks(results.d.results);
}
catch (e){ // catch any JavaScript runtime exception (error)
console.log(e); // print the error to the console
// (hit F12 in most browsers to see
// the console BEFORE you refresh
// the page to run your code)
}
}
else {
var msg = "The 'results' variable is ";
var varType = typeof(results);
if (varType == "object") {
msg += "NULL";
}
else {
msg += varType;
}
}
},
error: function (error) {
// this 'error' variable can be named
// anything you'd like and is a string
// description of the AJAX error.
// This description comes from $.ajax -
// which is part of jQuery (a JS library).
// This "error" is not a native JS
// exception; therefore, you wouldn't
// use a TRY-CATCH. Also, since it's
// only a string, if you want to show it
// as an error in the console, you should
// use `console.err`, not `console.log`.
console.err("Error in getting List: (0)", error);
}
});
}
What you are basically doing is making a request to the "/_api/lists/getbytitle" method.
When that method returns a response, it will do so as an object named "results", as you can see under the "success" callback.
What you are doing afterwards is reading a property called "d" and within "d" you are trying to obtain the value of property called "results".
What the error is saying is that "d" is undefined therefore it cannot retrieve the value of "results" from "d".
I suggest you check what is inside the object "results" of the success callback.
For SharePoint API result, you would need to parse the JSON response to convert it to Javascript object. I've modified your code a bit to make it work in this case.
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (response) {
var svcData = JSON.parse(response.data).d.results;
LoadFooterLinks(svcData);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}
I have a json array created by javascript and need to post it to a php file in order to save the data into the database.
var myArray = [{
"picture":"picture1.jpg",
"picture_comment":"some comment about picture1",
"pictureid":16,
"u0id":80,
"u1id":82,
"u2id":78,
"u3id":79,
"u4id":81,
"param0": "60f3f",
"param1":"48dd2",
"param2":"4f2f7",
"param3":"8d101",
"param4":"5efcc",
"active":false,
"dutyid":1256,
"t":0
},
{
"picture":"picture2.jpg",
"picture_comment":"some comment about picture2",
"pictureid":160,
"u0id":18,
"u1id":48,
"u2id":70,
"u3id":95,
"u4id":74,
"param0": "1123f",
"param1":"48d13",
"param2":"595f7",
"param3":"78ad8",
"param4":"4efdc",
"active":false,
"dutyid":125,
"t":4
}
//goes like this about more than 20 times.
;
I have tried to post it using jQuery.ajax but I was not successful.
$.ajax({
type: "POST",
url: "goDoMyWork.php",
data: myArray,
dataType: "json",
success: function(){
alert("Done! You'll be redirecting now.");
window.location.href = "/index.php";
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert("Fail!");
}
});
I have to insert some of the data into one table and some of them into another table.
I have got the following error using:
alert(jqXHR + '-' + textStatus + '-' + errorThrown);
[object Object]-parsererror-SyntaxError: JSON.parse: unexpected character
Try changing data: myArray to data: {mydata : myArray}. Passing your array directly causes jQuery to pass it in an odd format. http://api.jquery.com/jQuery.param/
JSON.parse is the function that transforms text in json-format into a JavaScript object. What you seem to be wanting to do is throw some data at the server, where the server will handle it further.
What you are actually doing is setting the dataType to json. In the documentation you can read that this is the data-type you are expecting to get back from the server. jQuery will therefor throw the data it gets back from the server through JSON.parse, but apparently the data is not a well-formed json-string. Removing the dataType from your request will fix this, as the data will most likely not be parsed. Therefor, whatever gets returned will be in the form of a string.
Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.
My project is in MVC3 and I'm using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.
Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)
#{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
#Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
Javascript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
The above code successfully calls the MVC method and returns:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
But jquery fires the error event for the $.ajax() method saying "parsererror".
I recently encountered this problem and stumbled upon this question.
I resolved it with a much easier way.
Method One
You can either remove the dataType: 'json' property from the object literal...
Method Two
Or you can do what #Sagiv was saying by returning your data as Json.
The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.
So if you remove the dataType: json property, it will not try to parse it as Json.
With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.
See the answer by #david-east for the correct way to handle the issue
This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.
I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete event and then checking the status value. e.g:
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
You have specified the ajax call response dataType as:
'json'
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
'text'
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
the problem is that your controller returning string or other object that can't be parsed.
the ajax call expected to get Json in return. try to return JsonResult in the controller like that:
public JsonResult YourAction()
{
...return Json(YourReturnObject);
}
hope it helps :)
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
Your JSON data might be wrong. http://jsonformatter.curiousconcept.com/ to validate it.
Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.
I don't know if this is still actual but problem was with Encoding. Changing to ANSI resolved the problem for me.
If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false.
As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.
$.ajax({
url: '/Test/Something/',
type: 'GET',
dataType: 'json',
cache: false,
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
you should remove the dataType: "json". Then see the magic... the reason of doing such thing is that you are converting json object to simple string.. so json parser is not able to parse that string due to not being a json object.
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
incase of Get operation from web .net mvc/api, make sure you are allow get
return Json(data,JsonRequestBehavior.AllowGet);
If you don't want to remove/change dataType: json, you can override jQuery's strict parsing by defining a custom converter:
$.ajax({
// We're expecting a JSON response...
dataType: 'json',
// ...but we need to override jQuery's strict JSON parsing
converters: {
'text json': function(result) {
try {
// First try to use native browser parsing
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
return JSON.parse(result);
} else {
// Fallback to jQuery's parser
return $.parseJSON(result);
}
} catch (e) {
// Whatever you want as your alternative behavior, goes here.
// In this example, we send a warning to the console and return
// an empty JS object.
console.log("Warning: Could not parse expected JSON response.");
return {};
}
}
},
...
Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)
With this custom converter, .done()/success will be triggered as long as the request was otherwise successful (1xx or 2xx response code).
I was also getting "Request return with error:parsererror." in the javascript console.
In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
I have encountered such error but after modifying my response before sending it to the client it worked fine.
//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response); // Sending to client
//Client side
success: function(res, status) {
response = JSON.parse(res); // Getting as expected
//Do something
}
I had the same problem, turned out my web.config was not the same with my teammates.
So please check your web.config.
Hope this helps someone.
I ran into the same issue. What I found to solve my issue was to make sure to use double quotes instead of single quotes.
echo "{'error':'Sorry, your file is too large. (Keep it under 2MB)'}";
-to-
echo '{"error":"Sorry, your file is too large. (Keep it under 2MB)"}';
The problem
window.JSON.parse raises an error in $.parseJSON function.
<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>
My solution
Overloading JQuery using requirejs tool.
<pre>
define(['jquery', 'jquery.overload'], function() {
//Loading jquery.overload
});
</pre>
jquery.overload.js file content
<pre>
define(['jquery'],function ($) {
$.parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
/** THIS RAISES Parsing ERROR
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
**/
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "#" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
$.error( "Invalid JSON: " + data );
}
return $;
});
</pre>