Im new to angular js i want to post a url to server
this is my code
Index.html
<html ng-app="signupApp">
<head>
<title>ServicePrice Signup</title>
<link rel="stylesheet" href="css/animations.css" />
<link rel="stylesheet" href="css/login.css" />
<link rel="stylesheet" href="css/foundation.min.css" />
</head>
<body>
<div class="centerwrap">
<div class="Signup" ng-controller="SignupController">
<!-- <form action="signin()"> -->
<h2>Signup</h2>
<label for="email">Email</label>
<input type="email" ng-model="email">
<label for="password">Password</label>
<input type="password" ng-model="password">
<input type="submit" class="button" ng-click="signup()">
</div>
<!-- </form> -->
</div>
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="js/controller.js"></script>
</body>
</html>
controller.js
var signupApp = angular.module('signupApp', [])
var site = "http://devhosting.wiredelta.in:9009";
signupApp.controller('SignupController', function($scope, $http) {
$scope.signup = function() {
var data = {
email: $scope.email,
password: $scope.password
};
$http({
url: site + '/company/signup',
method: "POST",
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log(data);
}).error(function(res) {
console.log(res);
});
}
});
how can clear this error and get response from server
both email and password reaches server but is says "bad request" all the time
error in console
POST http: //devhosting.wiredelta.in:9009/company/signup 400 (Bad Request)
controller.js: 24 Object {
error: Object
}
error: Objectmessage: "Data is not valid"
type: "BadRequestError"
__proto__: Object__proto__: Object
Unfortunately, Angular does not automatically encode the parameters in a formpost, like in jQuery.
You have to do this yourself, just like you have to add the header 'Content-Type': 'application/x-www-form-urlencoded' yourself, like you already did.
If you include jQuery you can do it like this: $.param(data)
I finaly found it as yang li told we need to convert data , so i used this
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
Related
I am writing a login form and I need to make an authentication for the username and password.
The form is written in dreamweaver html code. And the database is local in visual studio .net core code. I am still trying to figure out a way to use $post and $get methods, but I even can't write the url correctly. I am using swagger to host my api.
Here is my visual studio controller code :
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using authentication.Models;
using authentication.Repository;
using Microsoft.AspNetCore.Http;
namespace Taskb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private UsersRepository users = new UsersRepository();
private int count = 0;
[HttpGet]
public ActionResult<IEnumerable<user>> GetAllUser()
{
return users.GetAllUsers();
}
[HttpPost]
public ActionResult<user> CreateUser( user newUser)
{
foreach (user item in users.GetAllUsers())
{
if (newUser.username == item.username && newUser.password == item.password)
{
count++;
}
}
if (count == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Username or password incorrect");
}
return Ok("Authentication Successfull");
}
}
}
And here is my html code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Roy Daher</title>
<link href="styles/style.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial scale 1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"
type="text/javascript"></script>
<!--include jQuery Validation Plugin-->
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
</head>
<body bgcolor="#F1F1F1" class="body">
<div class="cont" >
<div class="top"></div>
<div class="bottom"></div>
<div class="center">
<form id="form" method="post">
<!--<div class="image">
<img src="images/28-287073_elonlol-discord-emoji-elon-musk-laughing-deer-hd.png" width="282" height="290" alt="Picture" class="elon">
</div>-->
<div class="container">
<label for="user"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="user" required id="userinput">
<label for="pass"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required id="passinput">
<button id="loginButton" type="button">Login</button>
<label for="remember">Remember me</label>
<input type="checkbox" checked="checked" name="remember">
</div>
<div class="container" style="background-color:#F1F1F1">
<span class="forgot">Forgot <a href="pages/PassRecovery.html" target="_blank" >password?</a></span>
</div>
</form>
</div>
</div>
</body>
<script>
$(document).ready(function(){
$("button").click(function(){
var inputVal = document.getElementById("userinput").value;
var passVal = document.getElementById("passinput").value;
var obj ={
username:inputVal,
password:passVal
};
console.log(obj);
$.post("https://44332/api/User",
{
},
});
});
});
</script>
</html>
Thank you in advance for your help.
Your post method should use [FromBody] user newUser as the input parameter like below:
[HttpPost]
public ActionResult<user> CreateUser([FromBody] user newUser)
{
List<user> users = new List<user> {
new user{ username="a",password="a"},
new user{ username="b",password="b"},
new user{ username="c",password="c"}
};
foreach (user item in users)
{
if (newUser.username == item.username && newUser.password == item.password)
{
count++;
}
}
if (count == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Username or password incorrect");
}
return Ok("Authentication Successfull");
}
And your ajax request should send like this:
<button id="loginButton">login</button>
<script>
$("#loginButton").click(function(){
var obj ={
username:"a",
password:"a"
};
$.ajax({
url: "https://localhost:44317/api/user",
type: 'post',
contentType: 'application/json',
data: JSON.stringify(obj),
success: function(data) {
alert(data);
}
})
});
</script>
Probably something simple going on here, but I have to attend to it before I attend to the PHP stuff. I'm going to try to use PHPMailer this time.
Also I've been trying to learn how to send a form on localhost for about a week now. Now I'm going to try to to incorporate PHPMailer. I had originally spent some time enabling a sites available to point to another folder, installing and testing PHP and installing msmtp on debian, even sent a test email with PHP, via command line but I haven't gotten one form to submit right yet and it's a :p
Also when working on forms before I made a couple changes to my php.ini files one on apache dir and one on cli dir, I think I uncommented some stuff and I hope it wont interfere with the what I'm trying to do.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style type="text/css">
input, textarea {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<input id="name" placeholder="Name" class="form-control">
<input id="email" placeholder="Email" class="form-control">
<input id="subject" placeholder="Subject" class="form-control">
<textarea class="form-control" id="body" placeholder="Email Body"></textarea>
<input type="button" onclick="sendEmail()" value="Send an Email" class="btn btn-primary"></type>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript">
function sendEmail() {
console.log('sending...');
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmtpy(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
body: body.val()
}, success: function (response) {
console.log(response)
}
});
}
}
function isNotEmpty(caller) {
if (caller.val()) == "") {
caller.css('border', 1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
</body>
</html>
RAW Paste Data
Try use code below:
<script type="text/javascript">
function sendEmail() {
console.log('sending...');
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
body: body.val()
}, success: function (response) {
console.log(response)
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() === "") {
caller.css('border', '1px solid red');
return false;
} else {
caller.css('border', '');
}
return true;
}
</script>
I checked. Work fine.
I am sending pdf file to server, and the form for creation of pdf file is not rendered, when the page loads. Its rendered when user click on something...
The problem is, that I cannot select id "file" which is input type="file" (html is generated by javascript).
How to select it the same as I am doing it with this code (the same result).
Thank you
$('.content').on('click','.file-btn', function() {
var data = new FormData();
var input = document.getElementById('file');
const title = $("#title").val();
const description = $("#textarea").val();
const sharingWith = $("#dropdown").val();
data.append('file', input.files[0]);
console.log("file" + data.get("file"));
$.ajax({
method: 'POST',
enctype: 'multipart/form-data',
url: 'https://localhost:8443/documents'+ "?title="+title + "&desc="+description + "&Role="+sharingWith ,
data: data,
processData: false,
contentType: false,
headers: {
'Authorization': 'bearer ' + localStorage.access_token},
success: function (data) {
alert("works!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
})
export const createDocumentForm = () => {
const markup = `<form class="doc_form" id="doc-form">
<label for="title" id="title-label">Title</label>
<input type="text" id="title" required placeholder="Title">
<label for="textarea" id="textarea-label">Description</label>
<textarea id="textarea" placeholder="Enter description" required rows="5"></textarea>
<label for="dropdown" id="dropdown-label">Select groups for sharing document</label>
<select name="select" id="dropdown" multiple required>
<option value="USER">USER</option>
<option value="SUPERIOR">SUPERIOR</option>
<option value="ADMIN">ADMIN</option>
</select>
<div class="doc_sender">
<form class="form-horizontal" method="POST" enctype="multipart/form-data" id="id_form">
<input type="file" id="file"/>
</form>
<button class="btn btn-doc file-btn">Save file!</button>
</div>
</form>`;
elements.content.insertAdjacentHTML("beforeend", markup);
};
try using this to get your file
var input = $("#file").get(0).files[0];
1st: be sure your html file you have the main.js is below the src of jQuery src
2nd: wrap your js code like the example below
$(document).ready(function() {
console.log('your document is ready ...');
// your code ....
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="main.js"></script>
<title>Your title</title>
</head>
<body>
</body>
</html>
Can someone please help me out, I want to upgrade this page to the latest version of angular but for some reason it doesnt work, I have tried defining the controllers rather than having them as functions but then I lose all my error messages that I have set up... Javascript is not my strongest skill so any help is greatly appreciated
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<!-- apply the module and controller to our body so angular is applied to that -->
<body ng-app="LoginformApp" ng-controller="formControllerApp">
<div class="wrapper">
<div class="clear"></div>
<form method="post" action="" ng-submit="processForm()">
<div>
<input type="text" id="emailaddy" name="email" placeholder="Email" ng-model="formData.email"> <br> <!-- attach ng to the form input -->
<span class="help-block" ng-show="errorEmail">{{ errorEmail }}</span>
</div>
<div>
<label class="lock" for="password">
<svg viewBox="0 0 32 32">
<g filter="">
<use xlink:href="#lock-locker"></use>
</g>
</svg>
</label>
<input type="text" id="paww" name="password" placeholder="Password" ng-model="formData.password"> <br> <!-- attach ng to the form input -->
<span class="help-block" ng-show="errorPassword">{{ errorPassword }}</span>
</div>
<div>
<input type="submit" id="followbtn" name="submit" placeholder="Login"> <br>
</div>
</form>
<!-- <pre>
{{ formData }}
</pre> -->
<div class="responsebox">
{{ message }}
<!-- ajax success response here -->
</div>
</div>
<script type="text/javascript">
// define angular module/app
var formApp = angular.module('LoginformApp', []);
// create angular controller and pass in $scope and $http
function formControllerApp($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};
// process the form
$scope.processForm = function() {
$http({
method : 'POST',
url : 'http://example.com/parse-login.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(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorEmail = data.errors.email;
$scope.errorPassword = data.errors.password;
//$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
}
</script>
</body>
</html>
Try the code below:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<!-- apply the module and controller to our body so angular is applied to that -->
<body ng-app="LoginformApp" ng-controller="formControllerApp">
<div class="wrapper">
<div class="clear"></div>
<form method="post" action="" ng-submit="processForm()">
<div>
<input type="text" id="emailaddy" name="email" placeholder="Email" ng-model="formData.email"> <br> <!-- attach ng to the form input -->
<span class="help-block" ng-show="errorEmail">{{ errorEmail }}</span>
</div>
<div>
<label class="lock" for="password">
<svg viewBox="0 0 32 32">
<g filter="">
<use xlink:href="#lock-locker"></use>
</g>
</svg>
</label>
<input type="text" id="paww" name="password" placeholder="Password" ng-model="formData.password"> <br> <!-- attach ng to the form input -->
<span class="help-block" ng-show="errorPassword">{{ errorPassword }}</span>
</div>
<div>
<input type="submit" id="followbtn" name="submit" placeholder="Login"> <br>
</div>
</form>
<!-- <pre>
{{ formData }}
</pre> -->
<div class="responsebox">
{{ message }}
<!-- ajax success response here -->
</div>
</div>
<script type="text/javascript">
// define angular module/app
var formApp = angular.module('LoginformApp', []);
// create angular controller and pass in $scope and $http
formApp.controller("formControllerApp",['$scope','$http', function formControllerApp($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};
// process the form
$scope.processForm = function() {
$http({
method : 'POST',
url : 'http://example.com/parse-login.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(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorEmail = data.errors.email;
$scope.errorPassword = data.errors.password;
//$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
}]);
</script>
</body>
</html>
Just remove the method: 'POST' and the url: /.. from your object and do this..
$http.post('/url', { ... })
See Angular 1.3.18 $http documentation
This code runs on a SharePoint Web Part page in a Script Editor web part. It makes an AJAX call to get list items from SharePoint, and then it should be populating the form with those items. However, nothing is happening.
<link data-require="bootstrap-css#*" data-semver="3.0.0" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<h2>Questionnaire:</h2>
<br />
<div ng-app="App">
<div ng-controller="spListCtrl">
<table width="100%" cellpadding="10" cellspacing="2" class="employee-table">
<tr ng-repeat="control in Controls">
<td>{{control.Title}}</td>
<td>
<input type="radio" name="{{control.Id}}" value="Yes">Yes
<input type="radio" name="{{control.Id}}" value="No">No
</td>
<td>
<textarea id="{{control.Id}}Comment"></textarea>
</td>
</tr>
</table>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.js"></script>
<script>
function getDataWithCaml(listName, caml) {
var endpoint = "https://myteamsite.sharepoint.com/_api/web/lists/GetByTitle('" + listName + "')/GetItems(query=#v1)?#v1={\"ViewXml\":\"'" + caml + "'\"}";
return jQuery.ajax({
url: endpoint,
method: "POST",
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose"
}
});
}
var App = angular.module('App', ['ngRoute'])
.controller('spListCtrl', function ($scope, $http) {
var caml = "<View><Query><Where><Contains><FieldRef Name='Title' /><Value Type='Text'>C-04</Value></Contains></Where></Query></View>";
var jsonData = getDataWithCaml("Controls", caml);
jsonData.success(function (data) {
alert('success');
$scope.Controls = data.d.results;
});
});
</script>
Since you are updating scope outside the context of Angular execution, you need to wrap the assignment in $scope.$apply, such as
$scope.$apply(function() {
$scope.Controls = data.d.results;
});