Not able to fetch data in codeigniter from angular 4 view - php

I am using angular 4 for front end and CodeIgniter at the backend. At the angular end, there is a form that has some input values and images that I need to fetch at CodeIgniter end so that they can be saved in the database. But for an image, I wish to save it in a folder and then save its path in a database
Form code
<form ngNativeValidate [formGroup]="form" (ngSubmit)="onSubmitadd()" class="form-horizontal">
<input type="text" class="form-control" name="title" id="title" formControlName="title" minlength="10" maxlength="150" required>
<input type="file" id="avatar" (change)="onFileChange($event)" #fileInput required>
<button type="submit" class="demo-loading-btn btn red savebtn">Save</button>
</form>
onSubmitadd() {
const formModel = this.form.value;
this.loading = true;
this.http.post('http://www.localhost/litehires/company/profile',formModel ,{
})
.subscribe(
res => {
console.log(res);
$("#add-data .close").click();
this.listBanner();
},
err => {
console.log("Error occured");
}
);
}
Controller Code
public function profile()
{
$res = $this->input->post('formModel');
return $res;
}
While checking in a console the data is getting passed in formModel but I am not able to fetch the data in a controller. Can anyone please tell how to fetch the data and image so that I can process it further

You will have to use php input stream for this
$data = json_decode(file_get_contents('php://input'), true);
public function profile()
{
$res = json_decode(file_get_contents('php://input'), true);
}
Let me know if it is unclear as I have been using it in my controllers

Related

How do I send an image to a PHP API using VueJS?

