jQuery AJAX JSON object not working - javascript

I'm having some trouble with my AJAX request.
The problem is with the JSON object named html.
AJAX request:
$.ajax({
url : 'index',
type : 'POST',
dataType : 'json', // Makes no difference
data : {
method : 'saveModule',
html : content
},
success : function(i){
console.log(i);
}
})
I know it's about the html JSON object because if I remove it the request will succeed.
This is what it looks like with firebug's console.log();
the object is stored within [ ], is that normal?
[Object { name="Home", link="/home"}, Object { name="Work", link="/work", childs=[3]}, Object { name="Contact", link="/contact", childs=[2]}]
The childs are JSON objects as well.
Please help, it's driving me crazy!
The error I'm getting with the Web Console:
[11:58:47.215] uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://localhost/mcms/htdocs/templates/resources/js/jquery-1.6.3.min.js :: <TOP_LEVEL> :: line 5" data: no]
The content var is made from this:
var content = mcms.module.analyse(obj); // obj is a dom element, in this case a UL with sub ULs inside LIs
The function itself:
analyse : function (that) {
return $(that).children('li').map(function() {
var b = {
name: $(this).children('a').text(),
link: $(this).children('a').attr('href')
};
if ($(this).children('ul').size() > 0) {
b.childs = mcms.module.analyse($(this).children('ul'));
}
return b;
});
}

I've found the problem and fix!
The problem was that the .map() function returns an array around the JSON object.
So I made a JSON object with a counter around the map to capture it and return it :)
Thanks for helping everyone!
analyse : function (that) {
var b = {};
var x = 0;
$(that).children('li').map(function() {
b[x] = {
name: $(this).children('a').text(),
link: $(this).children('a').attr('href')
};
if ($(this).children('ul').size() > 0) {
b[x].childs = mcms.module.analyse($(this).children('ul'));
}
x++;
});
return b;
}

I'm not so sure about the method parameter. If that is the method you are looking to call, you can as well include that in your URL, right?

Well, your current call to $.ajax doesn't look exactly right. It should be something along the lines of:
$.ajax({
url : 'index',
type : 'POST',
data : <data to be sent>
dataType : <Default: Intelligent Guess (xml, json, script, or html)>
success : function(i){
console.log(i);
}
})
More info on the jQuery website: http://api.jquery.com/jQuery.ajax/
EDIT
Ok, I see you corrected the call. This looks better now. Where does content come from and what's in it before it is converted into a JSON object?
EDIT2
Well, I think this answer should be of help to you: Post Nested Object to Spring MVC controller using JSON

Related

jQuery ajax post Uncaught RangeError: Maximum call stack size exceeded

I have a problem with jQuery ajax.
I have javascript
<script type="text/javascript">
$(function() {
$('body').on("click", "#pager a", function(e) {
e.stopPropagation();
e.preventDefault();
var a = $(this);
var model = $('#searchForm').serialize();
$.ajax({
url: '/Product/Products',
type: 'POST',
data: {
model: model, page: a
},
success: function (data) {
alert('success');
$('#productsList').html(data);
}
});
});
});
</script>
This code produce error "Uncaught RangeError: Maximum call stack size exceeded" and I don't understand why. I have no trigger, I used preventDefault and stopPropagation, but I still have this error. Can anyone help me?
This error can also come if you are passing something in data which is not defined in that scope.
Another reason is passing in data with val() directly.
Instead of using var a = $(this) to get the page, use one hidden field and give page value to the field.
<input type="hidden" value="xyzpage" id="pageValue">
var pageVal = $("#pageValue").val();
data: {
model: model, page:pageVal
},
This will solve the issue I guess
I want to share my experience,
in my case, it was only a wrong parameter name and exactly the same error message :
instead of confID, I put the configID and got this error.
function openNameEditor() {
var confID = $("#configStatusList").attr("data-id");
debugger;
$.ajax({
url: '#Url.Action("GetModelNameToChange", "Admin")',
type: "GET",
dataType: "HTML",
data: { configID: configID},//Here, instead of confID, I put configID which doesn't exist in the function.
success: function (response) {
$("#name-editor").html(response);
},
error: function (er) {
alert(er.error);
}
});
}
You need to take off the var a = $(this);. I don't know what you try to achieve there but using a the jQuery wrapped clicked element as request data is a non-sense.
Endless loop can also cause this kind of error. View that you don't call same function inside function.
I ran into such a problem when parsing a large piece of JSON using jquery.tmpl.js. This error appears when handling large arrays with the concat() function. Here is a link to the problem: https://bugs.chromium.org/p/chromium/issues/detail?id=103583
The problem has not been solved since 2011. To solve it, I had to edit the jquery-3.3.1.js javascript library file. For those who want to repeat this decision, do the following: find the following line in the library file return concat.apply ([], ret); and replace it with the code below.
// Flatten any nested arrays
if ([].flat) return ret.flat();
var ret2 = [];
ret.forEach(function (i) {
if (i instanceof Array) {
i.forEach(function (i2) {
ret2.push(i2);
});
} else {
ret2.push(i);
}
});
return ret2;
// original code:
// return concat.apply([], ret);
// chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=103583
We check if there is a flat() function in the browser's arsenal, for example, it has a chrome browser, and if there is - simply merge the data arrays - nothing more is needed. If not, the browser will go a slower path, but at least there will be no error.

