angularjs $http(config) ith data from form not working - javascript

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');
});

Related

Laravel 6 Error - Undefined property: App\Http\Controllers\GetContentController::$request

I am trying to send form data including files (if any) without form tag via Ajax request. However, I am getting the following error message
Undefined property: App\Http\Controllers\GetContentController::$request
Here are my codes
Controller
public function GetContentController($params){
$CandidateFullName = $this->request->CandidateFullName;
$CandidateLocation=$this->request->CandidateLocation;
//inserted into database after validation and a json object is sent back
Web.php
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Blade
<input type="text" id="CandidateFullName" name="CandidateFullName" class="form-control">
<input type="text" id="CandidateLocation" name="CandidateLocation" class="form-control">
<button id="final_submit">Submit</button>
<script>
$('#final_submit').click(function(e){
e.preventDefault();
var data = {};
data['CandidateFullName']= $('#CandidateFullName').val();
data['CandidateLocation']=$('#CandidateLocation').val();
submitSaveAndNext(data)
});
function submitSaveAndNext(data){
//console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}
});
$.ajax({
type : "POST",
url : '{{url("GetContent/submitContent")}}', //GetContentController ,but without Controller in the end
dataType : "json",
contentType : "application/json",
data : JSON.stringify(data),
success : function(response){
//console.log("response ",response);
if(response.message=="success"){
swal({
title:"Success",
type: "success",
});
}else{
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
},
error:function(xhr, status, error){
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
}) //ajax ends
I don't think controller instance in laravel possess the property having request instance, you'll have to type-hint to obtain the object of the request
public function GetContentController($params) {
// $this->request is the issue
$CandidateFullName = $this->request-> CandidateFullName;
$CandidateLocation = $this->request->CandidateLocation;
}
So you can try either of the below-given solutions
// make sure include the Request class into your controller namespace
public function GetContentController($params, Request $request) {
$CandidateFullName = $request->input('CandidateFullName');
$CandidateLocation = $request->input('CandidateLocation');
}
Or use the helper function for request
public function GetContentController($params) {
$CandidateFullName = request('CandidateFullName');
$CandidateLocation = request('CandidateLocation');
}
These links will help you get more details :
https://laravel.com/docs/8.x/requests#accessing-the-request
https://laravel.com/docs/5.2/helpers#method-request

Pass 2 parameters in $http POST

I have a scenario where a property can have multiple images but that image can only be assigned to one property(one to many, propertyId as FK).
In the html I'm retrieving the propertyId and passing it with the uploadFile function
<div id="imageDiv" ng-controller="uploadImageCtrl">
<input type="button" class="btn btn-info" value="Upload Image" ng-click="uploadFile(pro.id)"/>
<input type="file" file-input="files"/>
</div>
Here I have my app.js where I'm retrieving the image, and propertyId as Id. I'm trying to pass id and form_data.
app.directive("fileInput", function($parse){
return{
link: function($scope, element, attrs){
element.on("change", function(event){
var files = event.target.files;
console.log(files[0].name);
$parse(attrs.fileInput).assign($scope, element[0].files);
$scope.$apply();
});
}
}
});
app.controller("uploadImageCtrl", function($scope, $http,$routeParams,$location){
$scope.uploadFile = function(id){
var form_data = new FormData();
angular.forEach($scope.files, function(file){
form_data.append('file', file);
});
$scope.id = id;
console.log(id);
$routeParams.id = id;
//$scope.activePath = null;
$scope.updateMessage="";
console.log(form_data);
$http.post('php/uploadImage.php/',{'id':id},form_data,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined,'Process-Data': false}
}).success(function(response){
alert(response);
});
}
});
Then in uploadImage.php I'm assigning $id to the propertyId retrieved from app.j and uploading the image to that propertyId.
<?php
$data = json_decode(file_get_contents("php://input"));
$id=$data->id;
echo $id;
require_once("connection.php");
$conn = connectToDb();
if(!empty($_FILES))
{
$path = '../Images/' . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $path))
{
$insertQuery = "INSERT INTO tbl_images(imagePath , propertyId) VALUES ('".$_FILES['file']['name']."',$id)";
if(mysqli_query($conn, $insertQuery))
{
echo 'File Uploaded';
}
else
{
echo 'File Uploaded But not Saved';
}
}
}
else
{
echo mysqli_error($conn);
}
?>
The problem is that it's giving me a blank error with the number 8 and don't why it's not uploading, the 8 represents $id(echo $id).So propertyId is being retrieved succesfully and passed into the php.
The error is probably the last ELSE statment(echo mysqli_error($conn)).
Is form_data not being passed succefully?
I just needed to append id as well, with the form data and then retrieve the id with a normal POST.
app.controller("uploadImageCtrl", function($scope, $http,$routeParams,$location){
$scope.uploadFile = function(id){
var form_data = new FormData();
angular.forEach($scope.files, function(file){
form_data.append('file', file);
});
form_data.append('elmID', id);
$http.post('php/uploadImage.php',form_data,
{
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Process-Data': false
}
}).success(function(response){
alert(response);
});
}
});

