angular js json.stringify to php - javascript

Along with the form values, I need additional data to be passed to the PHP script- I have a javascript function "cart.items()" which returns the stringified items that have been selected in the cart. How do I pass this value to the PHP function?
form.html
<div ng-controller="formCtrl">
<input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
<input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
<input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
<button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)" ng-disabled="userForm.$invalid">Submit </button>
</form>
App.js
controller("formCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.url = 'http://localhost/ShoppingCart/ShoppingCart/email.php';
$scope.formsubmit = function (isValid) {
if (isValid) {
$http.post($scope.url, { 'name': $scope.name, "email": $scope.email, "message": $scope.message, "items": $scope.items }).
success(function (data, status) {
// console.log(data);
$scope.items = "this is scope";
$scope.status = status;
$scope.data = data;
$scope.result = data;
//window.location.assign("email.php");
//alert($scope.items);
})
} else {
alert('Form is not valid');
}
index.php
<?php
$post_date = file_get_contents("php://input");
$echo("I want the result of the cart.items() function here");
?>

To make http call use like this. Change according to your ajax call
var requestSignin = {
method: 'POST',
url: your url,
headers: {
"Content-Type" : "text/plain"
},
data: {
field 1: $scope.signinData.email,
field 2: $scope.signinData.password,
.
.
field n .
},
timeout: 30000
};
$http(requestSignin)
.success(function(data) { console.log(data);
}).errror(){
}
Send your fields in data object.
And your php code should be like this.
$post_date = json_decode(file_get_contents("php://input"));
To get the input from request.
while returning from php use json_encode()
Ex:
echo json_encode($cities);

Related

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

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

ng-model is not working with ng-value in AngularJS

Below is my View page
<form name="form">
<label>Name</label>
<input name="name" type="text" ng-model='user.name' ng-value='emp.name' required />
<span ng-show="form.name.$touched && form.name.$invalid">Name is required</span>
<button ng-disabled="form.name.$touched && form.name.$invalid" ng-click='formUpdate()'>Update</button>
</form>
This is my controller
$scope.formUpdate = function() {
$scope.status = false;
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
});
};
When I am using data: $scope.user in my HTTP call I am getting blank values on console but if I used data: $scope.emp, then I never get updated values of input fields rather getting old values of input fields.
ng-value binds the given expression to the value of the element.
As I understand your question, you are trying to initialize the input value to emp.name.
You should change your input to:
<input type="text" ng-model='user.name' ng-init='user.name = emp.name' required />
ng-init docs
try this code;
$scope.formUpdate = function(){
$scope.status = false;
$scope.$applyAsync();
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
$scope.$applyAsync();
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
$scope.$applyAsync();
});
};

angular js: Error: $ is not defined in http post

I'm trying to post values from a form. Form has two fields- name and email. I have setup the controller as well but when i try to post, error is shown.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
My controller is:
(function() {
angular
.module('myApp.saved', [])
.controller('dataController', function($scope, $http) {
var sap = this;
$scope.post = {};
$scope.post.login = [];
$scope.sap = {};
$scope.index = '';
var url = 'save.php';
sap.saved = function(isValid)
{
if (isValid)
{
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.sap }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response)
{
// success
alert('success');
},
function(response)
{
// failed
alert('failed');
});
}
};
});
})();
When i submit, $ is not defined is shown. I'm pretty much new in angular. Can anyone tell what all mistakes I made?
$ is alias for jQuery and param is a jquery method.
Have you included jQuery?
data: $.param({'user' : $scope.sap }),
should be
data: {
'user': $scope.sap //POST parameters
}
data – {string|Object} – The response body transformed with the transform functions

Accessing Form elements and div from Angular Promise

I am learning angular js. I just want to clear the form fields and show a success div inside a http then().
this.formSubmitted = false;
this.successs = false;
myResumeApp.controller("FormController",['$http', function($http){
this.formSubmit = function(contactForm) {
this.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : this.fname,
email : this.email,
content : this.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
this.successs = true;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}]);
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="formCtrl.successs" class="alert alert-success fade in" style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">Thank you for contacting me. I will be in touch with you shortly.</div>
<form role="form" name="contactForm" novalidate ng-submit="formCtrl.formSubmit(contactForm)">
Please let me know whether there is anything wrong with my code or any other suggestions. The control is coming inside the then() block. But I need to know how to access the successs element and clear the form fields.
Thank you.
Instead of this, use $scope (and add it to dependencies). Right know your successs property is assigned to different objects (window and callback function).
Controller code:
myResumeApp.controller("FormController",[
'$scope',
'$http',
function($scope, $http){
$scope.successs = false;
$scope.formSubmitted = false;
$scope.msg = {};
$scope.formSubmit = function(contactForm) {
$scope.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : $scope.msg.fname,
email : $scope.msg.email,
content : $scope.msg.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
$scope.successs = true;
$scope.msg = {};
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}
]);
HTML code:
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="successs"
class="alert alert-success fade in"
style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">
Thank you for contacting me. I will be in touch with you shortly.
</div>
<form role="form" name="contactForm" novalidate ng-submit="formSubmit(contactForm)">
<input type="text" name="name" ng-model="msg.fname" />
<input type="text" name="email" ng-model="msg.email" />
<input type="text" name="content" ng-model="msg.content" />
<input type="submit" value="submit" />
</form>
You should be able to handle that in successCallback.
... .then(function successCallback(response) {
this.successs = true;
contactForm.reset()
}, ...
Also I don't think that this inside successCallback is same as in line where you initialize this.formSubmitted = false;...

Is there a more effective way to serialize a form with angularjs?

Is there a way to serialize function for angularjs?
my post looks like this right now.
$scope.signup_submit = function () {
var formData = {
username: $scope.username,
full_name: $scope.full_name,
email: $scope.email,
password: $scope.password,
confirm_password: $scope.confirm_password
}
$http({
method: "POST",
url: '/signup',
data: formData,
}).success(function (data) {
if (data.status == 'success') {
alert('all okay');
} else {
alert(data.msg)
}
});
}
This isn't how you should access form data using AngularJS. The data in your form should be bound within the scope.
So use an object, e.g. $scope.formData, which will contain all your data structure, then each of your form elements should be bound to this using ng-model.
e.g:
http://jsfiddle.net/rd13/AvGKj/13/
<form ng-controller="MyCtrl" ng-submit="submit()">
<input type="text" name="name" ng-model="formData.name">
<input type="text" name="address" ng-model="formData.address">
<input type="submit" value="Submit Form">
</form>
function MyCtrl($scope) {
$scope.formData = {};
$scope.submit = function() {
console.log(this.formData);
};
}
When the above form is submitted $scope.formData will contain an object of your form which can then be passed in your AJAX request. e.g:
Object {name: "stu", address: "england"}
To answer your question, there is no better method to "serialize" a forms data using AngularJS.
You could however use jQuery: $element.serialize(), but if you want to use Angular properly then go with the above method.

Categories

Resources