How can I send an object via Ajax from within a Javascript Class?

My question title may not be phrased well, sorry.
I want to create a Javascript class to simplify sending information to a php page.
I'm using the method described in this answer to create my class
This is what I have so far:
var ParseObject = Class.extend({
init: function(classname, id){
// required properties
this.classname=classname;
this.objects=[];
this.fields=[];
// optional properties
if(id && id != '') this.id='';
//this.command = command;
//this.callback='';
//this.parent=[];
//this.children=[];
//this.relation='';
},
set: function(field, value) {
if(field == 'classname') this.classname=value;
else if(field == 'callback') this.callback=value;
else if(field == 'command') this.command=value;
else this.fields.push(field, value);
},
addChild: function(obj){
this.children ? this.children.push(obj) : this.children= [obj];
},
addParent: function(linkedFieldName, parentClassName, parentId){
this.parent=[linkedFieldName, parentClassName, parentId];
},
addObject: function(obj){
this.objects.push(obj);
},
isRelatedBy: function(relation){
this.relation=relation;
},
send: function(){
var obj = this;
$.ajax({
type: "POST",
dataType: "json",
url: "php/parseFunctions.php",
data: {data:obj},
success: function(response) {
// do stuff
},
error: function(response) {
// do stuff
}
});
}
});
And here's how Im trying to use the class:
var testObject = new ParseObject('TestObject');
testObject.set('callback','testResopnse');
testObject.set('command','save');
testObject.set('title','New Title');
testObject.set('description','New Description');
testObject.set('stuff',['one','two','three']);
testObject.addParent(['parent', 'MeComment', 'kRh5xcpkhz']);
testObject.send();
Everything works as expected until I get to testObject.send();
What I expect is for the below object to get sent to my PHP page:
But instead, what I get is "Uncaught RangeError: Maximum call stack size exceeded"
Why does this happen, and how can I achieve the desired result?
Update:#
Per Quentin's suggestion, this got me sorted
var obj =$.parseJSON(JSON.stringify(this));
When you pass an object to data:, jQuery will call param on it.
That function includes this code:
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
That ends up calling all the functions in the object (including the constructor) in the context of window. I don't have the tuits to figure out all the effects of that, but it clearly isn't desirable and, based on the error message, leads to infinite recursion.
You have several options here:
Write an explicit function that extracts the data you care about from the object and presents as a simple data structure consisting only of the data types you can serialise with .
Serialise the object to JSON and then deserialise it to strip out all the functions before you pass it to param via data:
Serialise the object to JSON, pass that as a string to data:, set the request contentType: "application/json" and change the PHP to expect a JSON formatted request instead of a form formatted request.
(I don't know if this will work) change the way you construct the class to use Object.defineProperty() and mark all the functions so they are not enumerable. I suspect this approach would fail because the object is, itself a function.

Retrieving a JSON.parse() string from a server

I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression

POST using jQuery AJAX in HP servicemanager (HPSM)

I know this is a long shot, but I'm trying to make a POST with AJAX within the Javascript tool in HPSM. It's got very limited debugging capabilities so I'm stuck where it should be simple (or so I thought). From the syntax I've seen in other articles, calling that AJAX function should be right, but it doesn't seem to want to take it.
Thanks for any help
Here is the code I'm calling, and using jQuery library v1.11.2
var JSONdata = {
"eId": "xxx111",
"deviceToken": "111111111111",
"deviceType": "iphone",
"applicationName": "huds"
};
system.library.jQuery.ajax({
type: "POST",
url: 'http://place:11400/location/collaboration/notifications/register/',
data: JSONdata,
dataType: "json",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
alert(JSON.stringify(data));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
errors
Process panel calc.javascript in RAD format.cjavascript encountered error in line 5 (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Script <UNKNOWN> line 20: ERROR TypeError: system.library.jQuery.ajax is not a function at char 1
Script 'jQuery' line 925: ERROR TypeError: document has no properties at char 1
Unrecoverable error in application: se.call.process on panel call.rad.1
Unrecoverable error in application: cm.update.save on panel call.master.upd
Unrecoverable error in application: format.cjavascript on panel calc.javascript
I'm assuming you have a ScriptLibrary called jQuery in your HPSM, right?
Try with
lib.jQuery.ajax(...
instead of system.library, regards.
not sure if you have imported the jQuery as a ScriptLibrary, but I think it will not work, because the code inside the jQuery Library includes some lines of code which are not valid for the HPSM.
Anyway...
To call an external external RESTful Service, you can use the doHTTPRequest() function in your ScriptLibrary.
What it is, what parameters are needed etc. can be found in the Programming Guide:
http://86.48.81.222:6080/classic/Content/Resources/PDF/sm_programming_guide.pdf
See Page 266 ...
Here an short example how it should work (it calls the REST API from the HPSM to create a new incident:
var objConfig = {
"url" : "http://place:11400",
"path" : "/location/collaboration/notifications/register/",
"connect_timeout" : 30,
"read_timeout" : 30
};
var objPostData = {
"eId": "xxx111",
"deviceToken": "111111111111",
"deviceType": "iphone",
"applicationName": "huds"
};
createRecord( objPostData );
/**
* Create a new Incident with the RESTful API
*
* #param {Object} objRecord Object with all required fields
*
*/
function createRecord( objRecord ) {
var JSON = system.library.JSON.json();
var arrHeaders = [];
//Content Type application/json is required
//otherwise we will get an 501 error
var typeHeader = new Header();
typeHeader.name = "content-type";
typeHeader.value = "application/json";
var arrHeaders = new Array();
arrHeaders.push(typeHeader);
//build url for the request
//Default Action for POST is "create" so we don't need
//to add the action again
var cRequestUrl = objConfig.url+objConfig.path;
//convert the given object to an json string
cPostBody = system.library.JSON2.toJSON(objRecord);
try {
//lets run the the HTTP request
//HTTP Command - url to execute - http header - POST Body
var rcRequest = doHTTPRequest( "POST", cRequestUrl, arrHeaders, cPostBody, objConfig.connect_timeout, objConfig.read_timeout );
//convert response json string back to an object
var objResponse = JSON.parse(rcRequest);
print( objResponse.toSource() );
} catch( e ) {
//something goes wrong
//check also http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html
//to get the description of the given http response code like 401 etc.
//currently it's not possible (or i don't know how) to get the correct
//error response - for me it looks like that the HPSM has an filter
//which removes the response body if the response header is not 200
//if it's possible to use the reponse, we can use the same code
//as above JSON.parse() etc.
print("ERROR: \n"+e);
}
}
INFO1: Currently there is a limitation in the doHTTPRequest.
It can't handle the catch case correctly.
So even when there is an error, you will get the response as string.
And not the Object or whatever the response is.
INFO2: This example is based on my example to call the internal incident api.
I have modified it to your given data.
Code was created and tested successfully with HPSM 9.3+.
Hope this helps.
Greets
Marcus

jQuery returning "parsererror" for ajax request

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>

Categories