window.location.replace is always undefined - javascript

I have a ajax post that I need to redirect to redirect url on success.
In the browser debugger I do c the correct url but I'm always getting "MYURL/undefined".
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function(result) { //debug >result={urlOne:'https://localhost:7077'}
// alert('Successfully received Data ');
if (result.UrlOne !== undefined) {
window.location.replace(result.UrlOne);
} else {
window.location.replace(result.UrlTwo);
}
console.log(result);
},
error: function(error) {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
In my controller:
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")});
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") });

Pass the JsonSerializerOptions as a parameter when creating the Json object to make property's name case-sensitive during deserialization. The JsonSerializerOptions has PropertyNameCaseInsensitive property that by default set to false. This will prevent the Json serializer to change names to be camel-cased.
var options = new System.Text.Json.JsonSerializerOptions();
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")}, options);
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") }, options);
JsonSerializerOptions Class

Please check the return json from controller:
You will find that the key is urlOne instead of UrlOne.
Javascript is case sensitive, So you need to change your code like:
if (result.urlOne !== undefined) {
window.location.replace(result.urlOne);
} else {
window.location.replace(result.urlTwo);
}

Related

How to pass multiple file names from input type file to a web method

Hi ihave this input with type file with multiple select enabled.
i need to get the files from the file input and pass it to my webmethod but i'm getting none in my webmethod, i've read that prop return a list, i have this code in jquery
function post_RepAttach(){
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:$('#FileUpload1').prop("files")[0]
}
var files = $('#FileUpload1').prop("files")[0];
alert(files);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Create-OCAP.aspx/post_attachment_rep',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
var response = data;
if (typeof callback != 'undefined') {
//hideLoadingGif();
//callback(response);
}
},
error: function (xhr, status, error) {
//hideLoadingGif();
console.log(xhr, status, error);
}
});
}
i have try this $('#FileUpload1').prop("files") remove the [0] but still no luck
and here's my webMethod
[WebMethod]
public static string post_attachment_rep(string Ocap_no, List<string> file_Name)
{
OcapDataAccess ODA = new OcapDataAccess();
bool result;
result = ODA.insert_reports(HttpContext.Current.Request.MapPath("~/OCAP/files/Reports/" + file_Name.ToString()), Ocap_no);
if (result == true)
{
return "1";
}
else
{
return "0";
}
}
but the file_Name count is zero even if i selected files
how can i achive it.
Hope you understand what i mean
var fileNames = $.map( $('#FileUpload1').prop("files"), function(val) { return val.name; });
and params is :
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:fileNames }
}

Response string JavaScript undefined

I have a program written in angularjs. I'm receiving json data from server when online. I'm developing offline mode now..
I have the problem here but i dont know why i cant fix.
I saved json info to localStorage when program to offline get this json string.
service.js - For webservicecall
webServiceCallPost: function(data, action) {
console.log("data "+JSON.stringify(data));
console.log("action "+JSON.stringify(action));
var deferred = $q.defer();
if (navigator.connection.type != "none") {
return $.ajax({
type: "POST",
url: appConst.serviceUrl.service + action,
crossDomain: true,
dataType: "json",
data: data,
timeout: 2000000,
async: true,
success: function(response) {
localStorage.setItem(data + action, JSON.stringify(response));
deferred.resolve();
},
error: function(xhr, ajaxOptions, thrownError) {
$ionicLoading.hide();
if (xhr.status == 0) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else if (xhr.status == 404) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
}
},
beforeSend: function() {},
complete: function() {}
});
} else {
window.plugins.toast.showShortBottom($translate.instant("checkNetWorkConnection"));
$ionicLoading.hide();
var response1 = JSON.parse(JSON.stringify(localStorage.getItem(data + action)));
return $http.get('').then(function(response) {
return response1;
});
}
}
Controller.js - Retriveing response.
Services.webServiceCallPost('', appConst.services.get_menu_card).then(function(response) {
$ionicLoading.hide();
console.log("Response: " + JSON.stringify(response));
if (response[1].response.status == 1) {
if (response[0].data.menu.length > 0) {
var categoryResponse = [];
angular.forEach(response[0].data.menu, function(value, key) {
if (value.menu_image_name != '') {
var extraData = {
imageUrl: appConst.serviceUrl.menu_image_url + value.menu_image_name
}
}
else {
var extraData = {
imageUrl: 'img/screen.png'
};
}
angular.extend(value, extraData);
categoryResponse.push(value);
});
$rootScope.categories = globalMethods.getDashboardGridView(categoryResponse, 2);
}
if (response[0].data.addons.length > 0) {
$rootScope.totalAddons = [];
angular.forEach(response[0].data.addons, function(value, key) {
var extraData = {
"finalCost": value.price,
"quantity": 1,
imageUrl: appConst.serviceUrl.addon_image_url + value.addon_image
};
angular.extend(value, extraData);
$rootScope.totalAddons.push(value);
});
}
$scope.getSiteSettings();
}
$rootScope.dashboardHistoryId = $ionicHistory.currentHistoryId();
});
Console Output :
When i check from json pretty print its looking same.
Online Response : https://codepaste.net/op0boq
Cached Response : https://codepaste.net/y3bkd6
Problem:
TypeError: Cannot read property 'status' of undefined
When i want to get response1.response.status ok is getting.
But when i'm offline and i get cachedResponse1.response.status its retriving status is undefined. But exactly same data, why ?
if this code
var cachedResponse = JSON.parse(JSON.stringify(localStorage.getItem('' + appConst.services.get_menu_card)));
uses an asynchronous call
console.log("Cached Response: " + cachedResponse);
won't wait for it to finish and would print undefined
Thanks for answer to #PatrickEvans
Then you might have not returned the right thing... but also you shouldn't be doing JSON.parse(JSON.stringify(localStorage.getItem()) it should just be JSON.parse(localStorage.getItem()) localStorage items are already strings, stringifying it is going to mess up what you are trying to do
and
return $q.when(response1);

