Class's not supported for deserialization of an array - javascript

I have this error(image):
My code:
function CheckLoginData() {
var user = [];
user.Email = $("#tbEmail").val();
user.Password = $("#tbPassword").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf=8",
url: "WS.asmx/CheckAccount",
data: "{user:" + JSON.stringify(user) + "}",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (request, status, error) {
alert("Erro : " + request.responseText);
}
});
}
Why this error is happening? I've tried to search deeply but without success

You assign an empty array to user
var user = [];
But then you treat it as an object by assigning fields to it, it confuses the serialiser.
You will need to declare user to be an object
var user = { Email: $("#tbEmail").val(), Password: $("#tbPassword").val() };

Related

JQuery ajax function sends the correct value.But RestController receives null

These codes are RestController of my spring boot project,
#RestController
#RequestMapping(value="/rest/user")
public class UserRestController {
#Autowired
private UserService userService;
#PostMapping("login")
public ResponseEntity<Boolean> authenticated(#RequestBody User user) {
System.out.println(user.getUsername() +":"+ user.getPassword()); //This line returns NULL password value
Boolean blogin = userService.authenticate(user.getUsername(), user.getPassword());
if(!blogin)
return new ResponseEntity<Boolean>(blogin, HttpStatus.NOT_ACCEPTABLE);
return new ResponseEntity<Boolean>(blogin, HttpStatus.OK);
}
}
And Below codes are JQuery ajax java-script codes.
function ajax_login_submit() {
var user = {
username: $("#username").val(),
password: $("#password").val()
};
console.log(user);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "rest/user/login",
data: JSON.stringify(user),
dataType: 'json',
success: function (data) {
var resultJson = JSON.stringify(data);
$('#helloUserDiv').html(resultJson);
console.log("SUCCESS : ", data);
alert(data);
},
error: function (e) {
var resultJson = e.responseText;
$('#helloUserDiv').html(resultJson);
console.log("ERROR : ", e);
}
});
}
console.log(user); of java script returns the correct value.
{"username":"joseph","password":"password"}
But in the RestController codes, password value is missing, "NULL".
The line System.out.println(user.getUsername() + ":" + user.getPassword()); returns strange value, "joseph:null"
Is it possible for JQuery ajax method not to transfer the json value to REST server? If I make some mistakes, kindly inform me how to send the json value to REST server correctly.
Try this:
$.ajax({
type: "POST",
contentType: "application/json",
url: "rest/user/login",
data: JSON.stringify({"username": $("#username").val(), "password": $("#password").val()}),
dataType: 'json',
success: function (data) {
var resultJson = JSON.stringify(data);
$('#helloUserDiv').html(resultJson);
console.log("SUCCESS : ", data);
alert(data);
},
error: function (e) {
var resultJson = e.responseText;
$('#helloUserDiv').html(resultJson);
console.log("ERROR : ", e);
}
});

Submission issue internal server error

I am trying to submit data through form as below which gives error:
echo 'The # here does not begin a comment.'
echo The \# here does not begin a comment.
But it wont give error, if we submit like below:
echo The # here does not begin a comment.
echo The # here does not begin a comment.
That is ,without single quotes and slash ,i am unable to submit data.
Code as below:
function AjaxCallOnClick(userName, email, commentText, blogID, commentHtml, onCommentEmailID) {
var parameters = "{'commentUserName':'" + userName + "','email':'" + email + "','commentText':'" + commentText + "','blogID':'" + blogID + "','commentHtml':'" + commentHtml + "','onCommentEmailID':'" + onCommentEmailID + "'}";
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/BlogService.asmx/GetShareStoryData")%>",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Your Comment was Saved");
var getCommentList = response.d;
var allComments = '';
$('#dvMainAndReplyCommentSection').html('');
$.each(getCommentList, function (index, comments) {
var comment = comments.HtmlComment;
allComments += comment;
});
if (allComments) {
$('#dvMainAndReplyCommentSection').html(allComments);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
failure: function (response) {
alert(response.responseText);
}
});
}
What is the work around for this?
I tried like this format var parameters = JSON.stringify({ commentUserName: userName, email: email, commentText: commentText, blogID: blogID, commentHtml: commentHtml, onCommentEmailID: onCommentEmailID }); and it's working fine for me.
Try it...Removes double quotes when saving object.
function AjaxCallOnClick(userName, email, commentText, blogID, commentHtml, onCommentEmailID) {
var parameters = JSON.stringify({'commentUserName': userName,'email': email,'commentText': commentText,'blogID': blogID,'commentHtml': commentHtml,'onCommentEmailID': onCommentEmailID});
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/BlogService.asmx/GetShareStoryData")%>",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Your Comment was Saved");
var res=JSON.parse(response);
var getCommentList = res.d;
var allComments = '';
$('#dvMainAndReplyCommentSection').html('');
$.each(getCommentList, function (index, comments) {
var comment = comments.HtmlComment;
allComments += comment;
});
if (allComments) {
$('#dvMainAndReplyCommentSection').html(allComments);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
failure: function (response) {
var res=JSON.parse(response);
alert(res.responseText);
}
});
}

