PHP and Angular JS resource post - php

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/

Related

PHP and AJAX update data to database

I'm trying to update a simple string to the database with PHP and AJAX.
Here is the code:
HTML
<form id="phoneNumberForm" class="form-inline" method="post" enctype="multipart/form-data">
<div class="form-group mx-sm-3 mb-2 align-content-center">
<label for="phoneNumber" class="sr-only">Phone</label>
<input type="text" class="form-control" name="phoneNumber" id="phoneNumber" placeholder="Phone">
</div>
<button type="submit" name="phoneNumber_submit" id="phoneNumber_submit" class="btn btn-primary mb-2">Save</button>
<div id="phoneSuccess"></div>
</form>
PHP
if (isset($_POST['phoneNumber_submit'])) {
$phoneNumber = $_POST['phoneNumber'];
$profileEditAdmin = $db->query('UPDATE users SET user_phone = ? WHERE user_name = ?', $phoneNumber, $_SESSION['user_name']);
}
AJAX
$('#phoneNumberForm').submit(function(e) {
e.preventDefault();
let phoneNumber = $('#phoneNumber').val();
let $body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
$.ajax({
type: "POST",
data: {
phoneNumber:phoneNumber,
},
success: function() {
$('#phoneSuccess').html('<p>Saved.</p>');
setTimeout(function() {
$('#phoneSuccess').fadeOut();
}, 2000)
}
});
});
When I remove preventDefault() I get the entry in the database, but page is reloaded.
My goal is to have an entry in the database and to avoid page refreshing.
Here your PHP looks for a variable called phoneNumber_submit:
if (isset($_POST['phoneNumber_submit'])) {
But here your AJAX sends only a variable called phoneNumber:
data: {
phoneNumber:phoneNumber,
}
Clearly these two names do not match, so the if statement will never be true and the query will never run. It works when you submit the form without AJAX because you have name="phoneNumber_submit" on your submit button, so this value is sent to the server.
So you can either:
1) hard-code this value into your data parameter:
data: {
"phoneNumber": phoneNumber,
"phoneNumber_submit": true
}
OR
2) just let jQuery do the work for you and use the serialize function to get all the values and names you've already defined in your HTML and send them directly to the server, without you needing to specify each one again:
data: $(this).serialize()
Note: this in the above code will be your <form> element since you're handling the form's "submit" event.

laravel api ajax form wont submit

This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)

Not able to fetch data in codeigniter from angular 4 view

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

how to decode an json array returned to a angular button click

I am trying to get the key value pairs that is return from a mysql query to an angular call. On click I get the three rows I want (see results below).
HTML:
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Fistname <input type="text" ng-model="emp_no" /><br/>
Secondname <input type="text" ng-model="first_name" /><br/>
Thirdname <input type="text" ng-model="last_name" /><br/>
<button ng-click="postData()">Submit</button><br>
</form>
</div>
<script>
var app = angular.module('myapp', []);
app.controller('empcontroller', function($scope, $http)
{
$scope.postData = function () {
var Indata = { what_to_do: "angular_users5", where_clause: '[{"sqlvalue1":"a_earchvalue1","sqlvalue2":"b_earchvalue2"}]' }
var req =
{
method: 'POST',url: 'angular_master.php',
headers: {'Content-Type': undefined},
params: Indata
}
$http(req).then(function (response)
{
$scope.names = response.data.records;
alert("i am here");
.. at this point I need the key value pair or each rows from the results below
});
}
});
</script>
The data return from the php query is:
{
"records":[
{
"Name":"Joe",
"City":"Doe",
"Country":"w"
},
{
"Name":"Joe1",
"City":"Doe1",
"Country":"w1"
},
{
"Name":"Joe2",
"City":"Doe2",
"Country":"w2"
}
]
}
Since I get 3 rows back I like to assign the names to the first name, second name,thirdname fields in the form.
Thanks
To me everything looks fine (except your strange naming conventions). You can now use the data in your view.
<form>
<div ng-repeat="n in names tracked by $index">
<h3>{{$index + 1}}. Name:</h3>
Firstname: <input ng-model="n.Name" /><br />
Secondname: <input ng-model="n.City" /><br />
Lastname: <input ng-model="n.Country" /><br />
<button type="button" ng-click="submitOne(n)">Save this</button>
</div>
<button type="button" ng-click="submitAll(names)">Save all</button>
</form>
Angular will decode your Json String from the server response into a Json Object automatically.
Just take care that your server sends a JSON header, so that Angular understands the format.
// add this to your server script (example: php), before you output the data
header('Content-Type: application/json; charset=utf-8');
Btw. you should not use Content-Type: undefined.
Use:
Content-Type: 'application/x-www-form-urlencoded; charset=utf-8'
Furthermore you are doing a POST request - which is fine, but you use "params" to add data to your request. You should use the "data" key, because "params" will add GET parameters.
https://docs.angularjs.org/api/ng/service/$http#usage
params – {Object.} – Map of strings or objects which
will be serialized with the paramSerializer and appended as GET
parameters.
data – {string|Object} – Data to be sent as the request
message data.

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".

Categories