Thanks for advance
Hi Tried angular-js http post function but always am getting 0 as error response ,i tried lot but it won't help ,so please give me idea to fix the issue.
I used following files
var app = angular.module('angularPostPHP', []);
app.controller('regCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: 'post',
url:'http://localhost/HAP_testing/Registration.php',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: {
email: $scope.UserName,
pass: $scope.Pwd
}
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
// document.getElementById("message").textContent = "You have login successfully with email "+data;
alert("done"+data);
});
request.error(function(status)
{
alert("Error"+status);
});
}
});
and
<?php
// check username or password from database
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->UserName;
$password = $request->pwd;
if($email == "dhaya" && $password== "dd"){
echo "1";
}
else {
echo "dhaya";
}
?>
I think the issue is here:
$email = $request->UserName;
$password = $request->pwd;
You passed this data:
data: {
email: $scope.UserName,
pass: $scope.Pwd
}
So I would think that would have to be:
$email = $request->email;
$password = $request->pass;
One way to do this would probably be:
// check username or password from database
$email = $_POST['email'];
$password = $_POST['pass'];
if($email == "dhaya" && $password== "dd"){
echo "1";
}
else {
echo "dhaya";
}
Edited:
Changed pwd to pass
Edit:
I've confirmed that this works with the following curl request:
curl -d "email=dhaya&pass=dd" "chase.phpdev.gurutech.ws/question_test.php"
Returns "1". I didn't setup and test the angular. But I've found at least 1 issue.
Thanks to everyone,finally i got fixed. it happening because of request data.
var app = angular.module('angularPostPHP', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: 'POST',
url:'../HAP_testing/Loginphp.php',
// headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
headers: { 'Content-Type': 'application/x-www-form-urlencoded;'},
data: $.param({
email: $scope.username,
pass: $scope.password
}),
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
alert("done");
});
request.error(function(status)
{
alert("Error"+status.code);
});
Related
Let's say I have a login form, with 2 fields, email and password, first I want to check if the user email is actually registered or not, so I made a separate file named user_check.php with the PHP code to check if a user exists or not,
include_once('../../classes/user.class.php');
$User = new User();
if ($User -> UserExists($_POST['login_email']) === true) {
echo true;
} else {
echo false;
}
now from login page, I want to call in an AJAX request to actually check if the UserExists() method returns false or true, if it returns false I will just give an error message to the user, else the code will continue
$.ajax({
url: 'ajax/login-handler/user_check.php',
type: 'POST',
data: {login_email: email.val()},
cache: false,
success: function(data) {
if (data == 1) {
alert('Exists');
} else alert('Doesn\'t Exist');
}
});
Should I do nested Ajax calls for other database checks inside success block if statements? Or if I need to do separate Ajax calls how can I pass one Ajax calls response to the other call?
If you have to make multiple asynchronous calls, I think the cleanest way would be to have an async function that awaits every asynchronous call you have to make. For example, using fetch, which supports well-formed Promises:
$(form).on('submit', (e) => {
e.preventDefault();
tryLogin()
.catch((e) => {
// handle errors
});
});
const tryLogin = async () => {
const userExists = await fetch('ajax/login-handler/user_check.php', {
method: 'POST',
body: JSON.stringify({ login_email: email.val() })
});
if (!userExists) {
// doesn't exist, tell user and return
return;
}
// user exists
const someOtherResult = await fetch('ajax/login-handler/somethingElse.php', {
method: 'POST',
body: JSON.stringify({ foo: 'bar' })
});
// do stuff with someOtherResult
};
First create your login page, then create your username and password field. And put this code after the JQuery library.
$(document).ready(function(){
$('#login').click(function(){
var usernameAdmin = document.getElementById("username").value;
var password = document.getElementById("password").value;
var dataString = 'usernameAdmin='+usernameAdmin+'&password='+password;
$.ajax({
type: "POST",
url: "controler/login.php",
data: dataString,
cache: false,
success: function(data)
{
document.getElementById("login").disabled = false;
window.location="admin/";
}
});
});
});
Now create your Ajax file according to the code below and enjoy it
if(isset($_POST['usernameAdmin']))
{
$username = $_POST['usernameAdmin'];
$password = $_POST['password'];
$c = $check->check_login_admin($username,$password);
if($c == true)
{
echo 1;
}
else
{
echo 0;
}
}
protected function check_login_admin($username,$password)
{
parent::__construct();
$sql = $this->_SELECT." `users` WHERE username=:u AND password=:p";
$r = $this->_DB->prepare($sql);
$r->bindValue(':u', $u);
$r->bindValue(':p', $p);
$r->execute();
$c = $r->rowCount();
if($c == 1)
{
foreach($r->fetchAll() as $row);
$_SESSION['log_true_admin']= true;
$_SESSION['name']= $row['name']." ".$row['family'];
$_SESSION['id']= $row['id'];
return true;
}
else return false;
}
good luck my friend
I have an issue with $http in angularjs :
app.controller('ctrlProfil', function($scope, $http){
$scope.loginProfil = "<?= $_SESSION['login']?>";
$scope.mdpProfil = "<?= $_SESSION['mdp']?>";
$scope.emailProfil = "<?= $_SESSION['email']?>";
var config = {
method: 'POST',
url: 'modifProfil.php',
data: $('#formProfil').serialize()
}
$scope.submit = function(){
$http(config).
then(function(response){
console.log(response);
console.log($('#formProfil').serialize());
})
}
});
my form =>
<form id="formProfil" ng-submit="submit()">
<p><span>Bonjour </span><input type="text" name="loginProfil" value="{{loginProfil}}"/></p>
<p>Mon mot de passe: <input type="text" name="mdpProfil" value="{{mdpProfil}}"/></p>
<p> Email: <input type="email" name="emailProfil" value="{{emailProfil}}"/></p>
<input class="btn btn-primary" type="submit" value="Enregistrer"/>
</form>
my php code =>
try
{
$db = new PDO('mysql:host=localhost;dbname=monprojet;charset=UTF8', 'root', 'root');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$login = $_POST['loginProfil'];
$mdp = $_POST['mdpProfil'];
$email = $_POST['emailProfil'];
$rep = $db->query('SELECT id FROM utilisateur WHERE login='.$_SESSION['login']);
$reponse = $db->prepare('UPDATE utilisateur SET login= :login, mdp= :mdp, email= :email WHERE id='.$rep);
$reponse->execute(array(
':login' => $login,
':mdp' => $mdp,
':email' => $email
));
$json = json_encode($reponse->fetchAll());
$reponse->closeCursor();
echo $json;
i can't manage to send the data via the $http(config), i have an error telling me :
Notice: Undefined index: loginProfil in
/Applications/MAMP/htdocs/izad/git/modifProfil.php on line 15
Notice: Undefined index: mdpProfil in
/Applications/MAMP/htdocs/izad/git/modifProfil.php on line 17
Notice: Undefined index: emailProfil in
/Applications/MAMP/htdocs/izad/git/modifProfil.php on line 19
but my index are defined, need some help to understand this one
Thanks
You have to add headers application/x-www-form-urlencoded to receive the data in GET/POST request in php.
By default, the $http service will transform the outgoing request by
serializing the data as JSON
Change your $http request to this:
var config = {
method: 'POST',
url: 'modifProfil.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $('#formProfil').serialize()
}
$scope.submit = function(){
$http(config).
then(function(response){
console.log(response);
console.log($('#formProfil').serialize());
})
You can also add headers for all $http request like this:
myapp.factory('httpRequestInterceptor', function () {
return {
request: function (config) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
return config;
}
};
});
myapp.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
I have similar issue like this one.
I'm trying to make AJAX login using Laravel 5.3 Auth.
Here's what I got so far:
var login = function()
{
var data = {};
data["email"] = $('#email').val();
data["password"] = $('#password').val();
if($('#remember').is(':checked'))
data["remember"] = "on";
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
// window.location.href = "/dashboard";
}
});
};
I'm sending CRSF token as X-CSRF-TOKEN header.
The problem is that when I successfully login, I say on the same page,
but in Network tab I can see that /dashboard page is loaded by I'm not
redirected.
In the same manner, when I pass wrong credentials, I stay on the same page,
but I can see that /login page is loaded in the separate call with an error message that should be actually displayed.
Also, I've tried without headers : { 'Content-Type': 'application/json' },
and sending data as: data = data, but I get the same thing.
Why the browser doesn't redirect to that page since it is loading it in the "background"?
Edit: I'm getting correct page as request response as well, I can see it
in console (console.log(data);).
//Login FORM
$(document).on('submit', 'form#FormID', function(e) {
e.preventDefault();
var forms = document.querySelector('form#FormID');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','/login');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (request.responseText == 'success') {
setTimeout(function() {
window.location.href = "/dashboard";
}, 5000);
}else{
};
}
}
}
});
//Controller
public function authUser(Request $request){
$data = $request->except('_token');
$validate = \Validator::make($data, [
'email' => 'email'
]);
if ($validate->fails())
return 'Invalid email format for username.';
if (\Auth::attempt($data)) {
return 'success';
}else{
return 'Invalid username or password';
}
}
//Route
Route::post('/login', 'YourController#authUser');
The problem might be with the response AJAX request is expecting before redirect.
Try the above code.
in the controller method
function login(Request $request){
if(\Auth::attempt($request)){
return response()->json('success');
}else{
return response()->json('wrong username or pass', 401);
}
}
in ajax
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
window.location.href = "/dashboard";
},
error : function(data){
alert(data);
}
});
Here's an interesting solution.
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax()) {
return response()->json([
'error' => Lang::get('auth.failed')
], 401);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
And this:
var loginForm = $("#loginForm");
loginForm.submit(function(e) {
e.preventDefault();
var formData = loginForm.serialize();
$('#form-errors-email').html("");
$('#form-errors-password').html("");
$('#form-login-errors').html("");
$("#email-div").removeClass("has-error");
$("#password-div").removeClass("has-error");
$("#login-errors").removeClass("has-error");
$.ajax({
url: '/login',
type: 'POST',
data: formData,
success: function(data) {
$('#loginModal').modal('hide');
location.reload(true);
},
error: function(data) {
console.log(data.responseText);
var obj = jQuery.parseJSON(data.responseText);
if (obj.email) {
$("#email-div").addClass("has-error");
$('#form-errors-email').html(obj.email);
}
if (obj.password) {
$("#password-div").addClass("has-error");
$('#form-errors-password').html(obj.password);
}
if (obj.error) {
$("#login-errors").addClass("has-error");
$('#form-login-errors').html(obj.error);
}
}
});
});
I am going to create a controller that will list distinct a selected field in a selected table in database and pass it to my API.
Currently, i am using a dirty method which is create several controller that has the field name and table name in it.
controller.js
.controller('ListDistinctCustomerCtrl', function($scope, $http) {
var xhr = $http({
method: 'post',
url: 'http://localhost/api/list-distinct.php?table=customer&field=cust_code'
});
xhr.success(function(data){
$scope.data = data.data;
});
})
.controller('ListDistinctSupplierCtrl', function($scope, $http) {
var xhr = $http({
method: 'post',
url: 'http://localhost/api/list-distinct.php?table=supplier&field=supp_code'
});
xhr.success(function(data){
$scope.data = data.data;
});
})
and this is the API file
list-distinct.php
<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);
function GetData($tablename,$fieldname) {
$sql = "SELECT distinct $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
I believe there is a clean and better way to do this.
You can create a service which contains methods for accessing your API. This will enable you to reduce your code duplication in your controllers, and allow for cleaner code in general.
.service('APIService', function($http){
var base = 'http://localhost/api/';
this.listDistinct = function(table, field){
return $http({
method: 'post'
, url: base + '/list-distinct.php'
, params: {
table: table
, field: field
}
});
}
});
Your controllers would inject the service and call whatever method it needs to access the api. Results will be obtained the same way by attaching a promise callback.
.controller('ListCtrl', function($scope, APIService){
APIService.listDistinct('customer', 'cust_code').then(function(data){
$scope.data = data;
})
});
For the PHP side of your code you need to use a white-list of possible table/field names to ensure safe operation. Without such a check you are vulnerable to SQL injection attacks. A simple array check would suffice.
$safeTables = ['customer', 'supplier'];
$safeFields = ['cust_code', 'supp_code'];
if (!in_array($tablename, $safeTables) || !in_array($fieldname, $safeFields)){
throw new Exception('Invalid parameter');
}
first of all, if you want to pass parameters by $http there is a cleaner method:
$http(
{
url: 'your url',
method: 'GET or POST',
params: {
// list of params
}
}
);
Now, is important for code maintenance and readability to use Service provider.
You can use Factory as service and create an API service.
Example:
angular.module( 'yourModule' ).factory( 'ServiceAPI', [ '$http', function ( $http ) {
var factory = {};
//PUBLIC METHODS
factory.method = method;
function method() {
return $http(
{
url: 'your url',
method: 'GET or POST',
params: {
// list of params
}
}
);
}
return factory;
} ] );
And now you can inject ServiceAPI on your Controller and use method function that reply with a promise of http.
angular.module( 'your module' ).controller( 'Ctrl', [ '$scope', 'ServiceAPI' ,
function ( $scope, ServiceAPI ) {
ServiceAPI.method.then( function ( data) {
$scope.data = data;
}, function(){console.err('error');} );
}
] );
AngularJS side, now is clear and readable.
I hope to be helpful for you.
Enjoy
Its time for Angular Providers
This is an example for your case:
angular.module('starter')
.factory('services', services);
function services($http) {
var services = {
customer: customer,
supplier: supplier,
};
return services;
//customer service
function customer() {
var req = {
method: 'POST',
url: 'http://localhost/api/list-distinct.php?table=customer&field=cust_code',
headers: {
'Accept' : 'application/json',
'contentType': "application/json"
}
};
return $http(req);
},
//supplier service
function supplier() {
var req = {
method: 'POST,
url: 'http://localhost/api/list-distinct.php?table=supplier&field=supp_code',
headers: {
'Accept' : 'application/json',
'contentType': "application/json"
}
};
return $http(req);
};
}
Then you call them like this from within the controller:
services.customer().then(
function(response) {
//do whatever is needed with the response
console.log(response);
},
function (error) {
console.log(error);
}
);
services.supplier().then(
function(response) {
//do whatever is needed with the response
console.log(response);
},
function (error) {
console.log(error);
}
);
I am trying to send username and password in json format but I am not sure I am doing it in right way. I am still new to angular.
myApp.controller('loginController',['$scope','$http', function($scope, $http)
{
$scope.email = "" ;
$scope.password = "" ;
$scope.loginForm = function(){
alert("login controller called");
console.log($scope.email);
console.log($scope.password);
var encodedString = 'email=' +
encodeURIComponent($scope.email) +
'&password=' +
encodeURIComponent($scope.password);
$http({
method:'POST',
url: 'rs/loginResource',
data: encodedString,
headers: {'Content-Type' : 'application/json'}
});
};
}]);
When I see in the header post using firefox, the username and password are shown as plain parameters rather than in json format. Right now I am using encodeURIComponent but I want to send it as json. How do I do that?
You don't need to build a query string to send the data with a POST. Nor do you need to specify the content type, Angular will do that for you.
You can use the post() shortcut method to send the data:
var data = { email: $scope.email, password: $scope.password };
var url = 'rs/loginResource';
$http.post(url, data);