Web method return OK but fire fail function

here is my web method
[HttpGet]
public ActionResult EditEmp(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee Emp = db.Employees.Find(id);
if (Emp == null)
{
return HttpNotFound();
}
ViewBag.dept_id = new SelectList(db.Departments, "dept_id", "dept_name", Emp.dept_id);
return PartialView("_EditEmp", Emp);
}
and here is the ajax call
$.ajax({
type: "GET",
url: '/Employee/EditEmp',
data: { id: idp },
dataType: "json",
success: function (result) {
alert(result);
$('#editid').html(result);
},
error: function (result) {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
});
it gives me result.status =200 and result.statusText = OK but it fire Error Event
Please check that you are returning valid json or not, because you are setting
dataType: "json"
it evaluates the response as JSON and returns a JavaScript object. (...) The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
You may want to see this

Ajax call showing error cant debug

this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?

Refresh Index after redirecting to it from AJAX call

I have a situation where I am setting a user value and trying to reload the index page. This is only a sample page and I cannot user any kind of user controls, like ASP.NET. Each user is in the database and the role is retrieved from there. My index is this:
[HttpGet]
public ActionResult Index(long? id)
{
AdminModel admin = new AdminModel();
UserModel usermodel = new UserModel();
if (id != null)
{
admin.UserModel = usermodel;
admin.UserModel.UserId = id.ToString();
admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(admin.UserModel.UserId);
}
else
{
admin.UserModel = usermodel;
admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(currentUser);
}
return View(admin);
}
This works fine when first loaded. In the page I am setting values based upon the user role:
$(document).ready(function () {
debugger;
user = function () { return #Html.Raw(Json.Encode(Model)) }();
if (user.UserModel != null) {
if (user.UserModel.UserRole == 'ADMIN') {
$("#btnAdmin").show();
$("#btnTran").show();
$("#btnNew").show();
$("#btnAdjust").show();
$("#btnReports").show();
}
if (user.UserModel.UserRole == 'TRANS') {
$("#btnReports").show();
$("#btnTran").show();
}
if (user.UserModel.UserRole == 'REPORTS') {
$("#btnReports").show();
}
}
});
The AJAX call is this:
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("SetUser")',
data: { userid: ui.item.value },
success: function (data) {
if (data == null) {
}
else {
}
},
error: function (xhr) {
//var err = xhr.responseText;
//alert('error');
}
});
And the SetUser action:
[HttpPost]
public ActionResult SetUser(string userid)
{
return RedirectToAction("Index", new { id = Convert.ToInt64(userid) });
}
This works fine in that the Index method is fired with the chosen ID, but the page does not reload to be able to set the buttons. Any ideas?
It won't redirect because you're returning an action via an ajax call. The best thing to do here would be to return the userid as JSON, then do the redirect.
So the ajax success function would be:
success: function (data) {
if (data != null && data.UserID != null) {
location.href = '#(Url.Action("SetUser"))?userid=' + data.UserID;
}
else {
location.reload(); //something went wrong?
}
},
});
And your action would be:
[HttpPost]
public JsonResult SetUser(string userid)
{
return Json(new { UserID = Convert.ToInt64(userid) });
}
Do you need to make Ajax POST call? If not you can replace that code with
window.location.href = '#Url.Action("Index")' + '/' + ui.item.value
or
window.location.href = '#Url.Action("Index")' + '?id=' + ui.item.value
depending on your route mapping.

Categories