AngularJS $scope data is not showing any thing - javascript

The submitform() does not take the for datas to the function. Chrome console says ReferenceError: $ is not defined. Is there anything wrong in the code ?
var app = angular.module('app', []);
app.controller('testimonialController', function($scope, $http) {
$scope.formdata = {};
$scope.submission = false;
$scope.submitform = function($scope, $http) {
$http({
method: 'POST',
url: 'sendmail.php',
data: $.param($scope.formdata), // pass in data as strings
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
}).
success(function() {
console.log("send successfuly");
}).
error(function() {
console.log("It is failed");
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="contact-form" ng-controller="testimonialController" ng-app="app">
<h1 id="contact">Contact</h1>
<pre>Form data: {{formdata}}</pre>
<p>Take a look around the site, Do you have something in mind you would like to let me know .You can contact me by filling the form below or email hello#athimannil.com</p>
<form ng-submit="submitform()">
<div class="form-wrap">
<label for="name">Name</label>
<input type="text" name="name" ng-model="formdata.name" placeholder="Name" required>
<br>
</div>
<div class="form-wrap">
<label for="email">Email</label>
<input type="email" name="email" ng-model="formdata.email" placeholder="Email" required>
<br>
</div>
<div class="form-wrap">
<label for="comment">Message</label>
<br>
<textarea name="comment" id="comment" ng-model="formdata.comment" placeholder="Comment" cols="30" rows="10" required></textarea>
<br>
</div>
<input type="submit" name="submit" value="Send">
</form>
</div>
This is the console message when use
$http({
method : 'POST',
url : 'sendmail.php',
data : $scope.formdata, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).

data: $.param($scope.formdata)
This line uses jQuery's $.param method. You have to include it, if you want to use it

Related

Post json data using fetch api failed

Am new in javascript , and am trying to POST data with an API endpoint but data is not posting , I have printed in the console , but I see Slow network is detected. See https://www.chromestatus.com/feature/5636954674692096 for more details. Fallback font will be used while loading: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0 in Google chrome.
But internet connection is good and stable.
This is my vanilla javascript for posting data :
function onSignUp() {
signupform
var email = document.signupform.email_edt.value;
var driver_rb = document.getElementById("driver_rb").checked;
var password_edt = document.signupform.password_edt.value;
var r_password_edt = document.signupform.r_password_edt.value;
var url = 'https://tuvuge-app.herokuapp.com/api/v1/signup';
//var data = {username: 'example'};
var data = {
username: email,
email: email,
password: password_edt,
isDriver: 'True'
};
fetch(url, {
method: 'POST',
body: JSON.stringify(data), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Then I attached the onSignUp() function to the button in html as below :
<form class="admin-modal-content" name="signupform" onSubmit="onSignUp();" action="index.html" method="post">
<div class="container">
<h4>Sign Up</h4>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email">
<b>Email</b>
</label>
<input type="email" placeholder="you#example.com" id="email_edt" name="email_edt" required>
<label for="email">
<b>Select an Option</b>
</label>
<p>
<input type="radio" name="driver_rb" value="driver" id="driver_rb">
<label>Driver</label>
</p>
<p>
<input type="radio" name="passenger_rb" id="passenger_rb" value="passenger">
<label>Passenger</label>
</p>
<label for="psw">
<b>Password</b>
</label>
<input type="password" placeholder="Enter Password" id="password_edt" name="password_edt" required>
<label for="psw-repeat">
<b>Repeat Password</b>
</label>
<input type="password" placeholder="Repeat Password" id="r_password_edt" name="psw-r_password_edt" required>
<div class="clearfix">
<button type="submit" class="btn">Sign Up</button>
</div>
</form>
What am I missing ,because the endpoint has a message it brings when there's a success or failure of data posting , but I see the above message.
What am I missing?

Error 500 on return all in Laravel Controller

Hi I am trying to send form data using ajax to my controller in Laravel. In my controller I am trying to return $request->all() to see if the form data is present. I am getting an error 500 internal server error and I am not sure why. I have setup my Exceptions/Handler.php to receive errors and also checked the error log.
Here is my HTML and Ajax:
<div class="container">
<div class="row">
<h1>Create your post</h1>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="post">Post</label>
<textarea name="post" rows="8" cols="80" id="post" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="image">Add image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<input type="submit" name="submit" value="Submit Post" id="submit" class="btn btn-primary">
</div>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click", function(e){
e.preventDefault();
var formData = new FormData();
var fileData = $('#image').prop('files')[0];
var title = $('#title').val();
var post = $('#post').val();
formData.append('fileData', fileData);
formData.append('title', title);
formData.append('post', post);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
}
});
$.ajax({
url:'/post/create/create',
type: "POST",
data: {
formData: formData
},
dataType: 'json',
success:function(response){
toastr.success(response.response);
},
error: function(error){
toastr.error(error.error)
}
});
});
});
</script>
Here is my controller:
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200)
}
missing ;
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200); //<--here
}

