I send io to server with YUI and how to respond back to YUI?
Here is code :
var user = {
userName: username,
password: password,
customerId: customerId
};
var success = function (ioId, o) {
responseContent = Y.JSON.parse(o.responseText);
if (responseContent.code == 0) {
window.location = 'Home.jsp';
}
};
var failure = function (ioId, o) {
//do something
};
var cfg = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
sync: false,
data: user,
on: {
'success': success,
'failure': failure
}
};
new Y.IO().send("http://localhost:7778/web/LoginController", cfg);
Redirect not work and i decide to redirect by YUI. Thanks!!!
var success = function (ioId, o) {
responseContent = Y.JSON.parse(o.responseText);
if (responseContent.code == 0) {
window.location = 'Home.jsp';
}
//Like this?
responseDiv.innerHTML = responseContent.yourData;
};
Related
when i pass data to the first action its working fine and based on the return of that action i call another one with another ajax post request and pass the same data but the error message appears on console and nothing happens, note that if i don't pass data at all(not in the same nor the second query) both actions get called without problem but with no data passed enter image description here
those are the codes for the actions and the script(second)
[HttpPost]
public async Task<bool> Check(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
var testAuthResult = authResult;
return authResult.force;
}
[HttpPost]
public async Task<IActionResult> LoginV2(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
if (!authResult.result)
{
model.LoginRequest.Password = "";
TempData["Message"] = authResult.message;
return RedirectToAction("Index", "Login", model);
}
if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Trainings");
}
public IActionResult IndexV2()
{
return View();
}
and this is the script
#using System.Text.Encodings.Web
#using Microsoft.AspNetCore.Mvc.Localization
#using Microsoft.Extensions.Localization
#using UI
#inject IViewLocalizer Localizer
#inject IStringLocalizer<SharedResource> SharedLocalizer
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions {
private string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<script type="text/javascript" nonce="bGFsYWNvY29qYW1ib2xhbGF5ZWFhYWE=">
$(document).on("click", "#LoginFormSubmit",
function (e) {
setLoginCredentials();
})
function GetLoginCredentials() {
var login = document.getElementById("txtUsername2").value;
var pwd = document.getElementById("Password").value;
var data = {
'login': login,
'password': pwd
};
//var jData = JSON.stringify({ login: login, password: pwd });
//return jData
return data ;
}
function setLoginCredentials() {
var data = GetLoginCredentials();
console.log(data);
$.ajax({
type: "POST",
url: "#Url.Action("Check", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
//contentType: "application/json; charset=utf-8",
//dataType: "json",
//data: JSON.stringify({login:data.login, password: data.password}),
data: data,
success: function (result, status, xhr) {
if (result == true) {
$('#LoginConfirmationModal').modal('show');
}
else if(result == false) {
//var data2 = GetLoginCredentials();
$.ajax({
type: "POST",
url: "#Url.Action("LoginV2", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
data: data,
//contentType: "application/json",
//dataType: "json",
//data: JSON.stringify({ login: data.login, password: data.password }),
//data:JSON.stringify({login:data2.login , password:data2.password}),
//contentType:"application/json;charset=utf-8",
//dataType:"json",
success: function (result, status, xhr) {
},
error: function (xhr, status, error) {
}
});
}
}
,
error: function (xhr, status, error) {
}
});
};
</script>
public class Home
{
string CustEmail { get;set;}
string CustName { get; set;}
int id { get; set;}
}
Model
[HttpPost]
public void CreateCustomer(Home cust)
{
if (ModelState.IsValid)
{
}
}
Controller
angular.module('myFormApp', []).controller('CustomerController', function ($scope, $http, $location, $window) {
debugger;
$scope.cust = {};
$scope.message = '';
$scope.result = "color-default";
$scope.isViewLoading = false;
//get called when user submits the form
$scope.submitForm = function () {
$scope.isViewLoading = true;
console.log('Form is submitted with:', $scope.cust);
//$http service that send or receive data from the remote server
var cust = {
CustEmail: $scope.cust.CustEmail,
CustName: $scope.cust.CustName,
id: 1,
};
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
}).then(function (data, status, headers, config) {
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
})
$scope.isViewLoading = false;
}
}).config(function ($locationProvider) {
//default = 'false'
$locationProvider.html5Mode(true);
});
I get the data in the proper format in front-end and the post-back call is also working but I cannot get value in MVC controller. I don't know what am I doing wrong. I have tried using the individual item in controller then it's working fine but i want it through model only.
The .then method of a promise only exposes one value, not four values.
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
})
For more information, see
AngularJS $http Service API Reference - returns
UPDATE
You can add a .catch block to console log any errors:
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
console.log("OK:", response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
I'm using the recognizeText REST endpoint from javascript running locally on my dev machine. I can successfully call the endpoint, get the operation-location url for the result and send a GET request to that url.
The issue is the return from the operation-location url is 200 success (meaning the operation has completed and doesn't need more time), but the body of the result is always empty.
How can I get the extracted text from the response?
My code:
var subscriptionKey: string = "my key";
var endpoint: string = "https://eastus.api.cognitive.microsoft.com/";
var uriBase: string = endpoint + "/vision/v2.0/recognizeText?mode=Printed";
const fetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
body:
'{"url": "https://www.bing.com/th/id/OIP.nZoyhANat4WNndv0jeoXFAHaLp?w=183&h=289&c=7&o=5&dpr=1.5&pid=1.7"}',
method: "POST"
};
fetch(uriBase, fetchData).then(data => {
var operationLocation = data.headers.get("Operation-Location");
if (operationLocation) {
const resultFetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
method: "GET"
};
setTimeout(function(operationLocation, resultFetchData) {
fetch(operationLocation, resultFetchData).then(resultData => {
alert(JSON.stringify(resultData, null, 2));
});
}, 10000);
}
});
}
There is something wrong with your fetch request code block, try this :
fetch(uriBase, fetchData).then(data => {
var operationLocation = data.headers.get("Operation-Location");
if (operationLocation) {
const resultFetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
method: "GET"
};
setTimeout(()=> {
fetch(operationLocation, resultFetchData).then(resultData => {
return resultData.json();
}).then((data)=>{
console.log(JSON.stringify(data, null, 2));
});
},10000);}
});
Result :
I try to implement a logIn in Meteor 0.9.2.1 with LDAPJS and Meteor methods. The code for the server-side is:
var Future = Meteor.npmRequire('fibers/future');
var ldap = Meteor.npmRequire('ldapjs');
LDAP = {};
LDAP.ldap = ldap;
LDAP.serverIP = 'xxx';
LDAP.serverPort = 'xxx';
LDAP.searchOu = 'ou=xxx,dc=xxx,dc=xxx';
LDAP.searchQuery = function(user) {
return{
filter: '(uid=username)',
scope: 'sub'
}
};
LDAP.checkAccount = function (options) {
LDAP.client = ldap.createClient({
url: 'ldap://' + LDAP.serverIP + ':' + LDAP.serverPort
});
options = options || {};
var dn = [];
future = new Future;
if (options.hasOwnProperty('username') && options.hasOwnProperty('password')) {
LDAP.client.search(LDAP.searchOu, LDAP.searchQuery(options.username), function (err, search) {
search.on('searchEntry', function(entry){
//console.log('entry: ' + JSON.stringify(entry.object));
dn.push(entry.object.uid);
dn.push(entry.object.userPassword)
});
search.on('error', function (err) {
throw new Meteor.Error(500, "LDAP server error");
});
search.on('end', function () {
if (dn.length === 0) {
future['return'](false);
return false;
}
var testBind = LDAP.ldap.createClient({
url: 'ldap://' + LDAP.serverIP + ':' + LDAP.serverPort
});
testBind.bind(dn[10], options.password, function (err) {
future['return'](!err);
});
client.unbind(function (err) {
assert.ifError(err);
future['return'](!err);
});
});
});
} else {
throw new Meteor.Error(400, "Missing Parameter");
}
};
var loginHandler = function (username, password) {
Accounts.registerLoginHandler("ldapjs",function(loginRequest) {
if (LDAP.checkAccount(loginRequest)) {
var user = Meteor.users.findOne({ username: loginRequest.username });
if(err){
console.log(err)
}
return {
userId: uid
}
}
});
};
Meteor.methods({
setSignIn: function(username, password) {
loginHandler(username,password)
}
});
My Problem is, that when I want to log in it starts with the loginHandler. But than the console throws back that Object has no method checkAccount. I changed today a lot and I'm already totally confused.
You need to instantiate the empty object as var LDAP = {}. Rest will be solved magically :)
I finally got to work it. Referneces:
http://notjoshmiller.com/using-ldaps-in-meteor/, https://github.com/emgee3/meteor-accounts-ldap
server-side:
var Future = Meteor.npmRequire('fibers/future');
var ldap = Meteor.npmRequire('ldapjs');
var LDAP = {};
LDAP.ldap = ldap;
//provides the variables, needed for the connection
LDAP.serverIP = 'xxx';
LDAP.serverPort = 'xxx';
LDAP.searchOu = 'ou=xxx,dc=xxx,dc=xxx';
//is needed for the searchQuery, which delivers the Filter so that only the uid with
//the given username get searched
LDAP.searchQuery = function(username) {
return{
filter: '(uid=' + username + ')',
scope: 'sub'
}
};
LDAP.checkAccount = function (options) {
//connects the client, nginx is here not necessary
LDAP.client = ldap.createClient({
url: 'ldap://' + LDAP.serverIP + ':' + LDAP.serverPort
});
options = options || {};
var dn = [];
future = new Future;
if (options.hasOwnProperty('username') && options.hasOwnProperty('password')) {
//create the connection
LDAP.client.search(LDAP.searchOu, LDAP.searchQuery(options.username), function (err, search) {
if(err){
console.log(err)
}
//uses the class searchEntry, which is node-specific
search.on('searchEntry', function (entry) {
dn.push(entry.objectName);
LDAP.displayName = entry.object.displayName
});
search.on('error', function (err) {
throw new Meteor.Error(500, "LDAP server error");
});
//uses the end class to 'fulfill' the connection by binding
search.on('end', function () {
if (dn.length === 0) {
future['return'](false);
return false;
}
LDAP.client.bind(dn[0], options.password, function (err) {
future['return'](!err);
});
});
});
return future.wait();
} else {
throw new Meteor.Error(400, "Missing Parameter");
}
};
Meteor.startup(function(){
Accounts.registerLoginHandler("ldapjs", function (loginRequest) {
if (LDAP.checkAccount(loginRequest)) {
var userId;
var user = Meteor.users.findOne({
username : loginRequest.username
//'profile.name': LDAP.displayName
});
if (user) {
userId = user._id;
} else {
// If no Meteor Account is found for a valid LDAP logon,
// you can either prevent logon by passing 'undefined' or
// you can automatically create the new account.
// return undefined;
userId = Meteor.users.insert({ username : loginRequest.username });
}
return {
userId: userId
}
}
return undefined;
});
});
client side:
Meteor.ldapLogin = function (username, password, callback) {
var loginRequest = {
username: username,
password: password
};
Accounts.callLoginMethod({
methodArguments: [loginRequest],
userCallback: function (err) {
if (err) {
console.log(err);
Session.set('alert', 'No valid inputs!');
} else {
Router.go('/Home');
}
}
});
};
//handles LogIn-Button, by using LDAPJS
Template.signIn.events({
"submit #box-login": function (e, t) {
e.preventDefault();
var signInForm = $(e.currentTarget),
username = trimInput(signInForm.find('#emailSignIn').val().toLowerCase()),
password = signInForm.find('#passwordSignIn').val();
if(isNotEmpty(username)&& isNotEmpty(password)) {
Meteor.ldapLogin(username, password, function (err) {
if (err) {
console.log(err)
Session.set('alert', 'Sorry, something went wrong.');
}
});
} else {
Session.set('alert','Please insert your username and password!')
}
return false;
}
});
PS: No Meteor.methods and Meteor.call is needed! It might change with every new Meteor version and package, but I guess u're aware of that ;)
i need to ask something and i am getting stucked of this:
This is my controller code :
public ActionResult FastRegister(FormCollection collection)
{
UserModel db = new UserModel(0);
string str = "";
//Boolean
//Common.IsAlphaNumeric_Dot_Underscore()? er
errorInsert err = new errorInsert();
try
{
db.set_value(0, Common.HtmlFormUrlEncode(collection["user_name"]), Common.HtmlFormUrlEncode(collection["user_pass"]), "", "", Common.HtmlFormUrlEncode(collection["user_email"]), "", DateTime.Now, "", Common.RandomString(false), 0);
db.Insert();
err.duplicate = false;
err.error = "success register";
return Json(err, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
if (exception.Message.Contains("unique") == true && exception.Message.Contains("duplicate") == true)
{
err.duplicate = true;
err.error = "username or email already taken";
}
else
{
err.duplicate = false;
err.error = exception.Message;
}
return Json(err, JsonRequestBehavior.AllowGet);
}
}
}
class errorInsert
{
public Boolean duplicate;
public string error;
public errorInsert()
{
}
}
and this is my jquery code :
<script type="text/javascript">
$(document).ready(function(){
function ajax_send_url(user_name, user_pass, user_email)
{
$.ajax({
type: 'POST',
url: 'http://localhost/smile/User/FastRegister',
data: 'user_name='+user_name+'&user_pass='+user_pass+'&user_email='+user_email,
//contentType: 'application/json; charset=utf-8',
success: function(e)
{
//var x=jQuery.parseJSON(e);
$("#loading").html(e.error);
}
, dataType:"json"
, beforeSend:function (e){$("#loading").html('<img src="loading.gif" width="50px">');}
});
}
$("#register").click
(
function()
{
var user_name = $("#user_name").val();
var user_pass = $("#user_pass").val();
var user_email = $("#user_email").val();
ajax_send_url(user_name,user_pass,user_email );
}
);
});
I've got in my firebug 200 OK Http but no response when i checked. Please someone figure it out and help me. Thanx...