understanding $http service - json

I don't understand how the $http service works. I have a controller that calls a factory and the factory calls a WS function.
If I run the app on debug mode, the factory calls the WS function and the WS function returned what I suppose is an json object.
On the other hand, when I watch in the web console, I get a message "undefined".
What should return the WS function? Or what's wrong in my factory?
Thanks in advance.
This is the VB.Net Web Service function:
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
<WebMethod()> _
Public Function getLogin(ByVal email As String, ByVal password As String) As String
Dim dt As New Data.DataTable
Dim result As String = ""
Using con As New SqlConnection(sConn)
'Dim sql As String = "Select id_usuario, nombre_usuario id_tipo_usuario from binder_usuarios where email = #email and password = #password"
Dim sql As String = "Select * from binder_usuarios where email = #email and password = #password"
Dim cmd As New SqlCommand
cmd.CommandText = sql
cmd.Connection = con
cmd.Parameters.AddWithValue("#email", email)
cmd.Parameters.AddWithValue("#password", password)
Dim dataAdapter As New SqlDataAdapter(cmd)
dataAdapter.Fill(dt)
If dt.Rows.Count > 0 Then
result = JsonConvert.SerializeObject(dt, New JavaScriptDateTimeConverter())
Return result
Else
result = "e"
End If
Return result
End Using
End Function
the WS function return a string:
"[{"id_usuario":3,"nombre_usuario":"Quethzel","apellido_paterno":"Diaz","apellido_materno":"Zarate","id_area":1,"id_tipo_usuario":1,"password":"sa","email":"hqdiaz#lis.com.mx"}]"
this is the factory:
function fcQAuth($http, $q, $window) {
return {
loginAuth: function(credentials) {
$http.post('../ws/wsReact.asmx/getLogin', credentials)
.success(function(data, status) {
return "your data it's Ok, in da face !";
})
.error(function(data, status) {
return "don't give up Nigga";
});
//return "myUser. " + credentials.email + ", myPass." + credentials.password;
}
}
}; // end fcQAuth factory
And this is the controller, that call the factory:
function loginCtrl($scope, $q, $http, $location, fcQAuth) {
$scope.loginUser = function() {
var credentials = {
email: $scope.user.email === '' || $scope.user.email === undefined ? 0 : $scope.user.email,
password: $scope.user.password === '' || $scope.user.password === undefined ? 0 : $scope.user.password
};
$scope.userInfo = fcQAuth.loginAuth(credentials);
console.log($scope.userInfo);
};
};

The http.post is an asyncronous call, when the console.log in your controller is executed, the http.post has no returned yet. Try this:
Return the promise in your factory:
function fcQAuth($http, $q, $window) {
return {
loginAuth: function(credentials) {
return $http.post('../ws/wsReact.asmx/getLogin', credentials);
}
};
}
Get the data in the success callback in your controller:
function loginCtrl($scope, $q, $http, $location, fcQAuth) {
var credentials = {
email: $scope.user.email === '' || $scope.user.email === undefined ? 0 : $scope.user.email,
password: $scope.user.password === '' || $scope.user.password === undefined ? 0 : $scope.user.password
};
fcQAuth.loginAuth(credentials).then(function(data){
$scope.userInfo = data;
console.log($scope.userInfo);
});
};

Related

Node.js Login Crashes App because Mysql "results" are "undefined"

I am extremely close to this working but for some reason the browser is rendering the standardized var of "results" as undefined.
` var email = request.body.email;
var password = request.body.password;
if (name && password) {
userDB.query('SELECT * FROM accounts WHERE name = ? AND password = ?', [email, password], function (err, results, fields) {
if (results.length > 0) { // <-- This is it
request.session.loggedIn = true;
request.session.email = email;
//loggedIn = true;
response.redirect('/');
} else {
response.render('test');
loggedIn = false;
}
response.end();
});
}`
Here is the actual err in the console:
TypeError: Cannot read property 'length' of undefined
I thought "results" and "fields" were standard. What am I missing?
If need be I can always reply w/ more code to clarify.

