Submitting angular form to a php file [duplicate] - javascript

This question already has answers here:
How do I POST urlencoded form data with $http without jQuery?
(11 answers)
Closed 6 years ago.
I'm trying to submit the form below to a php file called time.php, but its not working, even when I check the console there are no errors, its just clear. I'm not sure where I may be going wrong.
<form ng-controller="testCtrl" class="customform" data-ng-init="init()">
<div class="s-10 1-10">
<input ng-model="firstName" pattern=".{2,100}" title="2 to 100 Characters" placeholder="First Name" type="text" required />
</div>
<div class="s-10 1-10">
<input ng-model="lastName" pattern=".{5,255}" title="5 to 255 Characters" placeholder="Last Name" type="text" required />
</div>
<div class="s-12 l-10"><input ng-model="acNumber" placeholder="A/C Number" title="Employee Number, i.e c1234567" type="text" required /></div>
<div class="s-12 l-10"><input ng-model="email" placeholder="Email" title="Email" type="email" required /></div>
<div class="s-12 l-10">
<select ng-model="selectedRequestType" ng-options="requestType as requestType.type for requestType in requestTypes" required="required">
<option value="" disabled selected>Request Type</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedRequestType.type == 'Work Request'" ng-model="selectedWorkRequestType" ng-options="workRequestType as workRequestType.type for workRequestType in workRequestTypes">
<option value="" disabled selected>Work Request Type</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'New file(s) from source'" ng-model="selectedFile" ng-options="file as file.type for file in files">
<option value="" disabled selected>Files</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'New file(s) from source'" ng-model="selectedLibrary" ng-options="library as library.type for library in libraries">
<option value="" disabled selected>Does Library Exist</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'Code Automation' || selectedWorkRequestType.type == 'Amendments to existing code'" ng-model="selectedOutput" ng-options="outputType as outputType.type for outputType in outputTypes">
<option value="" disabled selected>Output</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedLibrary.type == 'Yes' || selectedRequestType.type == 'Incident'" ng-model="selectedPlatformOutput" ng-options="platformOutput as platformOutput.type for platformOutput in platformOutputs">
<option value="" disabled selected>Platform Output</option>
</select>
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'SAS' || selectedPlatformOutput.type =='SAS'" ng-model="sasLibraryName" type="text" placeholder="SAS Library Name: SPDS Exploit" />
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'SAP IQ' || selectedPlatformOutput.type =='SAP IQ'" ng-model="sapIQtext" placeholder="SAP IQ" >
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'Hadoop' || selectedPlatformOutput.type =='Hadoop'" placeholder="Library Name: HDFS_Exploit" ng-model="hadoop" />
</div>
<div class="s-12 l-10">
<input ng-show="selectedWorkRequestType.type == 'Amendments to existing code'" placeholder="Output Dataset Name" ng-model="outputDataset" type="text"/>
</div>
<div class="s-12 l-10">
<input ng-show="selectedLibrary.type == 'No'" type="text" ng-model="productName" Placeholder="Product Name" />
</div>
<div class="s-12 l-10">
<input ng-show="" placeholder="Upload Text File" type="file" ng-model="uploadTextFile" title="Please upload a txt file with the layout - to " multiple />
</div>
<div class="s-12 l-10">
<input ng-show="selectedRequestType.type == 'Incident'" type="text" ng-model="tableName" placeholder="Dataset/Table Name" />
</div>
<div class="s-12 l-10">
<textarea placeholder="Special Instructions" ng-model="specialInstruction" rows="5"></textarea>
</div>
<div class="s-12 l-10">
<input ng-show="selectedRequestType.type == 'Incident'" ng-model="uploadScreenshot" placeholder="Upload Screenshot of error" type="file" multiple/>
</div>
<div class="s-12 l-10">
<select ng-show="selectedRequestType.type == 'Work Request'" ng-model="selectedFrequency" ng-options ="frequency as frequency.type for frequency in frequencies">
<option value="" disabled selected>Frequency</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedFrequency.type == 'Weekly'" ng-model="selectedWeekly" ng-options ="weekly as weekly.type for weekly in weeklies">
<option value="" disabled selected>Weekly Frequency</option>
</select>
</div>
<input type="hidden" ng-model="token" value="<?php echo Token::generate()?>">
<div class="s-4"><button type="submit" id="submit" class="btn-custom btn btn-large btn-block" ng-click="sendRequest()">Request</button></div>
Please note: ng-app="app" is located in the header:
<!DOCTYPE html>
<html lang="en-US" ng-app="app">
The following code is the controller, and I believe the issue lies somewhere in here:
var app = angular.module('app', []);
app.controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sendRequest = function(){
var data= {
'firstName' :$scope.firstName,
'lastName' :$scope.lastName,
'acNumber' :$scope.acNumber,
'email' :$scope.email,
'selectedRequestType' :$scope.selectedRequestType,
'selectedWorkRequestType' :$scope.selectedWorkRequestType,
'selectedOutput' :$scope.selectedOutput,
'selectedFrequency' : $scope.selectedFrequency,
'selectedWeekly' : $scope.selectedWeekly,
'selectedFile' : $scope.selectedFile,
'selectedLibrary' : $scope.selectedLibrary,
'selectedPlatformOutput' : $scope.selectedPlatformOutput,
'productName' : $scope.productName
};
$http({
url: "time.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).success(function(data, status, headers, config) {
//Success code
}).error(function(xhr) {
//Failure code
console.log(data);
console.log(xhr.responseText);
});
return false;
// $window.location.href ='/time.php';
};
$scope.init = function (){
$scope.workRequestType = 'test';
$scope.requestTypes = [
{'type':'Work Request'},
{'type': 'Incident'}
];
$scope.workRequestTypes = [
{'type': 'Amendments to existing code'},
{'type': 'Code Automation'},
{'type': 'New file(s) from source'}
];
$scope.outputTypes = [
{'type': 'SAS'},
{'type':'SAP IQ'},
{'type': 'Hadoop'}
];
$scope.frequencies = [
{'type' : 'Daily'},
{'type': 'Monthly'},
{'type': 'Weekly'}
];
$scope.weeklies = [
{'type': 'Monday'},
{'type':'Tuesday'},
{'type': 'Wednesday'},
{'type':'Thursday'},
{'type':'Friday'},
{'type':'Saturday'},
{'type':'Sunday'}
];
$scope.files = [
{'type': 'New File(s)'},
{'type': 'Add to existing file received'}
];
$scope.libraries = [
{'type':'Yes'},
{'type':'No'}
];
$scope.platformOutputs = [
{'type': 'SAS'},
{'type':'SAP IQ'},
{'type': 'Hadoop'}
];
$scope.firstName= null;
$scope.lastName= null;
$scope.acNumber= null;
$scope.email= null;
$scope.selectedRequestType= null;
$scope.selectedWorkRequestType= null;
$scope.selectedOutput= null;
$scope.sasLibraryName = null;
$scope.sasIQtext = null;
$scope.selectedFrequency = null;
$scope.selectedWeekly = null;
$scope.selectedFile = null;
$scope.selectedLibrary = null;
$scope.selectedPlatformOutput = null;
$scope.productName = null;
};
}]);
I'm still learning Angular, so I may have made a simple error

