Ajax call returns undefined data - javascript

I have an ajax call that requests data from an MVC controller method.
I am returning a Json result from the controller.
Ajax request completes, but the data returned is undefined.Ajax Call
var param = {
"username": uname,
"password": pass
};
var serviceURL = "/Account/CheckUser";
var req = $.ajax({
url: serviceURL,
type: "POST",
data: JSON.stringify(param),
contentType: "application/json",
complete: successFunc,
error: errorFunc
});
function successFunc(data) {
if (data.exists == true) {
console.log("Completed : " + data.exists);
} else {
console.log("Failed : " + data.exists);
}
}
Controller Method
[HttpPost]
public JsonResult CheckUser(string uname, string pass)
{
Boolean cont = true;
return Json(new { exists = cont });
}
Can anyone tell me why exists returns as undefined? UPDATE
As suggested below, I wrote the data to the console, and it seems it's returning an empty string. So I guess the question should be more 'Why is the data returning empty?

The function you specify via the complete option doesn't receive the data (for good reason: it's called even if there is no data, because there was an error). Change complete: to success:.
var req = $.ajax({
url: serviceURL,
type: "POST",
data: JSON.stringify(param),
contentType: "application/json",
success: successFunc, // <=== Here
error: errorFunc
});

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);
}
});

How to send a JavaScript object on the server side (ASP NET MVC)?

Below is the relevant code (JS+jQuery on the client side):
function getuser(username, password) {
var user = new Object();
user.constructor();
user.username = username;
user.password = password;
//....
$("#a1").click(function () {
var u = getuser($("#username").val(), $("#password").val());
if (u == false) {
alert("error");
} else {
//....
}
});
}
The question is how to send var u to a session on the server side?
You can use ajax to accomplish this. Something like:
$.ajax({
url: "/Controller/Action/",
data: {
u: u
},
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
//handle response from server
}
});
Then have a controller action to receive the data:
[HttpPost]
public ActionResult Action(string u)
{
try
{
//do work
}
catch (Exception ex)
{
//handle exceptions
}
}
Note that /controller/action will be specific to where youre posting the data to in your project
See the documentation
For example:
If you just want to do a simple post the following may suit your needs:
var user = getUser(username, password);
$.post(yourserverurl, user, function(response){console.log("iam a response from the server")});
As the documentation says:
This is a shorthand to the equivalent Ajax function:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So In your example:
$.ajax({
type: "POST",
url: "/mycontroller/myaction",
data: {user: getUser(username, password)},
success: function(responseFromServer){//handleResponseHere},
error: function(xhr){//handleyourerrorsHere}
dataType: yourdatatype
});

Handing value into Success function from AJAX Call

G'day all,
I'm trying to pass a value through to a Success var from the original AJAX call.
Here's some code :
function isJobComplete(jobGUID) {
var data = { "pJobGUID": jobGUID };
var url = '/DataService.asmx/isJobComplete';
var success = function (response, jobGUID) {
if (response.d) {
//The job is complete. Update to complete
setJobComplete(jobGUID);
}
};
var error = function (response) {
jAlert('isJobComplete failed.\n' + response.d);
};
sendAjax(data, url, success, error);
}
function sendAjax(data, url, success, error) {
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: success,
error: error || function (response) {
jAlert(response.d);
}
});
}
When the isJobComplete function runs, it has the correct value for jobGUID on the first pass through, but on the return to Success after the AJAX call, jobGUID changes to the word "success", with the double quotes.
How can I pass through that jobGUID to the Success function so I can use it to do more work depending on the AJAX response?
Thanks in advance....

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.

pass a object list view to controller with Ajax function in Javascript

I have a list object. I want to pass my list view to controller with Ajax function My code like :
function Save()
{
debugger;
if(!ValidateInput()) return;
var oRecipe=RefreshObject();
var oRecipeDetails=$('#tblRecipeDetail').datagrid('getRows');
var postData = $.toJSON(oRecipe);
var mydetailobj= $.toJSON(oRecipeDetails);
// postData="Hello world!!!!!!! Faruk";
//return;
$.ajax({
type: "GET",
dataType: "json",
url: '/Recipe/Save',
data: { myjsondata : postData, jsondetailobject : mydetailobj},
contentType: "application/json; charset=utf-8",
success: function (data) {
debugger;
oRecipe = jQuery.parseJSON(data);
if (oRecipe.ErrorMessage == '' || oRecipe.ErrorMessage == null) {
alert("Data Saved sucessfully");
window.returnValue = oRecipe;
window.close();
}
else {
alert(oRecipe.ErrorMessage);
}
},
error: function (xhr, status, error) {
alert(error);
}
});
}
Normally my code run successfully if my list length <=3/4 but when my list length >4 here a problem arise. I could not find out what is bug? please any one suggest me
Note : Here i try to pass by list object convert to JSON data
Why type "GET"? It is obvious that you want to post your data back to the controller. Change it to "POST" and try.
$.ajax({
type: "POST",
dataType: "json",
...

Categories