Can't sending data from View to Controller - javascript

can you help about that issue?
I am trying to pass my data to the controller. Below you can see my ajax code.
<script type="text/javascript">
$(document).on("click", "#login_button", function () {
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
if (userName !== "" && password !== "") {
$.ajax({
url: '/Home/Login',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {
'userName' : userName,
'password' : password
},
datatype: 'json',
success: function (data) {
}
})
}
else {
alert("Lütfen Alanları Doldurunuz.")
}
})
</script>
And my controller is like,
[HttpPost]
public ActionResult Login(string userName, string password)
{
return View();
}
I checked my data and it is not empty or null. How can I fix it?
Now I am getting this error =
jquery.min.js:4 POST http://localhost:59277/Home/Login 500 (Internal Server Error)
Thanks a lot.

I had the same problem today during a programming competition.
What solved it for me was using a different way of sending a GET request:
$.get("URL/to/send/request/to", function(data, status){
alert("Data: " + data + "\nStatus: " + status);//data is the actual response you get, while status is weather the request was successful
});
});
Hope it works for you too.

i thik you should use
url: 'http://stackoverflow.com/Home/Login',
instead of
Home/Login

i solve my problem changing the type of ajax as "GET" and changing my controller as "HttpGet" but when I do this for "POST" it didn't solve. Can anyone explain it to me?

$.ajax({
url: 'http://stackoverflow.com/Home/Login',
type: "POST",
dataType: 'json',
data: dataToPost,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("hi" + data);
}
});
i think it is work

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

failed 500 internal server error

I m getting Internal server error (500) making an AJAX request. I m not sure why the request is failing. Need help in this. Here is my code.
$('#LanguageId').on('change', function(){
var setValue =JSON.stringify( $('#LanguageId').val());
console.log(typeof(setValue));
$.ajax({
url: '/RootObjects/SaveLanguage',
type: 'POST',
dataType: 'json',
data:setValue ,
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});
})
and the controller's action
[HttpPost]
public ActionResult SaveLanguage(string LanguageId)
{
GlobalVariables.LangId = LanguageId.ToString();
return View("Index");
}
can't understand what is wrong
Change your ajax request like this:-
$('#LanguageId').on('change', function(){
var setValue =$('#LanguageId').val();
console.log(typeof(setValue));
$.ajax({
url: '/RootObjects/SaveLanguage',
type: 'POST',
dataType: 'json',
data:{'LanguageId':setValue} ,
success: function (data) {
}
});
})

Getting Pop up window to login with basic authentication using Ajax?

Here I am trying to access reed.co.uk rest webapi to fetch all related jobs, When I call the URL, its showing this popup window even though I am passing username and password. This is the alert message I am getting:
http://www.reed.co.uk is requesting your username and password.
WARNING: Your password will not be sent to the website you are
currently visiting!
Pls help me where i am doing wrong.
Here is the Ajax code
var username = "xxxxx xxxxxxxxxxxxxxx";
var password = "";
function getAuthorizationHeader(username, password) {
var authType;
var up = $.base64.encode(username + ":" + password);
authType = "Basic " + up;
console.log(authType);
return authType;
};
$.ajax({
type: "GET",
url: "http://www.reed.co.uk/api/1.0/search?keywords=Software Engineer&locationName=London&distanceFromLocation=50",
dataType: 'jsonp',
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', getAuthorizationHeader(username, password));
},
success: function (response) {
console.log(response);
}
});
I tried passing Authorization header like this also but still i am getting pop up window
headers: {
'Authorization': getAuthorizationHeader(username, password)
},
It looks like it is expecting Basic Authentication. Thus you need to supply it at url.
For example:
$.ajax({
type: "GET",
url: "http://"+username+":"+password+"#www.reed.co.uk/api/1.0/search?keywords=Software Engineer&locationName=London&distanceFromLocation=50",
dataType: 'jsonp',
async: false,
success: function (response) {
console.log(response);
}});

Ajax call returns undefined data

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

Categories