How to send multiple forms data in one shot to server using angularjs?

Hi I am developing web application in angularjs. I have two forms in one html page. Below is the structure.
<form name="form1">
<input type="text" name="fname" />
<input type="text" name="lname" />
<input type="submit" value="Next" />
</form>
<form name="form2">
<input type="text" name="address" />
<input type="text" name="state" />
<input type="submit" value="Next" />
</form>
On clicking on the next submit button of first form i want to validate first form and i want to scroll to second form and disable the first form.
On clicking on the next submit button of form2 i want to validate second form and i want to submit data to server using $http from both forms(form1 and form2).
May i know is this is possible to achieve this? Also may i know is this is the right way i am following or something else i have to do with above requirement? Any suggestion or help would be greatly appreciated. Thank you.
You can bind all your values to a common object. I am enabling the second form after submitting the first form. In second forms submit function, you just have to loop through the values of common object and append it to formData. If you don't have any reason for having two forms, you can consolidate it into one.
Note: I have not added any form validations. For adding form validations, please refer https://codepen.io/sevilayha/pen/xFcdI
HTML:
<form name="form1" ng-submit="enableForm2()">
<input type="text" name="fname" ng-model="obj.fname" />
<input type="text" name="lname" ng-model="obj.lname" />
<input type="submit" value="Next" />
</form>
<form name="form2" ng-show="enableForm" ng-submit="finalSubmit()">
<input type="text" name="address" ng-model="obj.address" />
<input type="text" name="state" ng-model="obj.state" />
<input type="submit" value="Next" />
</form>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.obj = {};
$scope.enableForm = false;
$scope.enableForm2 = function() {
$scope.enableForm = true;
}
$scope.finalSubmit = function() {
$http({
method: 'POST',
url: YourURL,
withCredentials: true,
headers: {
'Content-Type': undefined
},
data: {},
transformRequest: function(data, headersGetter) {
var formData = new FormData();
angular.forEach($scope.obj, function(value, key) {
formData.append(key, value);
})
return formData;
}
}).then(function(data) {
$scope.enableForm=false;
}).catch(function(data, status) {
})
}
});
You can acheive it vai an Ajax Call not by direct Submit. Moreover Form Submit is not required. (Adding Form tag is optional)
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.4/angular-material.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Personal Info</p>
<input type="text" ng-model="form1.fname" name="fname"/>
<input type="text" ng-model="form1.lname" name="lname"/>
<input type="button" ng-click="SubmitForm()" value="Next"/>
<p>Address Info</p>
<input type="text" ng-model="form2.address" name="address"/>
<input type="text" ng-model="form2.state" name="state"/>
<input type="button" ng-click="SubmitForm()" value="Next"/>
</div>
<script>
var app = angular.module('myApp', ['ngMaterial']);
app.controller('myCtrl', function ($scope, $http, $q, HTTPService) {
$scope.form1 = {
fname: '',
lname: ''
};
$scope.form2 = {
address: '',
state: ''
};
$scope.SubmitForm = function () {
let submitFormData = {
form1: $scope.form1,
form2: $scope.form2
};
HTTPService.SubmitData(submitFormData);
}
});
app.factory('HTTPService', function ($http, $q) {
return {
SubmitData: function (formData) {
let apiUrl = 'http://localhost:2000/...';
var req = {
method: 'POST',
url: apiUrl + "SaveData.php",
headers: {
"Content-Type": "application/json",
"Authorization": '',
"Access-Control-Allow-Origin": "*"
},
data: formData
};
var result = $http(req)
.then(function(response) {
return angular.fromJson(response.data);
}, function(response) {
return null;
});
return result;
},
};
});
</script>
</body>
</html>
Using $scope also you will get values of fields which are not in same form.
HTML Code
<div ng-app="App" ng-controller="Ctrl">
<form name="myForm">
<!-- first nested form -->
<div ng-form="form1">
<label><p>Personal Info</p></label>
<input type="text" name="fname" ng-model="myForm.fname"/>
<input type="text" name="lname" ng-model="myForm.lname"/>
</div>
<!-- second nested form -->
<div ng-form="form2">
<label><p>Address Info</p></label>
<input type="text" name="address" ng-model="myForm.address"/>
<input type="text" name="state" ng-model="myForm.state"/>
</div>
<!-- etc. -->
<input type="submit" ng-click="SubmitForm()" value="Next"/>
</form>
</div>
JS/Controller code
var app = angular.module('App');
app.controller('Ctrl', function ($scope) {
$scope.SubmitForm = function () {
var SubmitForm = $scope.myForm;
console.log(SubmitForm);
}
});
You can do someting like below
<form name="form1" ng-submit="moveNext(user)">
<input type="text" ng-model="user.fname" name="fname" required/>
<input type="text" ng-model="user.fname" name="lname" required/>
<input type="submit" value="Next"/>
</form>
<form name="form2" ng-submit="submit(addressData)">
<input type="text" ng-model="addressData.address" name="address"/>
<input type="text" ng-model="addressData.state" name="state"/>
<input type="submit" value="Next"/>
</form>
and in Controller
$scope.userDetails = {};
$scope.addressDetails = {};
$scope.moveNext = function(userData){
$scope.userDetails = userData //Save user Data here and implement logic to scroll to next form and validation
}
$scope.submit = function(addressData){
$scope.addressDetails = addressData;
// and validate the form and Submit data to server here as per your requirement
}