My angular controller doesnt send data to c# controller

Hello everyone,
I couldn't send data from my angular controller to my c# controller.Whenever the controller is called it throws out error callback.I have tried different ways,but i couldn't rectify it.Am i making any mistake in defining correct url.I am really clueless.
Angular controller
var httpTimeout = 1800000;
var httpTimeoutSearch = 3600000;
angular.module('MyApp', [])
var app = angular.module('myApp', []);
app.controller('LoginController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
alert("in");
$scope.Username = "";
$scope.Password = "";
$scope.Login = function () {
if ($scope.Username != null && $scope.username != "") {
if ($scope.Password != null && $scope.password != "") {
try {
var obj = { UserName: $scope.Username, Password: $scope.Password };
alert(obj.Username);
$http({
method: 'POST',
data: obj,
url: '/Account/Maxi',
timeout: httpTimeout,
}).then(function successCallback(response) {
alert("sucess");
}, function errorCallback(response) {
alert("error");
});
}
catch (ex)
{ alert(ex); }
}
}
}
}]);
C# controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Maxi(LoginModel data)
{
string strReturn = "";
string ConStr = "";
string Code = "";
if (data.UserName != null)
{
if (data.Password != null)
{
DataSet ds = new DataSet();
SqlParameter[] parameters =
{
new SqlParameter( "#name", SqlDbType.VarChar, 20) { Value = data.UserName } ,
new SqlParameter("#Roll_No", SqlDbType.Int) { Value = data.Password } ,
};
ConStr = "Data Source=" + "192.168.1.9" + ";Initial Catalog=" + "MyFistDataBase" + ";User id=" + "sa" + ";Password=" + "123" + ";";
using (SqlConnection con = new SqlConnection(ConStr))
{
using (SqlCommand cmd = new SqlCommand("Maxi", con))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
cmd.Parameters.AddRange(parameters);
da.SelectCommand = cmd;
da.Fill(ds);
}
}
string errmsg = "";
if (errmsg != "")
{
Code = "0"; strReturn = errmsg;
}
else
{
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
Code = "1";
foreach (DataRow dr in ds.Tables[0].Rows)
{
strReturn += dr[0].ToString();
}
if (strReturn == "1")
{
Console.Write("Updated");
}
}
//TripDT = TripDT.ToShortDateString();
}
}
}
}
return View(data);
}
Object Model
public class LoginModel
{
[Key]
public string UserName { get; set; }
public string Password { get; set; }
}
You are misspelling the sending KVP data.
var obj = { Username: $scope.Username, Passord: $scope.Password };
should be
var obj = { UserName: $scope.Username, Password: $scope.Password };
for verificationToken error need to add this data to json also
"__RequestVerificationToken" : your_html_value
see how to add this key data HERE in Detail

calling callback from another file? node js express

why i can't getting callback as a record? must as a field('id')
ss : https://prnt.sc/ju4xb2
result reading as data row[0] from DAO
how i getting data from record ex: '0001' ? please help thankful
DAO
var executeQuery = function(query,callback) {
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'testt'
});
connection.connect();
connection.query(query, function(err, rows, fields) {
if (err) throw err;
connection.end();
console.log("Here in Dao: " + rows[0].mobile_phone);
callback(rows[0].mobile_phone);
});
};
module.exports = {
executeQuery: executeQuery
};
Model
var DAO = require('../lib/database.js');
module.exports = {
getuser : function(id,callback){
var User = DAO.executeQuery("select mobile_phone from ms_customer WHERE id = " + id, function(mobile_phone){
// var json = JSON.stringify(User);
console.log("Return from Dao = " +User);
callback(mobile_phone);
});
}
}
Controller
test : function(req,res){
var customerModel = require('../model/customer');
customerModel.getuser('0001', function(mobile_phone){
console.log("return from model_user = " + mobile_phone);
});
},
i always got error = 'ER_BAD_FIELD_ERROR: Unknown column '0001' in 'where clause''
i think error at query statement, please try this.
getuser : function(id,callback){
var User = DAO.executeQuery("select mobile_phone from ms_customer WHERE id = '" + id + "';", function(mobile_phone){
// var json = JSON.stringify(User);
console.log("Return from Dao = " +User);
callback(mobile_phone);
});
}
}