Google Script: get values from input forms

I implemented an authentication process using google scripts but with hard-coded data for username and password values from payload option and I can't find a way to get these values from the html page when user presses the Login button...
Is there a way to get this values from input fields to payload option?
Here is my code:
HTML:
<body>
<form>
<fieldset class='login'>
<div class="required">
<label for="email">Email:</label>
<input type="text" name="email" id="email" class="input-text" />
</div>
<div class="required">
<label for="pass">Password:</label>
<input type="password" name="pass" id="pass" class="input-password" />
</div>
</fieldset>
<input type="submit" id="submit-btn" value="Login" name='Submit' class='btn'/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#submit-btn').click(function() {
google.script.run.login();
});
</script>
</body>
Google Script:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Menu')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('login')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('SDR Tag Governance')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function login(){
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : 'email', //Add here the value from #email input
'password' : 'pass' //Add here the value from #pass input
}
var headers = {
'Connection':'keep-alive',
'Content-Type':'application/json;charset=utf-8',
'Accept':'application/json, text/plain, */*',
}
var options = {
'method' : 'post',
'headers' : headers,
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
Logger.log(urlResponse);
}
I tried to add this code to the HTML page:
<script>
$('#submit-btn').click(function() {
google.script.run
.withSuccessHandler(function(response) {
return urlResponse;
})
.login({
email: $('#email').val(),
pass: $('#pass').val()
});
});
</script>
With GS function:
function login(email,pass){
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : email,
'password' : pass
}
var headers = {
'Connection':'keep-alive',
'Content-Type':'application/json;charset=utf-8',
'Accept':'application/json, text/plain, */*',
'Cookie':'...',
}
var options = {
'method' : 'post',
'headers' : headers,
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
Logger.log(urlResponse);
}
But it doesn't work...
In your original HTML file you are not passing anything to the login() function in you .gs file. You can use jquery to grab those values.
<script>
$('#submit-btn').click(function() {
google.script.run
.withSuccessHandler(function(response) {
// this is where you handle the response from your Code.gs
})
.withFailureHandler(function(error) {
console.log(error);
})
.login({
email: $('#email').val(),
pass: $('#pass').val()
});
});
</script>
EDIT: login function in gs file
function login(data){
// i dont think you need this endpoint variable
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
// since you are passing in an object in the html, you can
// access the properties of data
var payload = {
'username': data.email,
'password': data.pass
}
// this is the same as your original
var headers = {
'Connection':'keep-alive',
'Content-Type':'application/json;charset=utf-8',
'Accept':'application/json, text/plain, */*',
'Cookie':'...',
}
// are you sure you need to JSON.stringify the payload?
// try just passing the payload object as is
var options = {
'method' : 'post',
'headers' : headers,
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
// Logger.log shows you what comes back
// when that is fine change it to return urlResponse;
// this will then get sent to the withSuccessHandler that is
// in your HTML file.
Logger.log(urlResponse);
}

Passing Parameter to Angular

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);
}
);

Angular-js post always getting error(0) as response

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);
});

Categories

Resources