If the HTTP POST request is taking place, but PHP is not able to access the POST variables, try converting the data from an object to a string.
$http({
url: "time.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(data),
})
The string should look like: firstName=John&acNumber=1234
Pass the $httpParamSerializerJQLike service into your controller with:
app.controller('testCtrl', ['$scope', '$http', '$httpParamSerializerJQLike', function($scope, $http, $httpParamSerializerJQLike) {

Related

How to Submit a Form by using a button at the same time click event on anchor link?

I have a from with button to submit it. Now i would like to pass same variables to another page to inset them in database. For that, i would like to pass the variables using an anchor link with GET with id's.
But how do it add an anchor link to the form where when i submit the form using the button the anchor link also gets triggered..
function splitAndResolve() {
var errorIds = [];
$('[name="error-selection-checkboxes"]:checked').each(function() {
errorIds.push($(this).val().split("-")[1]);
});
var taskVersion = 1;
if (errorIds.length > 0 && errorIds.length < $('[name="error-selection-checkboxes"]').length) {
var dataObj = {
'errorReportIdsToRemove': errorIds,
'user': 'user#mail.com'
};
var baseUrl = $(location).attr("href").substring(0, $(location).attr("href").lastIndexOf('/') + 1);
var splitTaskResponse = $.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70/split",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
}).responseJSON;
var taskId = splitTaskResponse.newTaskId;
// We need to update the version without which version on the UI and the DB are different.
taskVersion = splitTaskResponse.currentTaskPostSplit.version;
window.open(baseUrl + taskId, '_blank');
}
dataObj = {
'taskResolutionStatus': $("#inputResolution").val(),
'taskResolutionStatusDetail': $("#inputResolutionDetail").val(),
'taskResolutionNote': $("#inputNotes").val(),
'changeset': $("#inputChangeset").val(),
'requiresReview': $("#requiresReviewCheckBox").is(':checked'),
'version': taskVersion
};
$.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
});
enableStatusDropdown();
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal clearfix" onsubmit="return splitAndResolve()">
<div class="form-group">
<label for="changeset" class="col-sm-2 control-label">Changeset</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="changeset" id="inputChangeset" readonly="">
</div>
</div>
<div class="form-group">
<label for="taskResolutionStatus" class="col-sm-2 control-label">Resolution</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatus" id="inputResolution">
<option disabled="" selected="" value=""> -- Choose one -- </option>
<option value="ESCALATE">Escalate</option>
<option value="ALREADY_FIXED_IN_OSM">Already fixed in osm</option>
<option value="NOT_ENOUGH_INFORMATION">Not enough information</option>
<option value="NO_FIX_REQUIRED">No fix required</option>
<option value="FIXED">Fixed</option>
</select>
</div>
</div>
<div class="form-group" id="inputResolutionDetailDropdown">
<label for="taskResolutionStatusDetail" class="col-sm-2 control-label">Detail</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatusDetail" id="inputResolutionDetail">
<option value="LOW_PRIORITY_AREA">Low priority area</option>
<option value="KNOWN_BUG">Known bug</option>
<option value="ERROR_BASED_ON_BAD_DATA">Error based on bad data</option>
<option value="TRUE_EXCEPTION">True exception</option>
</select>
</div>
</div>
<div class="form-group">
<label for="taskResolutionNote" class="col-sm-2 control-label">Notes</label>
<div class="col-sm-10">
<textarea class="form-control" name="taskResolutionNote" id="inputNotes" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="requiresReview" class="col-sm-2 control-label">Requires review</label>
<div class="col-sm-2">
<input class="form-control" name="requiresReview" type="checkbox" style="box-shadow: none" id="requiresReviewCheckBox">
</div>
</div>
<input id="taskResolutionButton" type="submit" class="btn btn-primary">
<button id="taskCancelButton" type="button" class="btn btn-default" onclick="hideResolutionOverlay()">Cancel</button>
</form>
<input id="taskResolutionButton" type="submit" class="btn btn-primary" onclick="$('#your_form_id').submit();>

