I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:
[HttpPost]
public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
{
if (pwd == null || repeatpwd == null)
{
ViewBag.Error = "Insira os campos obrigatórios";
}
else
{
if (pwd == repeatpwd)
{
changePwd_Entidades(Session["ID"].ToString(),pwd);
return Json(true,JsonRequestBehavior.DenyGet);
}
else
{
ViewBag.Error = "As palavras chave precisam de ser iguais";
}
}
return Json(false, JsonRequestBehavior.DenyGet);
}
Script:
<script>
$('.alt-btn').on('click', function () {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home")?pwd=' +
$('#Info_pwd').val() + '&repeatpwd=' + $('#Info_repeatpwd').val(),
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
});
I think you are using incorrect id to get value of password field.
And instead of sending both password to code better approach would be just compare your both password values at client side and if they both are same then parse those values to code side other wise ask user to input same password .
That would be better to Send the data in the data parameter while you're using POST method
var data = JSON.stringify({
'pwd': $('#Info_pwd').val(),
'repeatpwd':$('#Info_repeatpwd').val()
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home"),
data: data,
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
This is for using POST method. If you want to use GET method than it would be fine to pass data in query string.
Related
I have an ajax call (GET) to a controller action to generate and return a url (JSON). When I run the code the ajax call goes but it never hits the controller action. I get a 500 error with no response text. I'm stumped. Below is my code, Thanks!
[HttpGet]
public ActionResult ViewOrderForm(int? id)
{
if (id == null || id == 0)
{
_logger.LogInformation("Order Id " + id + " does not exisit in the database. User is unable to view form.");
return NotFound("Order Id " + id + " does not exisit in the database.");
}
return Json(new
{
newUrl = Url.Action("ViewOrder", new { id = id })
}
);
}
function viewOrderForm(id) {
$.ajax({
url: siteURLS.ViewOrderForm,
method: "GET",
data: {
id: id
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
}).done(function (data) {
//alert(data.newUrl);
window.location.replace(data.newUrl);
});
}
Believe its type instead of method in ajax property
try this ajax,
$.ajax(
{
url: siteURLS.ViewOrderForm+"?id="+id,
type: 'GET',
dataType: 'json',
success: function (data) {
window.location.replace(data.newUrl);
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
});
Basically, I am trying to call controller from views using jQuery ajax but it's not calling controller.
What I have to do is passing my token value from registration page to controller so that I will use its value for user registration.
< script type = "text/javascript" >
document.getElementById('LoginWithAmazon').onclick = function() {
options = {
scope: 'profile'
};
amazon.Login.authorize(options,
function(response) {
if (response.error) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token) {
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: {
token: 'abc'
},
cache: false,
success: function(result) {
alert(result);
}
});
}
function receiveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].Data);
}
}
}
return false;
};
< /script>/
Here below is my controller code
public JsonResult ProfileInfo(string token) {
return Json("test", JsonRequestBehavior.AllowGet);
}
I need to pass the token value from registration page to my controller
Try to change this in the controller
return Json("test", JsonRequestBehavior.AllowGet);
into
enter code herereturn Json(new { value="test" }, JsonRequestBehavior.AllowGet);
and change your js to be like this
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: JSON.stringify({
token: 'abc'
}),
cache: false,
success: function(result) {
alert(result);
}
});
Finally, i have solved the problem.I am unable to call the account controller so i have used my home controller for this purpose.Here below is the code that i have used for calling controller :
<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
options = { scope : 'profile' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token)
{
var url = "/home/ProfileInfo?token=" + token;
var request = $.ajax({
url: url,
method: "GET",
dataType: "json"
});
request.done(function (msg) {
var data = [];
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
});
}
}
</script>
Purpose: The code written is suppose to save all the contents using Json and re direct to action.
Problem:
The current redirect using Json does not allow the redirection as suppose.
return new JsonResult { Data = new { status = status } };
The code is below for reference: Looking for suggestions:
View Code
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
window.location.href = d.Url;
//clear form
t = [];
d = [];
r = [];
$('#SN').val('');
$('#SA').val('');
$('#t').empty();
$('#d').empty();
$('#r').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
});
Controller
public JsonResult Save(SAVM O,)
{
bool status = false;
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
status = true;
}
else
{
status = false
}
return new JsonResult { Data = new { status = status } };
}
Here want to redirect like this:
return RedirectToAction("F", "SA");
but using JsonResult
Solution
View
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
window.location.href = d.Url;
})
} });
Controller
public JsonResult Save(SAVM O,)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
return Json(new { Url = "F/SA" });
}
You have a couple of options here, you decide which one you prefer based on your requirements.
Do not use AJAX. AJAX requests are meant for data required for the current page. You should use a synchronous request for the redirection.
Return the URL to which the client should redirect on the success event:
return Json(new { url = "/F/SA" });
And then:
success: function (d)
{
window.location.url = d.url;
}
Return the already rendered View and load it to the current page:
return View("some view...");
And then:
success: function (d)
{
$("#someElement").html(d);
}
I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...
I am using kendo ui and i dont want duplicate records in my database so what i am doing is using the .Save function of kendo grid to check the record and if exist then return false which is working fine but when i am returning return false then it is still saving the record.
function onSave(e) {
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax(
{
url: '/StudentTransaction/CheckRegistrationNumber',
type: "POST",
data: { 'RegisterNumber': currentValueForSend },
success: function (data) {
alert(data.CurrentRegNo);
if( data.CurrentRegNo.indexOf('true') >= 0){
alert("no duplicate records");
return false;;
}
}
});
}
i am also defining a global value to override the value but i am not able to override the value
function onSave(e) {
var status;
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax(
{
url: '/StudentTransaction/CheckRegistrationNumber',
type: "POST",
data: { 'RegisterNumber': currentValueForSend },
success: function (data) {
status = data.CurrentRegNo;
}
});
if (status.indexOf('true') >= 0)) {
e.preventDefault();
alert("Duplicates not allowed");
return false;
}
}
What i am doing wrong?
This is due to the async nature of these requests.
The sequence as described in your code is:
make the request
check if status is true
get the response
You need to use function callbacks to handle this properly. Try something like this:
function onSave (e){
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax({
url : '/StudentTransaction/CheckRegistrationNumber',
type : "POST",
data : { 'RegisterNumber': currentValueForSend },
success : afterSave
});
}
function afterSave (data){
var status = data.CurrentRegNo;
if (status.indexOf('true') >= 0)) {
e.preventDefault();
alert("Duplicates not allowed");
return false;
}
}