I have an Angular Bootstrap project- a form with some fields like name, email, phone, etc. to fill in. The form is written in HTML, in a file called customer-form.component.html. Upon submission, a JSON object is created with the values of the fields and displayed on-screen.
I am writing a HTTP POST request in the file customer-form.component.ts. The method in question looks like this:
postProfile() {
this.httpClient.post('API server url',
{
name:this.name,
phone:this.phone,
email:this.email,
yesorno:this.yesorno
})
.subscribe(
(data:any) => {
console.log(data)
}
)}
I set it up so submission of the form would also submit the POST request to the server. I am using Chrome to debug, and in the console I get the error message:
"Failed to INSERT or UPDATE Customer record due to: [com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'NAME' cannot be null]"
I changed the code to name:name once, and a submission got through. But when I checked it in the server, it had a blank name (name:''), and some true/false fields and fill-in numerical fields. Email and phone were not even represented, blank or otherwise, in the submission. Now if I try to submit something with name:name, it is counted as a duplicate and does not work. No matter what I fill in the form before I submit, the complaint is that the name field is blank.
My main question: Is there a way, preferably by referring to the JSON object, to accurately populate the POST request fields based on input fields? The JSON object is defined/created in a script in the index.html file.
My second question: What on earth is being used to populate the POST request right now? Even if I fill in the fields, the name field is blank upon submission. I have a model Customer object in customer-form.component.ts (like below), and I suspect that is how the original submission was populated (except the name?).
model = new Customer('Harry', 11111111111111, 'pott#r', true);
Please let me know if more information is needed.
Related
I am trying to load the username dynamically after octa Signin is ready for user input like this
check this screenshot of js configuration
Though value is being populated to the input field, on submission Octa js returns an invalid username error
check this screenshot how error message coming
though the value is present in the input field, it seems like it's not considered.
How to populate Octa Username automatically on widget ready? Any workaround could be helpful!
I tried all possible ways to fill input field, and it is loading there, but octa submission code not detecting
//document.getElementById("okta-signin-username").value = Username;
//document.getElementById("okta-signin-username").setAttribute('value', Username);
//document.getElementById("okta-signin-username").focus();
document.querySelector('input[name="username"]').value = Username;
I have created one form.
On click Submit button record is saving in database with ajax POST.
Then again for viewing those records on web page I am clearing existing html and adding new records.
In form I am having select list and text-boxes and textarea.
For example:
Following is my Form:
On Click Save FAQ button data from following form data is saving in database.
Quetion No. field is having unique no. for this I am generating number in backend.
Means when I do ajax POST Question No is blank but it is been assigned unique no. before putting in database.
Requirements:
Select list is present in that by default option value is Default Mode(New).
Question field value need to get append in select list after clicking Save FAQ.
For this I am getting all records with Ajax GET and clear previous html and add new data but this is not feasible.
I need to optimize this.
For this I need to save this record in array, ex :
saveFaqRecordT = []
saveFaqRecordT.push({faq_no: getRec, faq_quest: rec.faq_quest, faq_answer: rec.faq_answer});
getRec is counter as we are no passing any value for Question No from client side.
Or Please guide me with how to save record in client side also while saving doing Ajax POST, so that there is no need to do Ajax Get on each save?
Ajax Post -> Return appropriate response, let's say a JSON
On Success
{"status":"success","message":"added successfully"}
On Error
{"status":"error","message":"failed because of validation"}
Simply parse this JSON in the POST callback, to figure out where the saving was successful or not.
If the saving was successful, simply add the data to your saveFaqRecordT array.
$.ajax({
method:POST,
url:"http://someurl.com",
data:$("#myform").serialize(),
success:function(data){
var json=eval(data);
if(json.status=='success'){
//append to array
}
}
});
Above is just a sample un-tested code, to give you an idea on how it can be done.
I have a form with an 'Address' section. I send my form data to the server using an $http post request.
If I don't type anything in the address fields (pristine) then Address data is not included in the object data I'm sending to the server.
If I do type something in the address fields, then delete what I typed (leaving it blank), empty fields are included in th JSON post to the server:
{
street:"",
city:""
}
I don't want to include the (optional) address data if the fields are blank.
Is there a way to easily reset individual form fields to 'pristine' if they are left blank?
The only way to set something to pristine is manually. That is, once a form has been touched, it's touched until you say otherwise.
I would probably do a check in the update function for values in the form field as well as relying on pristine status.
I think you could use ng-pattern in order to invalidate your empty fields, which will prevent them from being added to your submitted object. I'd add something like that in the controller
$scope.nonEmpty=/^(.+)$/i
Then in the HTML
...< input ... ng-pattern='nonEmpty' ... >
If the field is empty it won't be added because it doesn't match the pattern, else it will be sent
You can put a watch on the value, check for empty, then reset it to pristine manually
$scope.$watch('inputName',function(newVal){
if(newVal ==="")
$scope.form.inputName.$pristine = true;
});
I have a form which collects some data, most importantly an address which needs to be geocoded to obtain the lat and long.
Suppose the user inputs something like:
123 main st
SomEwheRE, NY 12345
My client-side javasript goes out to the Google Geocoding service and attempts to get the lat and long for that address. In return I also get back more addition information including the properly formatted address:
123 Main St
Somewhere, NY 12345
What I want to do is replace the values in their respective textboxes so that the user can verify the data is good and then finally submit via jQuery.post("My/Controller/", myJSONData, function(){}); but I'm getting some strange behavior.
If I type in an address and don't include a zip code (it's required in the database but not necessary to geocode the address) I get a validation error. The thing is I would like to defer validation until after I obtain the information from the geocode service and replace the values in the textbox.
Right now, if I only type in a partial address (and hit "Submit") this is what happens:
Validation errors occur on the missing required fields and all my textboxes go blank
Hit submit again and this time the textboxes are properly filled in with the geocoded information BUT ALL fields produce validation errors.
Hit submit a 3rd time and now the validation errors go away and everything is as expected. At this point, I want to consider the form valid and allow the POST to the Controller.
Code:
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
var geoCodedAddress = geoCodeAddress($("#Address1").val(), $("#City").val(), $("#State").val());
console.log(geoCodedAddress);
geoCodedAddress.Name = $("#Name").val();
geoCodedAddress.Phone = $("#Phone").val();
$("#Address1").val(geoCodedAddress.Address1);
$("#City").val(geoCodedAddress.City);
$("#State").val(geoCodedAddress.State);
$("#ZipCode").val(geoCodedAddress.ZipCode);
});
});
geoCodeAddress() returns the JSON object with the required fields filled in and that works. I believe the problem lies somewhere between my ineptitude and the block of code I posted.
Well, after much tinkering this is what I came up with. Basically, when someone hits submit (or enter) I stop the form from being submitted (by e.preventDefault()) and check to see if it's valid. If the form data is valid, I then process what the user entered, fill in the form fields with the acquired data (this doesn't do anything functional, it just flashes the new data in the form). I couldn't figure out how to submit the form, so I posted it myself using $.post(). If there is a better way please leave a comment or answer and I will vote. Here is my complete code:
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
if ($("form").valid()) {
geoCodeAddress($("#Address1").val(), $("#City").val(), $("#State").val(), function (geoCodedAddress) {
geoCodedAddress.Name = $("#Name").val();
$("#Address1").val(geoCodedAddress.Address1);
$("#City").val(geoCodedAddress.City);
$("#State").val(geoCodedAddress.State);
$("#ZipCode").val(geoCodedAddress.ZipCode);
$("#Longitude").val(geoCodedAddress.Longitude);
$("#Latitude").val(geoCodedAddress.Latitude);
$.post("/Controller/Action/", geoCodedAddress, function () { $(window).attr("location", "/Controller/"); });
});
}
});
});
Let's say a user gets a page /form/
GET /form/
He then fills in the form and sends a post request
POST /form/
The server attempts to validate user input and determines input to be invalid.
Currently the history chain for the users is
GET /form/
POST /form/
Now the server redirects the user to the GET /form/ page so it can fill in the form again (with error messages).
His history looks like
GET /form/ with filled in form fields
GET /form/ without filed in form fields
How do I send the user back without the user losing the details he entered in his first form?
What techniques are there for redirecting users back to their GET /form/ page and not forcing them to re-enter their information.
Below is my express (node.js) specific server side code for this example.
The validation middleware:
validate().on("error", function _error(msg) {
// store error message on request object
req.flash(msg, validateUserMessage[msg]);
}).on("valid", function _valid() {
// handle the rest of /POST/
next();
}).on("invalid", function _invalid() {
// redirect user back to last page, the /GET/ form
res.redirect("back");
}).run(function _validateUsers(check, sanitize) {
// validation logic.
});
The routing:
// GET /form/
app.get("/form", function _signUpView(req, res) {
// render /form/
res.render("auth/signup", req.flash());
});
// POST /form/
// validation middleware used here.
app.post("/form", secure.validateUser, function _signUpCreate(req, res) {
model.create(req.body, function _create() {
// create thing in database
});
});
DO NOT redirect on invalid input. Do it on valid input only.
On invalid input, respond to the POST request with the same form, but this time populated with the POST data that you just received.
I have decided to summarise the comments below into my answer:
To me, there seems to be only two sure ways of doing this:
1. Passing the user input parameters back from the server to the browser and repopulate the form either:
a) Using a parameters object passed to the view and populating each field using your severside language
b) Passing back a Json object and populating the form using loadJson
2. Using HTML5 local storage - which also requires JavaScript
If you do not persisit your data using either the server or JavaScript, then surely you are limiting yourself to relying on the browser - which is something you have no control over.
Good luck - if you do find a solution then please post it as your answer as I would be very intersted to see how you succeeded.