How to set the object value in ng-model, in select tag, from an object array. and is there an easy way to add filters on ng-options,

Here is my html :
<body ng-controller="myCtrl">
{{loadDataSubject('${subjectList}')}}
{{loadDataTopic('${topicList}')}}
<h1 class = "bg-success" style="color: red;text-align: center">Fill in the below details for Question Template : -</h1> <br>
<div class="container">
<form method="get" action="createTemplate">
<div class="form-group">
<label for="sel1">Topics (select one):</label>
<select class="form-control" ng-model="selectedTopic" ng-options="topic.name as topic.name for topic in topics">
</select> <br>
{{selectedTopic}}
<label for="sel1">Subject (select one):</label>
<select name="subject" value= "" class="form-control" ng-model ="selectedSubject" ng-options="sub.name as sub.name for sub in subjects">
</select> <br>
<label for="sel1">Negative marking:</label>
<select class="form-control" name="negativeMarks">
<option>Yes</option>
<option>No</option>
</select> <br>
<label>Reference Book:</label>
<input type="text" class="form-control" name="ref" required>
<label for="sel1">Number of Questions:</label>
<input type="number" class="form-control" name="questionCount" required><br>
<input class ="bg-primary" type="submit" value="submit and download template">
</div>
</form>
</div>
</body>
and here is the script :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.subjects = [];
$scope.topics = [];
$scope.selectedSubject = {};
$scope.selectedTopic = {};
$scope.loadDataSubject = function(subjectList) {
$scope.subjects = JSON.parse(subjectList);
};
$scope.loadDataTopic = function(topicList) {
$scope.topics = JSON.parse(topicList);
};
});
I want to add a filter to options to selectonly the subjects of selected Topic,
something like filter : selectedTopic.id
Error is
angular.js:38 Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.4.8/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…turn%20b(f%2Cc%2Ce)%7D%22%2C%22newVal%22%3A74%2C%22oldVal%22%3A68%7D%5D%5D
at angular.js:38
at r.$digest (angular.js:15934)
at r.$apply (angular.js:16160)
at angular.js:1679
at Object.e [as invoke] (angular.js:4523)
at c (angular.js:1677)
at yc (angular.js:1697)
at Zd (angular.js:1591)
at angular.js:29013
at HTMLDocument.b (angular.js:3057)
before that i want to bind the value of object to ng-model, while the objects name gets binded. Please help me, I'm new with this.
subjects:
[{"subjectId":1,"name":"ComputerScience","code":"CS"},{"subjectId":2,"name":"Computer Basics","code":"CS","documentUrl":"None"},{"subjectId":3,"name":"Computer Basics","code":"CS","documentUrl":"None"},{"subjectId":4,"name":"php","code":"PHP01","documentUrl":"None"},{"subjectId":5,"name":"JAVA","code":"JAVA01","childSubjects":[{"subjectId":6,"name":"Core Java","code":"JAVA02","parentSubject":5,"childSubjects":[{"subjectId":8,"name":"Thread","code":"JAVA04","parentSubject":6},{"subjectId":9,"name":"Object Class","code":"JAVA05","parentSubject":6},{"subjectId":10,"name":"Inheritance","code":"JAVA06","parentSubject":6}]},{"subjectId":7,"name":"Advance Java","code":"JAVA03","parentSubject":5,"childSubjects":[{"subjectId":11,"name":"Servlet","code":"JAVA07","parentSubject":7}]}]},{"subjectId":12,"name":"Computer Basics","code":"CS","documentUrl":"None"}]
topics:
[{"topicId":1,"name":"Technical","code":"TECH","isSubjectsRelated":1,"description":"All Technical subjects","isActive":1,"subjects":[{"subjectId":1,"name":"ComputerScience","code":"CS"},{"subjectId":1,"name":"ComputerScience","code":"CS"}]},{"topicId":2,"name":"GATE","code":"GATE","isSubjectsRelated":1,"description":"GATE exam","isActive":1,"subjects":[]},{"topicId":5,"name":"Programming","code":"PROG","isSubjectsRelated":0,"description":"Coding skills","isActive":1,"subjects":[{"subjectId":5,"name":"JAVA","code":"JAVA01"}]}]
Change your Topics select-box to this
<label for="sel1">Topics (select one):</label>
<select class="form-control" ng-model="selectedTopic" ng-options="topic as topic.name for topic in topics">
</select>
And similarly for subject selectbox.Check out this plunker.

