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

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

Related

AngularJS form won't submit

I have this simple HTML form as below and I am using the Angular js (see the controller. - the is the form is not getting submitted and for some reason I am not able to read the values. i checked online and other questions on Stack overflow, but no success. Any pointers or guidance - what am i missing? thanks in advance :
<!doctype html>
<html ng-app="auth">
<head>
<title>Hello AngularJS</title>
</head>
<body>
<form method="post" ng-submit="login()" novalidate ng-controller="Login">
DBID<input type="text" name="dbId" value="23" ng-model="dbId" />
UserName<input type="text" name="username" value="test#test.com" ng-model="username" />
Password<input type="text" name="password" value="test1234" ng-model="password" />
<input type="submit" id="submit" value="login" />
<pre>list={{list}}</pre>
<p>The Token is: {{token}}</p>
</form>
<script src="Scripts/angular.js"></script>
<script src="Scripts/login.js"></script>
</body>
</html>
Here is my AngularJS controller:
var auth = angular.module('auth', []);
auth.controller('Login', function ($scope, $http)
{
$scope.login = function ()
{
if ($scope.dbId)
{
$scope.list.push(this.dbId);
$scope.text = '';
}
};
var Credentials = new Object();
Credentials.DBID = "23";
Credentials.username = "test#test.com";
Credentials.password = "test1234";
$http({
dataType: 'json',
method: 'POST',
url: 'http://localhost:55049/api/Security/Login',
data: Credentials,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic VGVzdEFwcGxpY2F0aW9uVG9rZW46'
}
}).then(function (response)
{
$scope.token = response.data;
});
});
Thanks
i think you are closing the login function brace too early. adjusted it and try again.
var auth = angular.module('auth', []);
auth.controller('Login', function ($scope, $http)
{
$scope.login = function ()
{
if ($scope.dbId)
{
$scope.list.push(this.dbId);
$scope.text = '';
}
var Credentials = new Object();
Credentials.DBID = "23";
Credentials.username = "test#test.com";
Credentials.password = "test1234";
$http({
dataType: 'json',
method: 'POST',
url: 'http://localhost:55049/api/Security/Login',
data: Credentials,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic VGVzdEFwcGxpY2F0aW9uVG9rZW46'
}
}).then(function (response)
{
$scope.token = response.data;
});
};
});
I added some modifications to the JavaScript code and it's working fine.
Please take a look and run the sample code to see it in action. Also I changed the username, DBID and password to be dynamic with input values.
var auth = angular.module('auth', []);
auth.controller('Login', function($scope, $http) {
$scope.list = [];
$scope.login = function() {
if ($scope.dbId) {
$scope.list.push(this.dbId);
$scope.text = '';
var Credentials = new Object();
Credentials.DBID = $scope.dbId;
Credentials.username = $scope.username;
Credentials.password = $scope.password;
alert("Posting your data: " + JSON.stringify(Credentials));
$http({
dataType: 'json',
method: 'POST',
url: 'http://localhost:55049/api/Security/Login',
data: Credentials,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic VGVzdEFwcGxpY2F0aW9uVG9rZW46'
}
}).then(function(response) {
$scope.token = response.data;
});
} else {
alert("Please add DBID");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="auth" ng-controller="Login">
<form method="post" ng-submit="login()" novalidate ng-controller="Login">
DBID<input type="text" name="dbId" value="23" ng-model="dbId" /> UserName
<input type="text" name="username" value="test#test.com" ng-model="username" /> Password
<input type="text" name="password" value="test1234" ng-model="password" />
<input type="submit" id="submit" value="login" />
<pre>list={{list}}</pre>
<p>The Token is: {{token}}</p>
</form>
</div>

angular js json.stringify to php

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

GAE: Not posting to local datastore (angular)

Ive got the following code. From chrome dev tools everythin is 200 OK and 302 after clicking post button but nothing is showing up on local datastore.
"Recommendation" model
class Recommendation(ndb.Model):
comment = ndb.StringProperty()
post method from python webapp2
def post(self):
r = json.loads(self.request.body)
new_comment = Recommendation(comment=r['comment'])
new_comment.put()
/exp.html
<form ng-submit="addComment()" method="post" id="frmComment">
<textarea ng-model="formFields.comment" id="comment" name="comment" class="form-control status-box comment" rows="2"></textarea>
</form>
<div class="button-group pull-right">
<button form ="frmComment"class="btn btn-primary pst sameline" type="submit">Post</button>
</div>
angular http post
$scope.formFields = {
comment : ""
}
$scope.comments = [];
$scope.addComment = function() {
var form_comment = $scope.formFields.comment
var payload = {
comment: form_comment
}
$http({
method: 'POST',
url: '/exp.html',
data: payload
}).then(function(response) {
$scope.comments.push(payload);
console.log(payload)
}, function(response) {
});

Populate textfield on page opening

I have simple form being opened clicking on tab
<form name="instructions" class="form form-horizontal" ng-controller="InstructionsPage">
<div class="form-group">
<label for="instruction">Instructions</label>
<textarea id="instruction" rows="5" class="form-control" ng-model="instructions">
</textarea>
</div>
<button class="btn btn-primary" data-ng-click="saveInstructions()">Save</button>
</form>
and related controller
angular.module('myApp.controllers')
.controller('InstructionsPage', ['$scope', function ($scope) {
use strict';
$scope.saveInstructions = function() {
var data = $scope.instructions;
// post request with data from textfield inside
}
}]);
How to receive data with GET-request to populate textfield with default/previously saved data? Thank you!
You can just update your $scope.instructions variable which is bound to the <textarea> ng-model from your controller like this:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.instructions = response;
}, function errorCallback(response) {
});

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

Categories

Resources