Overwrite the Knockout object

I need to Overwrite the Knockout Object . But When I try this I got the Following Error. When the Page Load I called loadXMLFiles and It worked without any issue. after pressing a button when I try to overwrite the object I got following Error Uncaught TypeError: Cannot read property 'fromJS' of undefined in downloadFile Function. but in both Cases It's coming same object. Can Any one please help me on this???
var urlPath = window.location.pathname;
//var self = this;
$(function () {
ko.applyBindings(indexVM);
indexVM.loadXMLFiles();
});
var indexVM = {
XMLFiles: ko.observableArray([]),
loadXMLFiles: function () {
var self = this;
$.ajax({
type: "GET",
url: "../HotelBackEndProcess/UpdateDatabase/FillIndex",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.XMLFiles(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
},
DownloadFile: function () {
Id = this.Id;
var self = this;
$.ajax({
type: "GET",
url: "../HotelBackEndProcess/UpdateDatabase/DownloadFile",
contentType: "application/json; charset=utf-8",
data: { Id: Id },
dataType: "json",
success: function (data) {
ko.mapping.fromJS(XMLFiles, self.data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
};
You're probably missing the mapping plugin (which has to be downloaded separately):
See ko.mapping in GitHub.

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

I have the following controller method:
public JsonResult CreateGroup(String GroupName)
{
ApplicationUser user;
var userName = User.Identity.Name;
using (DAL.GDContext context = new DAL.GDContext())
{
user = context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null)
{
var group = new Group();
group.GroupName = GroupName;
group.Members.Add(user);
context.Groups.Add(group);
context.SaveChanges();
}
}
string result = userName;
return Json(result, JsonRequestBehavior.AllowGet);
}
with the following ajax call:
$(function () {
$('#CreateGroup').on("click", function () {
var groupName = $('#groupname').val();
if (groupName != '') {
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: JSON.stringify({ 'GroupName': groupName }),
dataType: "json",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
}
});
The CreateGroup function fails saying "Uncaught ReferenceError: data is not defined"
Do i have to use another Json request - type post - to get the username?
you can do the call without using JSON.stringify. Also your controller method has a cache attribute that may yield more control. Personally, I would use the controller cache control. You are probably getting a cached version of the controller call prior to returning data.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult CreateGroup(string GroupName)
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: { 'GroupName': groupName },
dataType: "json",
traditional: true,
success: function (data, status, xhr ) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
NOTE: Update success callback.

Ajax call does not work

$('#loginbtn').click(function() {
var userName = document.getElementById('uid').value;
var password = document.getElementById('pwd').value;
$.ajax({
type: "POST",
url: "/LoginNew.aspx/Authenticate",
data: "{ 'userName': '" + userName + "' ,'password': '" + password + "' }",
async: false;
contentType: "application/json; charset=utf-8",
dataType: "json",
success: a(),
error: function(e) {
alert(e.valueOf());
}
});
alert("test");
function a() {
window.location.href = "Login.aspx";
}
});
As I have accepted the answer its goes to the server side code authenticates user and control passes to "a" function but it does not display login.aspx page...Any clues?
it should be
$('#loginbtn').click(function() {
var userName = document.getElementById('uid').value;
var password = document.getElementById('pwd').value;
$.ajax({
type : "POST",
url : "/LoginNew.aspx/Authenticate",
data : {
userName: userName ,
password: password
},
async : false, // not ; need to use ,
contentType : "application/json; charset=utf-8",
dataType : "json",
success : a, // pass the callback reference, don't invoke it
error : function(e) {
alert(e.valueOf());
}
});
alert("test");
function a() {
window.location.href = "Login.aspx";
}
});
The JSON you are generating is invalid. Don't try generating JSON by hand, use an JSON library.
JSON.stringify({ userName: userName, password: password })
You are calling a() instead of assigning a as the success handler. Remove the () if you want to assign the function instead of its return value.

Categories