var url="service/signProcess.aspx";
//sets the important hidden field of the form by which server decides what to send
$('#hdnReqType2').val('sign87162');
var data=$("#frmLogin").serializeArray();
var success=function(rdata, textStatus, jqXHR) {
console.log(rdata);
};
var fail=function(jqXHR, textStatus, errorThrown) {
console.log("Error" + errorThrown + " " + textStatus);
}
$.post(url,data,success,"text").fail(fail);
I am using this in the console of the page 'http://fsa.citop.in/lnct/' opened in chrome(when login form of the page is empty) and got a JSON String as response.
I found out at https://api.jquery.com/serializeArray/ that serializeArray() returns an array of objects having name and value.
so when I used
var data=[{name :"txtLogId",value: ""},{name:"txtLogPass",value: ""},{name:"hdnReqType2",value: "sign87162"}];
which I thought to be equivalent object to object returned by $("#frmLogin").serializeArray() . Server gave me a HTML page in response.
I tried console.log(data) with both the version of data variable and couldn't find any difference. Please explain me whats the difference between both the version of data and what could be the correct equivalent object to serailizeArray().
The data argument in success callback is the response object (JSON).
Your data variable before success function is conflicting with data argument in success callback.
I suggest you change the name of the data variable or change the name of data argument in success function.
var url="service/signProcess.aspx";
//sets the important hidden field of the form by which server decides what to send
$('#hdnReqType2').val('sign87162');
var data=$("#frmLogin").serializeArray();
var success=function(dat_a, textStatus, jqXHR) {
console.log(dat_a);
};
var fail=function(jqXHR, textStatus, errorThrown) {
console.log("Error" + errorThrown + " " + textStatus);
};
$.post(url,data,success,"text").fail(fail);
Here in the above code I have changed data argument in success callback function to dat_a.
I have tried almost everyway here on stack overflow, but somehow I cannot read JSON string data returned from a success function call in jquery ajax. my success function receives following JSON string:
Object {
readyState = 4, responseText = "{"
Response ":200,"
Data ":"
6 ","
Message ":"
6 "}", status = 200, statusText: "OK"
}
This is my success callback:
success: function(response, msg, responseText) {
if (response.Response == 200) {
console.log("Data was submitted");
var obj = responseText;
console.log(typeof obj);
} else if (response.Response == 400) {
console.log("there was some error");
}
}
When success function is fired and checks for status code, it executes console.log("Data was submitted"); statement successfully, however, I am not able to access the "Data":"6" key/value pair.
So far I have tried doing this:
var obj = responseText;
console.log(obj.Data);
and
console.log(obj.data[1]);
and numerous other ways, but either it says "undefined" or gives and error. However, when I console.log(obj), in console it shows 'obj'. which means I am getting a JSON object.
Please note that I have also tried:
obj = jQuery.parseJSON(responseText);
which gives me an error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
What to do in this situation? I want to be able to extract the value of a key name "Data": and and assign its value ="6" to a variable.
The first parameter of the success callback is what you need, not the third. The first parameter will represent the body of the response as returned from the server. Also you don't need to be checking for anything different than 200 status code in a success callback. That's what the error callback is designed for because the success callback will never be fired if your server returns 400 status code.
So:
dataType: 'json',
success: function (response) {
console.log("Data was submitted");
console.log(response.Data);
},
error: function() {
console.log("there was some error");
}
The success callback is success: function(data, textStatus, jqXHR )
So the 1st, data will contain the data returned to the success function.
I have a collection of rest services, calling independently with postman they work fine. I call getList with jquery works great. When I do a POST to create a new object it works (as in the object gets created), but blows up getting the response which is the object that was just created with an id now.
$("#createEventSubmit").click(function(){
createEvent();
});
function createEvent(){
$.ajax({
url: context + "/api/v1/organizer/event",
contentType: 'application/json',
data: formToJSON(),
type: "POST",
dataType : "json",
success: function( json ) {
console.log(json);
setMessage("Event was created! " + json.id);
},
error: function( xhr, status, errorThrown ) {
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
setMessage("Sorry, your event was not created, please check your inputs.","ERROR");
},
complete: function( xhr, status ) {
console.log( "Status: " + status );
}
});
}
Nothing happens visually and nothing gets put to the console. The error on the app server is this:
18:17:47,193 INFO [com.herdcat.web.api.v1.orgnaizer.event.OrganizerEvent] (default task-48) New Event Created: 60947792-0076-42d6-91d2-3d4144a40f5a
18:17:47,195 ERROR [io.undertow.request] (default task-48) UT005023: Exception handling request to /hc/api/v1/organizer/event: javax.servlet.ServletException: org.jboss.resteasy.spi.UnhandledException: Response is committed, can't handle exception
at org.apache.shiro.web.servlet.AdviceFilter.cleanup(AdviceFilter.java:196) [shiro-web-1.2.3.jar:1.2.3]
Caused by: java.io.IOException: Broken pipe
at sun.nio.ch.FileDispatcherImpl.write0(Native Method) [rt.jar:1.7.0_51]
The weird thing is the GET jquery is set up exactly the same. Pretty green to jquery so any advice is good advice for me. AND the object does get created, it just can't seem to handle response.
Thanks in advance.
Hi i have a problem when comparing two strings. the problem is that when i compare the equality of status variable with "success" string literal it returns False, However when I check the value of the success via alert or console.log I get "success".
when I use status.valueOf() == "success" I get an error which says Can not call method 'valueOf' of undefined but when checking
// this is a callback function used in jQuery.post(url, data, callback)
this.callback = function(data, status, jqXHR) {
alert(status); // shows that status is equal to "success"
console.log("STATUS: " + status);
console.log("STATUS CONSTRUCTOR: " + status.constructor);
console.log("STATUS TYPE: " + (typeof status));
if(status.valueOf() === "success") {
var data = JSON.parse(data);
if(data.errors) {
this.success(data.message);
} else {
this.failure(data.message, data.errors);
}
} else {
alert("WTF");
}
};
UPDATE 2:
This is what i get after logging some attributes of the status:
>>>console.log("STATUS: " + status);
STATUS: success add_poll.js:34
>>>console.log("STATUS CONSTRUCTOR: " + status.constructor);
STATUS CONSTRUCTOR: function String() { [native code] } add_poll.js:35
>>>console.log("STATUS TYPE: " + (typeof status));
STATUS TYPE: string add_poll.js:36
STATUS: undefined add_poll.js:34
Uncaught TypeError: Cannot read property 'constructor' of undefined add_poll.js:35
(callback add_poll.js:35)
(callback add_poll.js:41)
(fire jquery.js:1037)
Can not call method 'valueOf' of undefined
The error message says, valueOf is called on undefined. It means that the status is undefined. So, you might want to drop the valueOf and simply do
if (status === "success") {
A better way of checking might be,
if(status.toLowerCase() === "success")
First check what you server code is returning, if it is ok, try this
if (status === "success")
or you can do this
if (data=== "success")
The method you are using for jQuery ajax is almost deprecated.
As already mentioned in comment, there is no need of using valueOf method with status
So, this should do
$.ajax({
url: 'url2ajax.php',
dataType: 'datatype returned by the url ajaxed maybe json',
data: {//list of key-value pairs to be send },
success: function( oData ) {
//call back to perform on a successful ajax.
//Data returned from ajaxed url available as argument, oData
},
error: function( ojQXhr, strStat, strErr ) {
//callback to perform on a failed ajax request
//jQuery XHR object, status string and error message available as argument
}
});
Refer to jQuery.ajax for details
I finally found the problem. The problem is that I defined the callback function as a property of an object this.callback = function(){...}; I changed it and defined a normal javascript function and it worked. Actually I don't know why? Anyone knows why I can't use an object method as a callback function for $.post(url, data, callback)?
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>