Part of my HTML
<div>House Details:
<input type ="number" ng-model="house.totalArea" placeholder="total_area">
<input type="number" ng-model="house.cost" placeholder="Cost">
</div>
<div>Address:
<input type="text" ng-model="house.address.state" placeholder="state">
<input type="text" ng-model="house.address.city" placeholder="city ">
</div>
Angular:$scope.house = {};
$scope.house.address = {};
$scope.processRentForm = function () {
console.log($scope.house);
$http.post("http://localhost:8080/Property101/house/addHouse", $scope).
error(function (data, status, headers, config) {alert("Submit failed!!");
Code works fine for just $scope.house but
I'm getting a 400 eror ( syntactically incorrect) for nested JSON which is forming as
Object {address: Object, totalArea: 1000}
I have a Address class inside a House class on server side which have the similar no./names of parameters as the JSON I'm trying to send.
Some of the examples at SO have "house.address.state" syntax.
I'm new angular, any help would be appreciated.
Before sending the request JSON onto server side do the following 2 steps,
1) var reqObj = JSON.stringify($scope.house);
2) var requestJson = JSON.parse(reqObj)
Now send the requestJson as request. It should work.
Related
I have a json file in assets/json/abc.json
I have a requirement that I need to read /abc.json File from assets folder and write some data or delete some data from that /abc.json file according to an input value from a form in html.
I have tried but its not working.
Here, read/write/delete .json file is according to an input from user through a click event.
abc.json
[
{
"imgPath": "fa-users",
"dashboardName": "Command Center",
"urlToVisit": "dashboards/static/commandcenter"
},
{
"imgPath": "fa-tachometer",
"dashboardName": "HP Dashboard",
"urlToVisit": "dashboards/static/hpdash"
},
{
"imgPath": "fa-cube",
"dashboardName": "HP APJ",
"urlToVisit": "dashboards/static/hpapj"
}
]
abc.component.html
<form class="rmpm" (submit)="AddNewDashboardBox($event)">
<div class="form-group rmpm">
<div class='col-xs-12 rmpm'>
Enter Dashboard Name
<br>
<input type="text" class="form-control rmpm" placeholder="Dashboard Name" name="dashboardName"
required>
<br>
</div>
<div class='col-xs-12 rmpm'>
Enter Icon Name
<br>
<input type="text"class="form-control rmpm" placeholder="Icon Name" name="IconName"
required>
<br>
</div>
<div class='col-xs-12 rmpm'>
Enter Url Path to Visit
<br>
<input type="text" class="form-control rmpm" placeholder="Url Path" name="UrlPath"
required>
<br>
</div>
</div>
<button type="submit" class="btn btn-info">Add</button>
</form>
abc.component.ts
AddNewDashboardBox(e) {
e.preventDefault();
let dashboardNameInput = e.target.elements[0].value;
let IconNameInput = e.target.elements[1].value;
let UrlPathInput = e.target.elements[2].value;
var obj = {
table: []
};
var json = JSON.stringify(obj);
var fs = require('fs');
fs.readFile('assets/json/abc.json', 'utf8', function readFileCallback(err, data) {
if (err) {
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({ "imgPath": IconNameInput , "dashboardName": dashboardNameInput, "urlToVisit": UrlPathInput }); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('assets/json/abc.json', json, 'utf8');
}
});
}
The angular application is running on client browser and the file you want to change is residing on server. So this thing is not possible.
You will have to write an api to which angular will make rest call with new data and then that server will make the required changes in file on file (that is on server).
I recommend you to see the client server architecture for in depth details.
How do I display a message on a div <div asp-validation-summary="All" class="text-danger"></div> when I am sending a message from the back-end?
[HttpPost]
public IActionResult Signup(Signup signup)
{
var result = DBGetCls.GetList("SELECT * FROM Usertable WHERE Email = '{0}' ", signup.Email);
if (result.Count > 0)
{
object notFound = new { message = "Email has been used!" };
return BadRequest(notFound);
}
So my form would look like this:
<div id="signup">
<form asp-action="Signup">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="field-wrap">
<label asp-for="FullName" class="control-label active highlight">Name :</label>
<input asp-for="FullName" class="form-control" />
</div>
.
.
In your frontend MVC controller, you can add errors to the model state. These will be rendered in the validation summary. So when the backend answers with BadRequest, add an error manually.
ModelState.AddModelError("PropertyNameInViewModelToBeHighlighted",
"Error message to be shown in validation summary");
Some teams also build custom infrastructure to wrap the backend calls, catch any errors, extract the error message, and add it to the ModelState automatically.
See also What is the ModelState?
Using the MvcForm HtmlHelper, I have added 'id' and 'data-values' attributes to a form in an ASP.NET MVC Razor view.
I created a new object 'DataVars' to hold local and Model values. Then I converted 'DataVars' object into a JSON object and added it to the form tag 'data-values' attribute to be referenced later by JavaScript on the client-side.
#{
var DataVars = new
{
var1= LocalVar,
var2= Model.var1
};
var testing = Json.Encode(DataVars);
}
#using (Html.BeginRouteForm("GetForm", FormMethod.Get, new
{
id = "formId",
data_values = #Html.Raw(testing)
})) {
<div class="form-element-group">
<label class="screen-reader-only" for="terms">#T("Tooltip")</label>
<input type="text" class="text" id="terms" autocomplete="off" name="q" placeholder="#T("Tooltip")" />
<span class="input-group-btn">
<input type="submit" class="button" value="#T("Button")" />
</span>
</div>
}
This all works, but the problem is, in the resulting HTML output in the form 'data-values' attribute, double quotes are encoded within the JSON object;
data-values="{"var1":"text info","var2":0}"
When stepping through the code in debug the value for variable testing is set to:
{\"var1\":\"text info\",\"var2\":0}
Is there a way to force the JSON to be;
data-values="{"var1":"text info","var2":0}"
So I have been sitting here racking my brain for a few hours and just cannot seem to find what I have wrong here. I am trying to get my form to send the information that the user inputs to my email. When I click send nothing happens... Anything would help! Thanks!
Here is the code I have atm:
Email me!
<div class="formCenter">
<form action="MAILTO:myemail#yahoo.com" method="post" enctype="text/plain">
First Name:<br>
<input type="text" name="firstName"><br>
Last Name:<br>
<input type="text" name="lastName"><br>
Email:<br>
<input type="text" name="email"><br>
Comments:<br>
<textarea name="commentBox" rows="6" cols="40"></textarea><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
</div>
Okay so you have to send the Action to a page like Email.PHP (or ASP.net ect) which will process your POST variables.
Example:
<?php
$firstame = $_POST['firstName'];
?>
You then have to use Mail(), which will work on most servers but sometimes it won't so you can use a tool like PHPMailer which is an object orientated tool.
As you are providing the link as MAILTO, it opens up your local mail client to send an email with the POST variables listed, which is very unprofessional at best. You are better off having a link that goes to MAILTO for the time being, perhaps with a hidden value like or something like that, so when they open the client it automatically generates an email that they can just click. With that being said, you would keep your form layout as it is, but just swap out variables so they don't appear.
The reason you didn't see anything when you clicked Send is because even though your TYPE is a submit, you sometimes need the Value and/or Name to be Submit. Some browsers and servers will treat it differently, even frameworks like Bootsrap. If you change your name and value to Submit then change one back to Send to see what works for you, you can keep it in the Send format, given that it works.
I hope this helps.
you can try this one:
<?php
if($_POST["message"]) {
mail("your#email.address", "Form to email message", $_POST["message"], "From: an#email.address");
}
?>
see this page http://htmldog.com/techniques/formtoemail/
The form itself is not able to send the email. What the code does is prompts you to select email client software such as Outlook.
Did you check whether your email client software work properly? A reboot of machine is also a mean of troubleshooting.
JavaScript
function submitEmail() {
var fname = $.trim($("#txtfname").val());
var lname = $.trim($("#txtlname").val());
var email = $.trim($("#txtemail").val());
var comments = $.trim($("#txtComments").val());
if (isValidEmail(email) && (fname.length > 1) && (lname.length > 1)) {
$.ajax({
type: "POST",
url: "index.aspx/SubmitEmail",
data: "{'Email':'" + $.trim($("#txtemail").val()) + "'," + "'FName':'" + $.trim($("#txtfname").val()) + "'," + "'LName':'" + $.trim($("#txtlname").val()) + "'," + "'Comments':'" + $.trim($("#txtComments").val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != "null") {
var JsonObj = $.parseJSON(response.d);
if (JsonObj._Status == "OK") {
alert('Success Email :)')
}
else {
alert(JsonObj._Message);
}
}
},
failure: function (msg) {
alert(msg);
}
});
}
else {
return false;
}
}
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
<WebMethod()> _
Public Shared Function SubmitEmail(ByVal Email As String, ByVal FName As String, ByVal LName As String, ByVal Comments As String) As String
Dim _serializer = New JavaScriptSerializer()
Dim jSonRes As String = String.Empty
Dim MyString As New StringBuilder()
MyString.Append("First Name: " & FName).Append(Environment.NewLine)
MyString.Append("Last Name: " & LName).Append(Environment.NewLine)
MyString.Append("Email Address: " & Email).Append(Environment.NewLine)
MyString.Append("Comments: " & Comments).Append(Environment.NewLine)
Try
Dim Message As New Net.Mail.MailMessage("Do-Not-Reply#test.com", "myemail#yahoo.com")
Message.CC.Add("test#test.com,test#test.com")
Message.Subject = "New Request from " & FName & " " & LName
Message.IsBodyHtml = False
Message.Body = MyString.ToString()
Dim SmtpMail As New System.Net.Mail.SmtpClient
SmtpMail.Host = "localhost"
SmtpMail.Send(Message)
jSonRes = _serializer.Serialize(New With {._Status = "OK", ._Message = ""})
Catch ex As Exception
jSonRes = _serializer.Serialize(New With {._Status = "Error", ._Message = ex.Message})
End Try
Return jSonRes
End Function
<form action="index.aspx/submitEmail" method="post" enctype="text/plain">
First Name:<br>
<input type="text" name="firstName" id="fname"><br>
Last Name:<br>
<input type="text" name="lastName" id="lname"><br>
Email:<br>
<input type="text" name="email" id="txtemail"><br>
Comments:<br>
<textarea name="commentBox" rows="6" cols="40" id="txtComments"></textarea><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
This is the correct way to send a email. You can also use a php or C# code for sending a email. I have used vb.net code(webmethod) for sending email.
I'm trying to make a simple angular app which reads json data , but in response I'm only getting "," not data.Any pointers where I m going wrong ? I have attached index.html and abc.json file that i m keepingat server
PFB the code .
HTML:
<body ng-app="sampleApp" ng-controller="ctrl1">
Name:<input type="text" ng-model="name">
<ul>
<li ng-repeat="student in students | filter:name">{{student.name +","+student.empNo}</li>
</ul>
Name:<input type="text" ng-model="newname">
EmpNo:<input type="text" ng-model="newemp">
<input type="button" value="AddMe" ng-click="add()"/>
<div>
<div ng-view></div>
</div>
Javascript:
var x=angular.module('sampleApp',[])
.factory("simpleFactory",function($http){
var factory={};
factory.getStudents=function(){
return $http.get("abc.json");
}
return factory;
})
.controller("ctrl1",function($scope,simpleFactory){
$scope.students=simpleFactory.getStudents();
$scope.add=function(){
$scope.students.push(
{
name:$scope.newname,empNo:$scope.newemp
}
)
}
})
abc.json
[
{"name":"jack","empNo":"1"},
{"name":"Red","empNo":"2"},
{"name":"Jill","empNo":"3"}
]
getStudents is asynchronous. You should retrieve and assign students through the callback handler.
.factory("simpleFactory",function($http){
var factory={};
factory.getStudents = $http.get("abc.json");
return factory;
})
.controller("ctrl1",function($scope,simpleFactory){
simpleFactory.getStudents().then(function(result) {
$scope.students= result.data;
});
...
})
Nearly right. getStudents in fact returns you a 'Promise', not the data itself. You have to use that Promise to get your data:
simpleFactory.getStudents().then(function(data) {
$scope.students=data
// $scope.students=data.data // you may need this given your feedback
});