How to send data through ajax function to php file?

I want to call one addPost.php file through ajax function, and return the result as post submitted or not.
For that I am calling userAction function onClick of a button but now I am not getting the data through post, when I tried to access the post array data in addPost.php file its sending the error as undefined index category.
Can anyone please help what is going wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<form class="postForm" id="postForm" method="post" action="addPost.html">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url">
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<p>
Select Url Type :
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<option value="0">Server Image</option>
<option value="1">Server Video</option>
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
<p>
Select Category :
<select name="category" id="category">
</select>
</p>
<p>
<input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">
</p>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
getCategories();
function getCategories() {
$.ajax({
type: "POST",
url: 'getCategories.php',
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#category').html(result);
}
});
}
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#postForm").find('.form').serialize() + '&action_type=' + type + '&id=' + id;
}
$.ajax({
type: 'POST',
url: 'addPost.php',
data: userData,
success:function(report){
alert(report)
}
});
}
</script>
</form>
</body>
</html>
addPost.php
include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {
if($_POST['action_type'] == 'add') {
/* $database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbConnection->prepare("insert into keywords(keyword)
values(?)");
$stmt->execute(array($_POST['keywords']));
//insert data into posts table
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords)
values(?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords']));
$count = $stmt->rowCount();
if ($count > 0) {
//if inserted
$response = array("status" => -1, "message" => "Post Submitted");
return $response;
} else {
//if not inserted
$response = array("status" => -1, "message" => "Could not submit post.");
return $response;
}*/
echo $_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'];
}
}
EDIT :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<form class="postForm" id="postForm" method="post" action="addPost.php">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url" required>
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<p>
Select Url Type :
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<option value="0">Server Image</option>
<option value="1">Server Video</option>
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
<p>
Select Category :
<select name="category" id="category">
</select>
</p>
<p>
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
<input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">
</p>
<p id="report"></p>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
getCategories();
$("#postForm").validate();
function getCategories() {
$.ajax({
type: "POST",
url: 'getCategories.php',
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#category').html(result);
}
});
}
function userAction(type,id){
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
if (type == 'add') {
$('#action_type_id').val(type);
$('#p_id').val(id);
}
$.ajax({
type: 'POST',
url: 'addPost.php',
data: $('#postForm').serialize(),
success:function(report){
$('#report').html(result);
}
});
}
</script>
</form>
</body>
</html>
Now By this edit code the data is getting insert in the database but I want to show the result in para in add.html so I have given the id of para in success method but this is not working, also form validation is not working.
Please help. Thank you.
You can use hidden value to send data in server.In your form place this two fields.
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
And your ajax method will be like:
function userAction(type,id){
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
if (type == 'add') {
$('#action_type_id').val(type);
$('#p_id').val(id);
}
$.ajax({
type: 'POST',
url: 'addPost.php',
data: $('#postForm').serialize(),
success:function(report){
alert(report);
}
});
}
Explanation: Before submitting the form, you set type and id value to hidden field and send the entire form to server.now you can able to get all post data by $_POST['action_type'] and $_POST['id'].
echo $_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords']
in this statement, you are trying to access "category", "title" etc. But you have not passed that fields in ajax(userdata), so you got "undefined index category" - this error

