this.navCtrl is undefined after ajax success call - ajax

Hello I am struggling to redirect the landing page after successful login to ionic3 apps. It always shows error: ERROR TypeError: "this.navCtrl is undefined"
doLogin(){
$.ajax({
type: 'get',
url: 'http://my_server_ip_address/php/login.php?u='+this.UserInfoForm.username+'&p='+this.UserInfoForm.password,
success: function (res) {
window.localStorage['userInfo'] = JSON.stringify(res);
this.navCtrl.setRoot('clientDashboard');
},
error:function(){
this.navCtrl.setRoot('LoginPage');
}
});
}
my constructor:
constructor(public navCtrl: NavController,
public navParams: NavParams,
private formBuilder: FormBuilder,
private menu: MenuController) {
this.menu.enable(true); // Enable sidemenu
}

Related

Razor Pages PageModel binding for GET with AJAX

I am having trouble getting binding to work with a specific set of circumstances. I am using Razor Pages with ASP.NET Core 3.1 to act like a controller for servicing AJAX calls. I have already added the anti-forgery token to the Startup.cs:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
My AJAX calls include the anti-forgery in the calls and look like:
function getTankConfig(tankId) {
var json = { id: tankId };
$.ajax({
cache: false,
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/Tank/Config",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(json),
success: getTankConfigSuccess
});
}
function getTankConfigSuccess(data) {
if (data !== null) {
// do stuff with data
}
}
I have tried about every combination of binding technique. Using the parameter normally, adding [FromBody], adding a public property and giving it the [BindProperty] attribute, using [BindProperty(SupportsGet = true)]. It seems like it was so simple when using a controller to do this, but I am not finding the magic for making it work with Razor Pages and PageModels.
Here is the simplified version of my PageModel class:
public class TankConfigModel : PageModel
{
public JsonResult OnGet(int id)
{
TankConfigViewModel config = new TankConfigViewModel();
config.Id = id;
return new JsonResult(config);
}
}
Any help or guidance would be greatly appreciated. Thanks.
You have to add this to your razor page
#page "{id}"
and fix ajax
$.ajax({
type: "GET",
url: "/Tank/Config/"+tankId,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (result) {
getTankConfigSuccess(result)
},
error: function (jqXHR) {
}
});

sending POST request to Controller action works in IE not in Chrome

Action code is:
//tickets is null in chrome but has value in IE
public async Task<IActionResult> ChangeStatus(string tickets)
{
//Code goes here
}
ajax call
var selectTickets = '"ticket1","ticket2"'
$.ajax
({
type: 'post',
url: "/SkyBusTickets/ChangeStatus/",
data: {'tickets': selectTickets},
success: unexpiredTicketsBulkStatusChangeSuccess,
failure: unexpiredTicketsBulkStatusChangeError
});
In chrome it gives an error in console
jquery.js:9536 POST http://localhost:54656/SkyBusTickets/ChangeStatus/
500 (Internal Server Error)
what needs to be done to make it work in both browsers?
EDIT
If I change the action method to the below one it will stop working in IE too
//tickets is null in both chrome & IE
public async Task<IActionResult> ChangeStatus([FromBody]string tickets)
{
//Code goes here
}
Check this, it worked for me
//ajax side
$(document).ready(function () {
var selectTickets = '"ticket1","ticket2"'
$.ajax
({
type: 'post',
url: "api/Test/ChangeStatus",
dataType: 'json',
data: { "": selectTickets },
success: function () {
},
failure: function () {
}
});
});
In Controller part
[HttpPost]
public string ChangeStatus([FromBody]string tickets)
{
return "sdfdf";
}
You can refer this link
http://www.c-sharpcorner.com/UploadFile/dacca2/web-api-with-ajax-understand-formbody-and-formuri-attribute/

Parameters not populating with Ajax Call

This is my controller
[HttpPost]
public bool Sync(int? id, string name)
{
throw new NotImplementedException();
}
Here is my ajax request call that I am trying to make to this controller:
<script type="text/javascript">
var buttonClicked = document.getElementById("syncLegacy");
buttonClicked.addEventListener('click', function () { syncLegacyMake(); }, false);
function syncLegacyMake() {
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: JSON.stringify({
id: $("#Id").val(),
name: $("#Name").val()
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function () {
alert("error");
}
});
}
The controller gets hit however there are no values to the parameters. The values are both null.
When I look at the call itself on chrome console, the values are populated as these under Request Payload in the headers:
{id: "01", name: "Titan"}
id
:
"01"
name
:
"Titan"
Could anyone point out what I am doing wrong here? I have been able to do the same in .net 4.6.1 framework so not sure if framework changed has caused this?
have you tried the following things:
Using a Dto instead of separate simple types:
public class SyncDto
{
public int? Id {get;set;}
public string Name {get;set;}
}
// Controller action:
[HttpPost]
public bool Sync(SyncDto input)
{
throw new NotImplementedException();
}
Make Jquery stringify itself
Let jquery figure your ajax call out itself:
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: {
id: $("#Id").val(),
name: $("#Name").val()
}
});