I am trying to send an object which contains an image using Vue to a PHP API but honestly I don't know how,
I have my form
<form #submit='sendData'>
<div class="input-group">
<label for="name">Name</label>
<input type="text" #change="getText" name='text' id='text'>
</div>
<div class="input-group">
<label for="photo">Photo</label>
<input type="file" #change="getImage" name='photo' id='photo'>
</div>
</form>
export default{
data(){
return {
myData:{
text:'',
photo:''
}
}
}
and the getImage() like this
getImage(event){
let formData = new formData();
formData.append('photo',event.target.files[0]);
this.myData.photo=formData;
}
getText(event){
this.myData[event.target.name]=event.target.value;
}
sendData(event){
event.preventDefault();
this.$http.post('myapi/api/user',this.myData);
}
I don't know how to access this image in my PHP API and upload it to database.
I tried accessing $_FILES but it's an empty array
Sorry seems the problem is that I am sending some other data too and not only the formData
if you want to send an image to an api.
You form should specify the type de data you must send for
your form. you should add this.
<form enctype="multipart/form-data">
<input type="text" class="form-control" v-model="myData.text" />
<input type="file" class="form-control" #change="handleUpload($event.target.files)" />
</form>
In your script you need to set this methods
data () {
return {
myData: {
text: '',
photo: null
}
}
},
methods: {
handleUpload(files) {
this.myData.photo = files[0];
},
saveProductImage () {
let formData = new FormData()
formData.append('text', this.myData.text);
formData.append('photo', this.myData.photo);
// Send here
}
}
Please check the docs

Vue form not sending data in request

I have a form in one component, and I am trying to send data on submit with Ajax request:
<form>
<div class="control">
<input class="input is-large" type="email" v-model="email" required>
<label>E-post</label>
</div>
<div class="control">
<input class="input is-large" type="password" v-model="password" required>
<label>Passord</label>
</div>
<div #click="save" type="submit" class="button hero-button is-medium is-primary">
Logg in
</div>
</form>
This is the method for post request, I am using axios library for Ajax requests:
methods: {
save() {
const form = new FormData();
form.append('email', this.email);
form.append('password', this.password);
this.$backend.post('/user/login', form, {
}).then(() => {
console.log('success');
}, (err) => {
console.log(err);
});
}
}
But, when I check on the backend side, built with laravel, I get an empty request:
{"request":[]}
This is the function in the controller on the backend side:
public function login(Request $request)
{
//testing $request object
return ['request' => $request->all()];
$authenticatedUser = $this->authenticate($request->email, $request->password);
if (!$authenticatedUser) {
$remoteAuthenticated = $this->checkWplUser($request->email, $request->password);
if (!$remoteAuthenticated) {
return $this->response->errorUnauthorized();
}
}
return $this->issueToken($request->email, $request->password);
//return $this->returnUserResponse();
}
This is how the request header looks like:
How can I fix this?

Login AJAX and codeigniter

I am trying to incorporate AJAX into my work. I want it to log the user in once the login button has been pressed. Below is the relevant code.
The view is calling the login function in my controller.
View
<form id="loginform" class="navbar-form navbar-right" action="https://siteurl/CI/index.php/postedLinks/login" method="post" role="search">
<div class="form-group">
<input type="text" name="username" class="form-control" placeholder="Username">
<input type="password" name="password" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Login</button>
</form>
Controller
public function login(){
$this->form_validation->set_rules('username','Username', 'trim|required');
$this->form_validation->set_rules('password','Password', 'trim|required|callback_check_login');
if ($this->form_validation->run()==false) {
$data['links'] = $this->links_model->get_links();
$this->load->view('postedLinks', $data);
}else{
redirect(site_url('postedLinks'), 'refresh');
}}
public function check_login($password){
$username = $this->input->post('username');
$result = $this->links_model->login($username,$password);
if ($result) {
$sess_array = array();
foreach ($result as $row) {
$sess_array = $arrayName = array('id' => $row->id, 'username' => $row->username);
$this->session->set_userdata('logged_in', $sess_array);
}
return true;
} else{
$this->form_validation->set_message('check_login', 'Invalid Username or Password');
return false;
}
}
It works perfectly however I need to add ajax into it however when I attempt it never works. Any help is appreciated. Below is what I have attempted to place in my view.
$(document).ready(function() {
// process the form
$('#loginform').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
// process the form
$.ajax({
url : "https://siteurl/CI/index.php/postedLinks/login"
type : "POST",
dataType : "json",
data : {"username" : username, "password" : password},
success : function(data) {
// do something
},
error : function(data) {
// do something
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
You've not modified the javascript in any way to show us your attempt. The code below should work to pass the username and password to the login controller but you'll need to decide what to do once the user is logged in. You'll also have to output some JSON from the login controller to tell it the login has been successful. Note, I've added ID tags to the HTML form to select the input values via jQuery.
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form id="loginform" class="navbar-form navbar-right" action="https://siteurl/CI/index.php/postedLinks/login" method="post" role="search">
<div class="form-group">
<input id="uname" type="text" name="username" class="form-control" placeholder="Username">
<input id="pass" type="password" name="password" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Login</button>
</form>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
// process the form
$('#loginform').submit(function(event) {
// get the form data
// note, I've added ID tags to your form above
var u = $('#uname').val();
var p = $('#pass').val();
$.ajax({
url : "https://siteurl/CI/index.php/postedLinks/login", //enter the login controller URL here
type : "POST",
dataType : "json",
data : {
username : u,
password : p
},
success : function(data) {
// do something, e.g. hide the login form or whatever
alert('logged in');
},
error : function(data) {
// do something
alert('pooped the bed');
}
});
// stop the form from submitting the normal way and refreshing the page
return false;
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
your problem is your controller:
your ajax code call function login in your controller and pass two variable to it but your login function do not get them,login function must be like this:
public function login($Variable_one,$Variable_two)
Here is a snippet of one of the ajax forms I use.
$("#form1").submit(function() {
var data = $("#form1").serialize();
//alert(data); return false;
$.ajax({
url: "/forms/form1",
data: data,
type: "POST",
success: function(msg) {
if (msg) {
$("#display").html(msg);
} else {
$("#display").text("nothing came back For some reason");
}
}
});
return false;
});
You serialize your form data. You are not using json, you are using post. You do not need to include the long URL of your post method or URL, just use the controller and the method, Codeigniter puts in the base_url by itself. Try it this way
You also do not need the prevent default. Just use return false

Angularjs Image Upload showing empty nested object

I'm a bit confused how to access file data using with angular from a basic form. I'm following a tut on: (https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs) and youtube (https://www.youtube.com/watch?v=vLHgpOG1cW4). They seem to get it right but when I try things seem to go a different way. Anyways here's my HTML form:
<form>
<div class="form-group">
<label for="name">Full Name</label>
<input type="text" ng-model="customer.name" id="name" class="form-control"/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" ng-model="customer.email" id="name" class="form-control"/>
</div>
<div class="form-group">
<label for="file">Image</label>
<input type="file" file-model="customer.file" id="file" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" ng-click="submit()" class="btn btn-primary">Submit</button>
</div>
</form>
And the Directive
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
And finally the controller:
app.controller('CustomerController', ['$scope','CustomerService', function($scope, CustomerService){
$scope.customer = {};
CustomerService.save($scope.customer);
}]);
When I {{ customer }} in my view I'm getting something like this:
{"name":"Robert DeNiro","email":"robie#godfather.com","file":{}}
It's that empty last "file":{} file object that's causing me problems getting values to post to server.
Here's my Customer Service code:
var CustomerService = function($resource) {
return $resource('advertisements/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
},
save: {
method: 'post',
transformRequest: angular.identity,
'Content-Type': undefined
}
});
};
CustomerService.$inject = ['$resource'];
app.service('CustomerService', CustomerService);
I'm using Laravel 5.1 and its reporting validation errors 'required' on all fields suggesting there's an empty object sent through. Thanks in advance.
I have added a submit() method in CustomerController like this:
$scope.submit = function(){
var file = $scope.customer.file;
console.log('file is ' );
console.log(file.name);
console.log($scope.customer.file);
console.dir($scope.customer.file);
};
And in there you can see I've tried experimenting with console.log() and console.dir() and i seem to get the results. For example if i console.log($scope.customer) or console.dir($scope.customer) it gives me the nested file object with all file details. And its looking like this:
> Object {name: "robert deniro", email: "robie#godfather.com", file: File}
> Object
Notice file: File Therefore I'm able to access the file contents/object within the submit() like this: console.log(file.name) or console.log(file.type) or console.log(file.size). I don't know why I was missing it all this time. I hope someone learn from my mistake.
May be that form requires the attribute enctype="multipart/form-data".

PHP and Angular JS resource post

How will I receive my post data comes from angular resource to php?
Angular controller:
myApp.controller('myController', ['$scope', 'USER', function($scope, USER) {
$scope.addItem = function () {
USER.save($scope.item, function () {
$scope.items.push($scope.item);
console.log($scope.item);
});
};
}]);
HTML Form:
<div ng-app="myApp">
<form method="POST" enctype="multipart/form-data" ng-controller="myController">
<label>Email</label>
<input type="text" name="txtEmail" ng-model="item.txtEmail" />
<label>Fullname</label>
<input type="text" name="txtFullname" ng-model="item.txtFullname" />
<button type="button" ng-click="addItem()" name="btnSubmit">
Add Data
</button>
</form>
</div>
PHP:
public function addUser(){
$txtEmail = $_POST['txtEmail'];
$txtFullname = $_POST['txtFullname'];
if(isset($_POST['btnSubmit'])):
$query = $this->sql->prepare('INSERT INTO tbl_users (id, fullname, email) VALUES (NULL, :fullname, :email)');
$query->execute(array(':fullname' => $txtFullname, ':email' => $txtEmail));
endif;
}
Screenshot:
In my given screenshot, how will my php function received the output of angular resource?
You need to send the ajax call to the php page you want to read the data . In the angular controller
(you need to include $http in the app controller)
USER.save($scope.item, function () {
$http.post('/poster.php',{item:$scope.item})
.then(function(result) {
console.log( result.data) ; // the response from server
});
In your poster.php file (or controller), you need to check for the POST variables as you normally do and send back the response.
print_r($_POST['item']);
Here is the answer:
I can't considered angular post as an regular php post:
http://codeforgeek.com/2014/07/angular-post-request-php/

Categories