Generate dynamic form input fields and collect field data in an array in angularJS

I need to generate form input fields dynamically by clicking 'add sale' button on the form. which is accomplished
Also on change selected drop down, it get the price from the database and use the quantity to calculate the amount of that product.
if I click on 'add sale' button for another form generate the changes affect the previous one.
how to calculate the amount for each form independently and collect the data in it using angularJS?
this is controller
appcat.controller("MainCtrl", ['$scope', '$http', '$location', function ($scope, $http, $location)
{
//var quan = $scope.quantity;
$http.get('/api/pproduct').success(function (data)
{
$scope.pcategoryA = data;
});
// this controll the addition and removal
$scope.choices = [{ id: 'choice1' }];
//any time changes occurr it calculate the Amount
$scope.changedValue = function (item,quan)
{
if (item != null && quan !=null)
{
$http.get('/api/product/'+ item).success(function (data) // this is the price for that product from the Database
{
//this sets amount field
$scope.amount = parseFloat(data.price * quan);
});
}
}
// this generate a form
$scope.addNewChoice = function ()
{
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({ 'id': 'choice' + newItemNo });
};
// this remove the form
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if ($scope.choices.length > 1) {
$scope.choices.splice(lastItem);
}
};
}]);
this is the html
<form class="form-inline" role="form" padding-left:10em">
<strong class="error">{{ error }}</strong>
<div class="form-group">
<label for="name">
Invoice No. :
</label>
<input type="text" class="form-control" id="name" ng-model="name" />
</div>
<br /><hr />
<div ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<div class="form-group">
<label for="name">
Quantity :
</label>
<input type="text" class="form-control" id="quantity" ng-model="quantity" />
</div>
<div class="form-group">
<div class="form-group">
<label class="control-label"> Product : </label>
<select class="form-control" id="selected_id" ng-model="selected_id" ng-options="c.Value as c.Text for c in pcategoryA"
ng-change="changedValue(selected_id,quantity)">
<option value="">-- Select Category --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name">
Amount :
</label>
<input type="text" class="form-control" id="amount" ng-model="amount" ng-readonly="true" />
</div>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
<br />
<hr />
</fieldset>
<button type="submit" class="col-sm-offset-10 addfields" ng-click="addNewChoice()">
Add Sale
</button>
</div>
</form>
thanks in advanced!!
You have to put 'amount' in choices array.
$scope.choices = [{ id: 'choice1', amount: 0}];
Then in controller:
$scope.changedValue = function (choise,item,quan)
choise.amount = parseFloat(data.price * quan);
And in tempalte:
ng-change="changedValue(choise,selected_id,quantity)">
<input type="text" class="form-control" id="amount" ng-model="choise.amount" ng-readonly="true" />

