I used the code below to upload Image and username to server. it works fine.
Now I want to return the username and filename in a console but it says this request has no response data available. I have tried to use a successcallback() function but still with no luck. it seems the issue is from the successcallback(). can someone help me fix that.
file.upload = Upload.upload({
method: 'post',
url: 'image.php',
data: {username: $scope.username, file: file},
}).then(function successCallback(response) {
alert(response.data[0].username);
alert(response.data[0].file);
console.log(response.data[0].username);
});
below is the entire code
//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout','$http', function ($scope, Upload, $timeout, $http) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
url: 'upload.php',
data: {username: $scope.username, file: file},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
console.log(response.data[0].username);
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
image.php
<?php
error_reporting(0);
$data = json_decode(file_get_contents("php://input"));
$username = strip_tags($data->username);
$return_arr[] = array("username"=>$username);
echo json_encode($return_arr);
exit();
The issue mentioned in the post above has been resolved.
I was sending the form parameter username as json_decode()
$data = json_decode(file_get_contents("php://input"));
$username = strip_tags($data->username);
Sending everything as post parameter solved my problem as in case below
$username = $_POST['username'];
Thanks
Related
I don't have much front-end experience, so please bear with me.
I have a local Angular app in browser (no back-end) and I want to upload a JSON file so that I can show the uploaded data on graphs. Since I don't know if I can just fs.readFile from Angular, I've chosen ng-file-upload to load the file in a nice way (from the file browser). Let me know if it isn't the right tool, though...
So I've copied the code from the official JS Fiddle on the repo. Had to modify it a bit to allow me upload anything -- remove validations.
var app = angular.module('app', ['ngFileUpload']);
app.controller('fileUploader', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function(file, errFiles) {
$scope.f = file;
$scope.errFile = errFiles && errFiles[0];
if (file) {
file.upload = Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () { // don't know why this timeout
$scope.fileReady = true;
file.result = response.data;
// can't figure out what to do with this!!!
console.log('response.data:\n', JSON.stringify(response.data.result, null, 2));
});
}, function (response) {
if (response.status > 0)
$scope.fileError = response.status + ': ' + response.data;
});
}
};
}]);
The response comes out as an object I can't do much with:
[
{
"fieldName": "file",
"name": "my-awesome-data.json",
"size": "364077"
}
]
How do I get the actual data that was uploaded / parse the JSON file?
Try to get the file content using $http.get like:
$http.get(response.data).success(function(data) {
console.log(data);
});
Good night!.. I am a newbie working on MEAN Stack, and I'm trying to upload a picture using the ng-file-upload. This is the angular code:
app.controller('profilePicCtrl', ['Upload', '$scope', '$http',
function(Upload, $scope, $http){
$scope.watch(function(){
return $scope.file
}, function(){
$scope.upload($scope.file);
});
$scope.userID = localStorage.getItem('userID');
$scope.upload = function(file){
console.log("entro en upload");
if(file){
Upload.upload({
url:'api/profile/edit',
method:'POST',
data: {userId: $scope.userID},
file: file
}).progress(function(evt, status){
console.log("dale puej mijo ");
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status){
console.log('archivo subido');
}).error(function(error){
console.log(error);
})
}
};
}]);
Here is the express code:
module.exports.updatePhoto = function(req, res){
var file = req.file;
var userId = req.body.userId;
console.log("User "+userId+ " is submitting ", file.name);
}
And the last is the server-side code, where I call the controller:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var profileController = require('./routes/profile-controller');
...
app.post('api/profile/edit', multipartMiddleware, profileController.updatePhoto);
It doesn't go thru the controller, the server never responds. Thanks in advance for your attention.
I had a code that wasn't letting me go into any other method different than 'GET'. This one below was the guilty one:
if(req.method === "GET" || req.method === "POST"){
if(!req.isAuthenticated()) {
res.redirect('/#login');
}else{
return next();
}
}
Instead of the or sentence I had in the if just the req.method==='GET sentence, which was causing my code to go into an infinity loop returning the next() method but not finding one. Now with the or sentence my code goes to the POST methods.
I'm encountering a weird issue in my AngularJS app. It's supposed to access a number of values from a cookie 'login', pass those values to an API endpoint and then return the API response.
This works fine, except it keeps launching new GET queries continuously every 500ms. This results in an unending stream of the console error: "Error: 10 $digest() iterations reached. Aborting!" and forcing me to kill it manually.
Where is this weird behavior coming from, and how can I limit it to just 1 run?
workbooks.html
<body>
<div>This is the workbooks view.</div>
<span>{{callQueryWorkbooksForUser()}}</span>
<section ui-view>{{response}}</section>
</body>
workbooks.controller.js
'use strict';
(function() {
class WorkbooksComponent {
constructor($scope, $http, $cookies) {
$scope.callQueryWorkbooksForUser = function() {
var login = JSON.parse($cookies.get('login'))
var auth_token = login.authentication_token;
var siteid = login.site_id;
var userid = login.user_id;
$http({
method: 'GET',
url: '/api/sites/' + siteid + '/users/' + userid + '/workbooks',
params: {
auth_token: auth_token
}
}).then(function successCallback(response) {
$scope.response = response.data
}, function errorCallback(response) {
$scope.response = 'Server error'
});
};
}
}
angular.module('orbitApp')
.component('workbooks', {
templateUrl: 'app/workbooks/workbooks.html',
controller: WorkbooksComponent
});
})();
Make the http request in init block of your controller.
class WorkbooksComponent {
constructor($scope, $http, $cookies) {
this.$onInit = function() {
var login = JSON.parse($cookies.get('login'))
var auth_token = login.authentication_token;
var siteid = login.site_id;
var userid = login.user_id;
$http({
method: 'GET',
url: '/api/sites/' + siteid + '/users/' + userid + '/workbooks',
params: {
auth_token: auth_token
}
}).then(function successCallback(response) {
$scope.response = response.data
}, function errorCallback(response) {
$scope.response = 'Server error'
});
};
}
}
This is my AngularJS controller :
app.controller('emailConfirmCtrl', function ($scope, $http) {
$scope.check_credentials = function () {
var request = $http({
method: 'POST',
url: 'api/slim.php/website/email_verification',
data: {
email: 'email#abc.com'
},
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' }
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
console.log('email sent successfully');
console.log(data);
});
}
});
And in my Slim API I am trying to access data like this:
$app->post("/website/email_verification", function () use ($app, $db) {
$request = $app->request();
$body = json_decode($request->getBody());
// $email_id = $body['email'];
echo $body;
});
But I am getting Error 404, but if I change post method to get then there is no 404 error(i.e url given in AngularJS controller is fine).
How can I access email_id in my SLIM API with post method.
$app->post(
'/login',
function () use ($app) {
$app->response()->header("Content-Type", "application/json");
$post = json_decode($app->request()->getBody());
$postArray = get_object_vars($post);
$login = $postArray['login'];
$pass = $postArray['pass'];
for json you can read raw request body
you will decode the input stream
$body = json_decode(file_get_contents('php://input'));
in your case you can try this
$app->post("/website/email_verification", function () use ($app, $db) {
$body = json_decode(file_get_contents('php://input'));
echo $body;
});
I'm making a mobile app and I have a controller that handles user login. It makes a http call (currently to localhost) to check if the user is valid. For some reason it won't fire off the $http call and the console says nothing about it failing. I'm new to AngularJS and I've probably made a beginner mistake in my code. I'm using AngularJS with Ionic Framework.
This is my LoginController:
.controller('LoginCtrl', ['$scope', '$ionicPopup', 'User', '$window', '$http', '$templateCache', function($scope, $ionicPopup, User, $window, $http, $templateCache){
$scope.authUser = function(){
console.log('authUser initialized');
var email = document.getElementById('User_email');
var password = document.getElementById('User_password');
console.log('email=' + email.value);
console.log('password=' + password.value);
console.log('logging in...');
if(email.value == '' || password.value == ''){
var alertPopup = $ionicPopup.alert({
title: 'Failed to login',
template: 'Both fields need to be filled.'
});
alertPopup.then(function(res){
console.log('Both fields need to be filled.');
});
} else {
console.log('Contacting API server...');
$scope.$apply(function(){
$http({
method: 'POST',
url: 'http://api.tb.local/api.php',
data: { 'action': 'user/auth', 'email': email.value, 'password': password.value },
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).
success(function(response){
console.log('Response success');
console.log(response);
if(response.valid){
console.log('Login success. Redirecting to welcome page...');
$window.location.href = '#/welcome';
} else {
var alertPopup = $ionicPopup.alert({
title: 'Failed to login',
template: 'Wrong credentials. Please try again.'
});
alertPopup.then(function(res){
console.log('Wrong credentials. Please try again.');
});
}
}).
error(function(response){
var requestFailDialog = $ionicPopup({
title: 'Internal Error',
template: 'The server encountered an unknown error.'
});
requestFailDialog.then(function(res){
console.log('Internal Error: ' + response);
});
});
});
}
}
}])
The last thing I get in my console is Contacting API server....
I tested my API manually and it returns a json { "valid": true } just like it should.
Try to Remove cache: $templateCache from $http request.