Using AngularJS to post to server using $http

I'm sure this will be a duplicate of some other post, but I just can't find it?
I have just started looking at Angular and have written the following as per various sources online.
HTML:
<div data-ng-app="appAuthentication">
<form name="authentication" method="post" data-ng-controller="AuthenticationController" data-ng-submit="doAuthentication(authentication)" novalidate>
<fieldset>
<label for="sign-in-email-address">Email address:</label>
<input id="sign-in-email-address" name="sign-in-email-address" data-ng-model="authentication.emailAddress" type="text" required />
<label for="sign-in-password">Password:</label>
<input id="sign-in-password" name="sign-in-password" data-ng-model="authentication.password" type="password" required />
<button type="submit">Go ยป</button>
</fieldset>
</form>
</div>
And my Angular:
angular.module('appAuthentication', [])
.controller('AuthenticationController', ['$scope', function($scope, $http) {
$scope.authentication = {
emailAddress: '',
password: ''
};
$scope.doAuthentication = function(authentication) {
// console.log('Hello ' + authentication.emailAddress);
$http({
method : 'POST',
url : '/actions/authentication/sign-in.php',
data : authentication.emailAddress
})
.success(function () {
console.log('Success');
})
.error(function () {
console.log('Failure');
});
};
}]);
In the console I am getting:
TypeError: undefined is not a function
at k.$scope.doAuthentication (http://cms2.indypub.co.uk/static/scripts/core.js:16:4)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:176:88
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:193:165
at k.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:111:373)
at k.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:112:121)
at HTMLFormElement.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:193:147)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:31:161
at q (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:7:290)
at HTMLFormElement.c (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:31:143)
When I uncomment the first console.log in the JS the emailAddress is written out in the console.
Any pointers to where I am going wrong greatly appreciated.
Thanks,
Tony.
The main problem is in your controller dependencies, you have implicitly put $http in the function parameter but not in its array notation.
change:
controller('AuthenticationController', ['$scope', function($scope, $http) {
// your code
});
to
controller('AuthenticationController', ['$scope', '$http', function($scope, $http) {
// your code
});
Furthermore, change your name value attributes in your input tags, make it so it conforms like a variable name - Since you'll be accessing these names when validating forms.
e.g. <form name>.<input name>.$pristine or <form name>.<input name>.$error
change:
<label for="sign-in-email-address">Email address:</label>
<input id="sign-in-email-address" name="sign-in-email-address" data-ng-model="authentication.emailAddress" type="text" required />
<label for="sign-in-password">Password:</label>
<input id="sign-in-password" name="sign-in-password" data-ng-model="authentication.password" type="password" required />
to:
<label for="sign-in-email-address">Email address:</label>
<input id="sign-in-email-address" name="sigInEmailAddress" data-ng-model="authentication.emailAddress" type="text" required />
<label for="sign-in-password">Password:</label>
<input id="sign-in-password" name="signInPassword" data-ng-model="authentication.password" type="password" required />

submit form data to serverside

<form ng-submit="doRegister()">
<div class="control-group">
<label for="email">E-Mail Address</label>
<input type="email" id="email" name="email" ng-model="user.email" autofocus>
</div>
<div class="control-group">
<label for="password">Password</label>
<input type="password" id="password" name="user.password" ng-model="password">
</div>
<div class="control-group">
<label for="password_confirmation">Confirm Password</label>
<input type="password" id="password_confirmation" name="password_confirmation" ng-model="user.password_confirmation">
</div>
<input type="submit">
</form>
How do I submit the form to register via POST? Technically I don't know where data could be placed.
function registerCtrl ($scope, $http) {
document.title = 'Register';
$scope.doRegister = function(){
$http.post('/register', data).
success(function(data, status, headers, config) {
console.log(data);
}).
error(function(data, status, headers, config) {
angular.element('.errors').html(data.errors.join('<br>')).slideDown();
});
};
}
EDIT: Progress:
function registerCtrl ($scope, $http) {
document.title = 'Register';
$scope.user = {};
$scope.doRegister = function(){
$http.post('/register', $scope.user);
};
}
but the request sent to the server was an empty array in php:
Array()
You already have a properties binded within the form.
You can define data using them.
For example, for email field:
var data = {};
data.email = $scope.email;
Or you can even define $scope.data = {} in controller,
and post it.
EDIT on 9/14
This seems to be one of the problem that people see with $http.post() for sending
form data. Solution is given in the following Q&A.
AngularJS - Any way for $http.post to send request parameters instead of JSON?
You need to declare variables and change headers like this:
function registerCtrl ($scope, $http) {
document.title = 'Register';
$scope.user = {
email: '',
password: ''
};
$scope.doRegister = function(){
$http({
url: '/register',
data: $scope.user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
});
};
}
And you need
AngularJS' post method sends data as Request Payload.
Just use:
$json = json_decode(file_get_contents("php://input"));
You can access values in php by using
$email = $json->email;
$password = $json->password;
$password_confirmation = $json->password_confirmation;
<form id="Register" action="/register">
<div class="control-group">
<label for="email">E-Mail Address</label>
<input type="email" id="email" name="email" ng-model="email" autofocus>
</div>
<div class="control-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" ng-model="password">
</div>
<div class="control-group">
<label for="password_confirmation">Confirm Password</label>
<input type="password" id="password_confirmation" name="password_confirmation" ng-model="password_confirmation">
</div>
<input type="submit">
</form>
call ajax function.
$.ajax({
url: form.prop('action'),
type: 'POST',
data: form.serialize(),
dataType: 'json',
async: false,
success: function (result) {
}
}); // ajax post end
var form = $("#Register");
data pass form.serialize() that is very easy to pass data from server side.

Categories