Nodejs Request values

So I have a nodejs server and I am trying to make comparisons to the req values. Firstly, here is my code:
app.post('/', function(req, res) {
firstName = req.body.firstName;
lastName = req.body.lastName;
message = req.body.message;
token = req.body.token;
user = {name: firstName + " " + lastName, token: token};
selectedUser = req.body.selectedUser;
users.push(user);
console.log(user.name);
if (req.body.isAndroid === true) {
sendToAndroid(); //add message parameter
} else {
sendToios(); //add message parameter
}
});
app.listen(8080, function() {
console.log('running on port 8080');
});
//GCM
function sendToAndroid() {
var message = new gcm.Message();
var tokenLocation;
//API Server Key
var sender = new gcm.Sender('AIzaSyD-B3EG1xpMh6YhwBKfLMyw0GIQKWfGgZM');
//console.log(message);
// Value the payload data to send...
message.addData({
title: 'Hello',
body: 'Message From: ' + user.name + ': ' + message,
msgcnt: 1,
timeToLive: 3000
});
// At least one reg id required
if (registrationToken.indexOf(token) == -1) {
registrationToken.push(token);
tokenLocation = registrationToken.indexOf(token);
} else {
tokenLocation = registrationToken.indexOf(token);
}
if (users.indexOf(user.name) == -1) {
console.log("user destination not found");
} else {
var userTokenArray = [];
userTokenArray.push(user.token);
sender.send(message, { registrationTokens: userTokenArray } , function (err, response) {
if(err) console.error(err);
else console.log(response);
});
userTokenArray.pop();
}
}
And here is my problem when outputting to see what the value is:
running on port 8080
undefined undefined
user destination not found
What I am trying to do is put the registered users into an array of users that each element has a full name and token. Then in the Android function, it will check to see what value value is selected and then push a notification to the selectedUser via their token. I am so confused on how to compare the "strings" or whatever they are. I am using nodejs express with body-parser.

Json query result not getting set

I am trying to use a Json request to get data from a login screen. But no matter if the login request is valid or not, I am always getting returned to my home screen. I think I am checking the result incorrectly?
Basically, in my Twitter-Bootstrap enabled site, I have a modal popup that takes the user to a login form.
The values are passed via a json query, to my MVC4 controller. A breakpoint shows I am getting good data.
Here's the scrip that sends the data:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result['success'] == 'true') {
alert("true");
window.location = '#Url.Action("Index", "Home")';
} else {
alert("BAD");
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
And here is the controller method:
[HttpPost]
public JsonResult LoginUser(string username, string password, string rememberMe)
{
string success = "false";
string message = "Not set";
if (username == string.Empty || password == string.Empty)
{
success = "false";
message = "Invalid Username/Password";
}
else
{
if (ModelState.IsValid)
{
var us = new UserService();
var reply = us.Authenticate(username, Security.EncryptText(password));
if (reply == 0)
{
success = "false";
message = "Invalid Username/Password";
}
if (reply != 0)
{
var p = us.GetPerson(reply);
FormsAuthentication.SetAuthCookie(p.Id.ToString(CultureInfo.InvariantCulture), rememberMe == "on");
Session["UserDisplay"] = string.Format("{0} {1} - ({2})", p.Firstname, p.Surname, p.Email);
success = "true";
message = "Login Success";
}
}
}
var result = new { Success = success, Message = message };
var r = new JsonResult
{
Data = result
};
return r;
}
However, I always get the 'BAD' alert. Never the 'true'.
Can I check the result the way I am? Am I attempting to do this the right way? Basically, if I get 'BAD', I don't want the screen to refresh. Infact, I will want to show a message saying what ever is in the 'message' parameter.
Edit: I think 'result' is NULL.