Ajax call does not work - javascript

$('#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.

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

Class's not supported for deserialization of an array

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

How to get the data value during Jquery Ajax calling?

I'm calling Ajax like below
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: '{ "jsondata":' + jsondata + ',"key":"' + getValue('id') + '"}',
success: function (data) {
callback(data);
},
error: function (error) {
callback(error.responseText);
}
});
I want to get the "Data" value at calling time because after the call the execution doesn't goes to the desired web method and the error is showing like
""Message":"Invalid web service call, missing value for parameter: \u0027obj\u0027..."
I have to track the the Ajax posting value during Ajax call and find out what is the problem with posting data.Is there any tricks to get the data value before Ajax calling?
Any help will be appreciated.
Edit: I'm sending the jsondata value like below
var jsondata = '{ "pagenumber":"' + pagenumber + '","sortColumn":"' + sortColumn + '","sortDirection":"' + sortDirection + '","rowPerPage":"' + rowPerPage + '"}';
Thanks.
I was just checking with below code -
please have a look. please check beforesend content
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/dummy',
dataType: "json",
data: '{dummy:"dummy"}',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error);
},
beforeSend: function(data,data1) {
console.log('before'+data1.data)
},
});
})
});
var path = "test_ajax.php";
var jsondata = "Testing123";
var test = "test";
var data = {jsondata : jsondata,key : test};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: data,
success: function (data) {
alert("success:"+data);
},
error: function (error) {
alert("failure"+error.responseText);
}
});

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

how to pass parameter to URL in javascript?

I need to pass the parameters to URL.I have posed the code.
How can I pass the username and password entered in the textbox to URL in my code.thanks for any help..
You should not send password in the URL.
If you want to pass some other details: Update these two lines as below:
data: {data1:$("input#data1").val(),data2:$("input#data2").val()},
url: "http://localhost:53179/hdfcmobile/hdfc.ashx",
if you want to pass a url parameter, the you want to use:
type: 'GET'
and also:
url: 'http://localhost:53179/hdfcmobile/hdfc.ashx
into the .ajax configs, using type:'POST' will post the fields into the headers instead of the url.
Try below code:
You can try your code in this pattern...
var sdate = $('#banners_startdate').val();
var edate = $('#banners_enddate').val();
if(sdate != '' && edate != ''){
$.ajax({
url: 'your url',
data: 'apiname=get_banner_stat_platform_sharing&var=bannerstats&sdate=' + sdate + '&edate=' + edate,
dataType: 'html',
success: function(data){
$('#bannerstats').html(data);
return false;
}
});
}
Where username and password can be fetch by id:
function ajaxcall(username,password)
{
jQuery.ajax({
type: "POST",
url: "Enter Url to pass",
data: {user: username, pass: password},
dataType: "html",
success: function(data) {
//write code what you want to do here
}
});
}
You can fetch the value on page by just $_POST['user'] and $_POST['pass'].

Categories