How To save users feed data in database in my custom form in WordPress? - database

I have created a custom form in my project and also create mail functionality for it. Now i want to save all the data post by users in database how do i achieve it?
Here is my Form:
<form id="formMy">
<input name="txtFirstName" type="text" required placeholder="Name" id="txtFirstName">
<input name="PopupContact_email" type="email" required placeholder="E-Mail Address" id="requestemail">
<input name="txtOrganisationName" type="text" required placeholder="Company/ Institute Name" id="requestcompany">
<input type="hidden" name="hiddenform">
<button class="btn btn-primary btn-lg bbtn" data-toggle="modal" data-target="#myModal" style="display:none;">
Launch demo modal
</button>
<button type="button" class="btn btn-inverse" style="vertical-align:top;" name="submit" onClick="ajaxFormSubmit2();">Request a Demo</button>
</form>
And this is my ajax code:
<script>
function ajaxFormSubmit2(){
var txtFirstName = jQuery('#txtFirstName').val();
var requestemail = jQuery('#requestemail').val();
var requestcompany = jQuery('#requestcompany').val();
var atpos=requestemail.indexOf("#");
var dotpos=requestemail.lastIndexOf(".");
if(txtFirstName=="" || requestemail=="" || requestcompany==""){
jQuery('.alertred').show();
jQuery(".alertred").delay(10000).hide(0);
jQuery('.alertred').html('<strong>Error!</strong> Please Fill out all the fields.');
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=requestemail.length)
{
jQuery('.alertred').show();
return false;
}
else
{
jQuery.post("<?php echo get_bloginfo('template_directory').'/mail2.php'; ?>",{txtFirstName:txtFirstName,requestemail:requestemail,requestcompany:requestcompany},function(r){
if(r=="success"){
jQuery('.success').show();
}
});
}
}
</script>

You can get all the form data using formId_specifier.serialize() method. And you get this in your php file like this one example for you.
JS Code::
$(document).on('submit', 'form#form_id',function(){
$.post(
MyAjax.ajax_url,{
action: AJAX_FILE_URL,
data: me.serialize()
}, function(response){
// Handle after getting response
}
);
});
In php code you can get form date using this code:
parsestr($_POST['data'], $form_data); // now all form data is assign to $form_data

Related

Save every scope from a Form in a service Angularjs

I would like to save my datas from my form to my service function setData(), but I am not sure how to do it. I have already done the service, the setData() function, and my form.
Form
<form id="eventForm" data-toggle="validator" class="text-left" role="form" name="form.eventForm">
<div class="form-group col-md-12">
<input type="text" ng-model="form.return" name="RT" id="return"> Return
<input type="text" ng-model="form.oneway" name="OW" id="oneway"> One way
</div>
<button name="submit" class="btn btn-default ng-click="form.$valid && submit()">Pay now</button>
</form>
AngularJS submit method
$scope.submit = function() {
FormData.setData($scope.form);
$location.path("/flights");
}
Service setData()
this.data = JSON.parse(sessionStorage.getItem("flights") || '{}');
this.setData = function(data) {
this.data = data;
sessionStorage.setItem("flights", JSON.stringify(data));
}
this.getData = function() {
return this.data;
}
I don't know how should I pass my whole data from my Form to setData() function.
Try changing the submit button to disable on an invalid form, and set the submit action to send the form object. Then, in the controller, set the function to accept an argument (the form data), and use that.
HTML
<form id="eventForm" data-toggle="validator" class="text-left" role="form" name="form.eventForm">
<div class="form-group col-md-12">
<input type="text" ng-model="form.return" name="RT" id="return"> Return
<input type="text" ng-model="form.oneway" name="OW" id="oneway"> One way
</div>
<button name="submit"
class="btn btn-default
ng-disabled="form.$invalid"
ng-click="submit(form)">
Pay no
</button>
</form>
JS
$scope.submit = function(submitData) {
FormData.setData(submitData);
$location.path("/flights");
}

AngularJS error: TypeError: v2.login is not a function