I can only make MVC 6 Sessions work when using the browser address bar

Setup:
So I have two visual studio instances running.
1) Backend: MVC 6 Application with a MVC controller called homeController
2) Frontend: Website project. HTML.
I didn't build it with the traditional Views in mvc, but a standalone HTML webpage, using the MVC backend for data. - I like having them separate.
Test:
So I wanted to use sessions for the first time in MVC 6 and followed this guide.
First tests went fine, as I didn't bother to write the html and ajax, I just called the mvc from the address bar like this:
http://localhost:55043/home/setsession
The code behind it is:
[HttpGet]
public string SetSession()
{
string sessionId = "1";
HttpContext.Session.SetString(sessionId, "myvalue");
return sessionId;
}
And then:
http://localhost:55043/home/getsession?sessionId=1
The code behind it is:
[HttpGet]
public string GetSession(string sessionId)
{
string value = HttpContext.Session.GetString(sessionId);
return "session value is: " + value;
}
It gave my value back correctly.
Problem:
But when I wrote the website and its calles the same methods, then its not remembering the value set in the second call.
My code is like this:
$.ajax({
url: url + "/home/SetSession",
type: 'GET',
async: true,
crossDomain: true,
cache: true,
success: function (data) {
alert("finito - Sessionid: " + data);
$.ajax({
url: url + "/home/GetSession",
data: {
sessionId: data,
},
type: 'GET',
async: true,
crossDomain: true,
cache: true,
success: function (data) {
alert(data);
},
error: function (x, t, m) {
alert("failed");
}
});
},
error: function (x, t, m) {
alert("failed);
}
});
So why is it not working for my website? What is the difference?
Some of my Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCors();
services.AddCaching();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.CookieName = ".BrunataBooking";
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseSession();
app.UseCors(builder =>
{
builder.WithOrigins("*")
.WithMethods("GET", "POST")
.AllowAnyHeader();
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Start}/{id?}");
});
}

Ajax post can't find action controller

I'm writing a simple web app that allows users to login via facebook. When using the javascript sdk, I'm able to retrieve the proper credentials, but my ajax post is unable to find the mvc action to process the information.
Here's the js code:
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
var credentials = { uid: response.authResponse.userID, accessToken: response.authResponse.accessToken };
SubmitLogin(credentials);
}
});
function SubmitLogin(credentials) {
alert("Creds: " + credentials.uid + ":::" + credentials.accessToken);
$.ajax({
type: "POST",
ContentType: 'application/json',
url: '#Url.Action("FacebookLogin","Home")',
data:JSON.stringify(credentials),
success: function () {
window.location("~/Views/Account/Home.cshtml");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
}
and the corresponding controller:
[HttpPost]
public JsonResult FacebookLogin(string uid, string accessToken)
{
Session["uid"] = uid;
Session["accessToken"] = accessToken;
return null;
}
The model used in the controller:
public class FBLoginModel
{
public string uid { get; set; }
public string accessToken { get; set; }
}
The alert in the js function shows the correct token, but my ajax post is unable to the action. When I remove the "[HttpPost]" above the controller, I can access the action, but all data I attempt to pass is null.
Any help would be greatly appreciated. Thanks.
use
$.ajax({
type: "POST",
ContentType: 'application/json',
url: '#Url.Action("FacebookLogin","Home")',
data:JSON.stringify(credentials),
success: function () {
window.location("~/Views/Account/Home.cshtml");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
Ther should be single quote in 'Url.Action()'
Yout Controller action should be like below.Because you are not passing model items
public JsonResult FacebookLogin(long uid,string accessToken)
{
Session["uid"] = uid;
Session["accessToken"] = accessToken;
return null; //Because you are not posting anything back
}
I somehow devised a solution... By writing out the url and adding a forward slash to my ajax call, somehow my ajax call can find my action.
$.ajax({
type: 'POST',
url: 'Home/FacebookLogin/',
data: {
'uid': response.authResponse.userID,
'accessToken': response.authResponse.accessToken
},
cache: false,
success: function (result) { },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});

Resources