How to post additional data within the scope of angular-payments

I'm trying to build a donation form using angular-payments and sending the data to an Expressjs server.
Currently I'm having trouble getting my form to post data other than the data that angular-payments sends. How can a post data that's not part of the angular-payments scope using the same controller?
Here is my Angular script:
angular.module('donate', ['angularPayments'])
function DonateCtrl($scope, $http) {
$scope.handleStripe = function(status, response){
console.log('response', status, response);
if(response.error) {
console.log('error');
// there was an error. Fix it.
} else {
// got stripe token, now charge it or smt
console.log('no error');
var token = response.id;
console.log(token);
return $http.post('http://localhost:8181/api/payments', response)
}
}
};
And here's the HTML:
<form stripe-form="handleStripe" name="donateForm">
<h3>Credit Card Details</h3>
<label for="">Card number</label>
<input type="text" name="number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="donateForm.number.$card.type" placeholder="4500 0000 0000 0000" />
<label for="">Expiry</label>
<input type="text" ng-model="expiry" payments-validate="expiry" payments-format="expiry" placeholder="01 / 99" />
<label for="">CVC</label>
<input type="text" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type" placeholder="123" />
<h3>Donor Details</h3>
<label for="name">Name on card </label>
<input type="text" name="name" ng-model="name" placeholder="John Smith">
<label for="address">Street Address</label>
<input type="text" name="address" ng-model="addressLine1" placeholder="123 Any Street" required/>
<input type="text" name="city" ng-model="addressCity" placeholder="Anytown" required />
<input type="text" name="province" ng-model="addressState" placeholder="Any Province" ng-required="addressCountry == 'Canada' || addressCountry == 'United States'" />
<select data-placeholder="Choose a Country" name="country" ng-model="addressCountry" required>
{% include 'includes/countryselect' %}
</select>
<input type="text" name="postcode" ng-model="addressZip" placeholder="A1B 2C3" ng-required="addressCountry == 'Canada' || addressCountry == 'United States'" />
<div ng-show="donateForm.addressLine1.$pristine && donateForm.addressLine1.$invalid || donateForm.addressCity.$pristine && donateForm.addressCity.$invalid || donateForm.addressState.$pristine && donateForm.addressState.$invalid || addressCountry.$pristine && addressCountry.$invalid || donateForm.addressZip.$pristine && donateForm.addressZip.$invalid" class="help-block">Enter your full home address.</div>
<label for="phone">Phone Number <small>(include country & area code)</small></label>
<input type="tel" name="phone" ng-model="phone" placeholder="+1 204-555-5555" required />
<div ng-show="donateForm.phone.$invalid && donateForm.phone.$pristine" class="help-block">Enter your phone number.</div>
<label for="email">Email Address</label>
<input type="email" name="email" ng-model="email" placeholder="johnsmith#email.com" required />
<div ng-show="donateForm.email.$invalid && donateForm.email.$pristine" class="help-block">Enter your email address.</div>
<button type="submit">Submit</button>
When you say post additional data, do you mean send data with the POST request?
This is how I do it as an example:
$http({
url: 'http://localhost:8181/api/payments',
method: 'POST',
data: {
key: value,
key2: value
}).success(function(data) {
// If successful
}).error(function(data) {
// If error
return data.message;
});

Categories