I would like to call the login function when I click the login button but keep getting the error message in the title. Can someone point out the error in my script?
login.js code below:
/*global Firebase, angular, console*/
'use strict';
// Create a new app with the AngularFire module
var app = angular.module("runsheetApp");
app.controller("AuthCtrl", function ($scope, $firebaseAuth) {
var ref = new Firebase("https://xxxxx.firebaseio.com");
function login() {
ref.authWithPassword({
email : "xxxxx",
password : "xxxx"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
And the code for login.html is also below:
<div class="container" style="max-width: 300px">
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
</div>
Edge case here, but I want to mention it for posterities' sake. I got this same error when using the controllerAs pattern with a form name with the same value as ng-submit. For example:
<form name="authCtrl.signUp" ng-submit="authCtrl.signUp()">
Throws: TypeError: v2.signUp is not a function
The solution was to change the name of the form to something different:
<form name="authCtrl.signUpForm" ng-submit="authCtrl.signUp()">
In my case, I was having an exact same issue as yours. However, coming across gkalpak's answer to such a scenario helped me out.
Turned out to be what I was calling was addBuddy() function, from a form named "addBuddy". The solution was to change the name of either of the two things to make one stand out or differentiable from the other. I changed the name of the form to "addBuddyForm" and voila! My function worked!
Here's a snippet of my case:
<form name="addBuddy" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
Which, I changed to:
<form name="addBuddyForm" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
...and it worked! :)
In AngularJS call the function from view it must be in the $scope.
JS
// exposes login function in scope
$scope.login = login;
HTML
<div class="container" ng-controller="AuthCtrl" style="max-width: 300px"> <!-- I notice here for include ng-controller to your main div -->
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
This may not be specific to your problem, but I was also getting this error and it took a bit to figure out why.
I had named both a function and a variable the same, with the variable assigned in the function, and so the assignment of the variable was overriding the function and it was exploding on a second run.
You'll notice in the example the uploadFile() function as an upload.uploadFile = true; This was a wonderful file that was meant to be upload.uploadingFile - a flag used to control the behavior of a spinner. Once that was fixed, the issue went away.
Example:
(function()
{
'use strict';
angular.module('aumApp.file-upload')
.controller('FileUploadCtrl', FileUploadCtrl);
function FileUploadCtrl($scope, $http)
{
upload.uploadFile = function()
{
upload.uploadFile = true;
var backendUrl = '/ua_aumcore/events/api/v1/events/uploadFile';
var fd = new FormData();
fd.append('file', upload.src);
$http({ url: backendUrl, data: fd, method: 'POST', transformRequest : angular.identity, headers: { 'Content-Type' : undefined } })
.then(function uploadSuccess(response)
{
upload.data = response.data;
upload.message = "Uploaded Succesfully.";
upload.uploadSuccess = true;
upload.uploadingFile = false;
},
function uploadFailure(response)
{
upload.message = "Upload Failed.";
upload.uploadSuccess = false;
upload.uploadingFile = false;
});
};
}
FileUploadCtrl.$inject = ['$scope', '$http'];
})();
To be callable from the view, a function must be in the $scope. Add
$scope.login = login;
to the JS code of the controller.
You also need to actually use that controller. Change
<div class="container" style="max-width: 300px">
to
<div ng-controller="AuthCtrl" class="container" style="max-width: 300px">
This is all fundamental stuff. My advice would be to learn from an AngularJS tutorial before going further.
Two enable two-way binding you have to assign your login function to $scope. Replace your code for function with this:
$scope.login=function() {
ref.authWithPassword({
email : "nick.koulias#gmail.com",
password : "Jaeger01"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
It may be a late answer by me.
But It working for me
Check form name you set
e.g. ng-form="login"
and function name
e.g. ng-click="login()"
Then it will not work . You have to change one of them.
e.g. ng-form="loginForm"
Explanation:
AngularJS 1.x registers any form DOM element that has a name property in $scope via formDirectiveFactory. This directive automatically instantiates form.FormController if the above is true:
If the name attribute is specified, the form controller is published onto the current scope under
from: angular.js:24855
Hence if you have a <form name=myForm> it will override your $scope.myForm = function() { ... }

Adding hidden form field to array in Angular

I am trying to add a "hidden" field to a basic form in Angular (using Firebase as the backend). I'm having trouble figuring out how to include this field as part of the array when the form is submitted. I want to include {type: 'Basic'} as part of the array. I've looked at the other related posts on this site, but am still unsure how to apply to my particular situation.
Any suggestions on how to do this?
Javascript:
myApp.controller('NewProjectCtrl', function ($location, Projects) {
var editProject = this;
editProject.type = 'Basic'; //this is the hidden field
editProject.save = function () {
Projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
});
HTML:
<form>
<div class="control-group form-group">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name">
</div>
<label>Description</label>
<textarea name="description" class="form-control" ng-model="editProject.project.description"></textarea>
<button ng-click="editProject.save()" class="btn btn-primary">Save</button>
</form>
You don't need a hidden form field, just submit your value in your controller like this:
editProject.save = function () {
editProject.project.type = 'Basic';
Projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
All attributes of your editProject.project will be submitted, as you may notice in the developer console.
I would structure the controller a bit different.. here is an example (I am considering you are using angular-resource, where Projects returns a Resource?):
myApp.controller('NewProjectCtrl', function ($location, Projects) {
$scope.project = new Projects({type: 'Basic'});
$scope.save = function () {
$scope.project.$save().then(function(data) {
$location.path('/');
});
};
});
<form ng-submit="save()">
<div class="control-group form-group">
<label>Name</label>
<input type="text" name="name" ng-model="project.name">
</div>
<label>Description</label>
<textarea name="description" class="form-control" ng-model="project.description"></textarea>
<input type="submit" value="Save" class="btn btn-primary" />
</form>
The save function will $save the new project resource (this is an default method and will make a POST on the given resource URL).

AngularJS form validations with submit and reset buttons

I have a simple form where I have applied AngularJS validation on a input box containing number value. On submit, it works fine but when I click on Reset button, it gives the input box validation error message. Looks like it is calling ng-submit after ng-click of Reset button. I have tried resetting the value of input field in ng-click, removed type='Reset' and also used $setPristine() on the form. But nothing helps. Below is the code.
<form name="myForm" novalidate ng-submit="submitFilter()">
Enter Age:
<div>
<input name="age" ng-class="{errorinput: submitted && myForm.age.$invalid }" class="form-control" ng-pattern="/^[0-9]+$/" placeholder="Age" type="text" ng-model="age" required>
</div>
<span class="error" ng-style="{color:'red'}" ng-show="submitted && myForm.age.$invalid">Please enter a valid Age</span>
<button type="submit">
Submit
</button>
<button ng-click="reset(myForm)">
Reset
</button>
</form>
Controller:
var original = $scope.age;
$scope.submitFilter = function () {
if ($scope.filterForm.$valid) {
} else {
$scope.submitted = true;
}
};
$scope.reset = function (myForm) {
$scope.age = angular.copy(original);
$scope.myForm.$setPristine();
};
Kindly help in getting rid of this error.
Thanks in Advance.
Setting the reset button's type as 'button' should work. Following code works perfectly on my machine.
// Code goes here
app.controller('mainController', function($scope) {
$scope.age = 123;
var original = $scope.age;
$scope.submitFilter = function () {
$scope.submitted = true;
};
$scope.reset = function (myForm) {
$scope.age = angular.copy(original);
$scope.myForm.$setPristine();
};
});
<form name="myForm" novalidate ng-submit="submitFilter()">
Enter Age:
<div>
<input name="age" ng-class="{errorinput: submitted && myForm.age.$invalid }" class="form-control" ng-pattern="/^[0-9]+$/" placeholder="Age" type="text" ng-model="age" required>
</div>
<span class="error" ng-style="{color:'red'}" ng-show="submitted && myForm.age.$invalid">Please enter a valid Age</span>
<button type="submit">
Submit
</button>
<button type="button" ng-click="reset(myForm)">
Reset
</button>
</form>

Input text not being cleared out

I'm trying to clear an input text after saving some data but it just doesn't work. This is what I've tried so far (what it's in comments too):
Thanks in advance for any help!
HTML:
<div id="add-tag">
<h3>Add new tag</h3>
<form name="addTagForm">
<input class="form-control" type="text" ng-model="newTag" ng-change="onChangeTag()">
<button class="btn btn-primary" ng-click="addTag(newTag)">Add Tag</button>
</form>
</div>
JS:
//$scope.master = {};
// Reset scope
$scope.reset = function() {
$scope.newTag = "";
//$scope.newTag = angular.copy($scope.master);
};
$scope.addTag = function(tag) {
// Save some data (this works fine)
// ....
// Reset input field
$scope.reset();
};
UPDATE:
My ng-controller was set to the parent template (I'm using ui.router). Just added it to the child template and it indeed worked.
<div id="add-tag" ng-controller="FormController">
<h3>Add new tag</h3>
<form name="addTagForm">
<input class="form-control" type="text" ng-model="newTag" ng-change="onChangeTag()">
<button class="btn btn-primary" ng-click="addTag(newTag)">Add Tag</button>
</form>
</div>
I am new in angularjs but after trying some thing i got some sort of solution for you. You can check this bin. I have just added a controller :-
function test_c($scope){
$scope.reset = function() {
$scope.newTag = "";
//$scope.newTag = angular.copy($scope.master);
};
$scope.addTag = function(tag) {
// Save some data (this works fine)
// ....
// Reset input field
$scope.reset();
};}
Look at the html part:-
<body ng-app>
<div id="add-tag" ng-controller="test_c">
<h3>Add new tag</h3>
<form name="addTagForm">
<input class="form-control" type="text" ng-model="newTag" ng-change="onChangeTag()">
<button class="btn btn-primary" ng-click="addTag(newTag)">Add Tag</button>
</form>
</div>

Resources