Sending data gives [object HTMLInputElement] as query response - html

I am trying to send user form data to partner endpoint like this:
$('#registrationFrm').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "https://pixel.plexop.com/?country="+countryid+"&_v=6&name="+firstName+"&lastname="+lastName+"&phone="+phone
+"&email="+emailid+"&ud=&e=2&adv=1&a=4&f=221161&FormId=1807&SerialId=1210053",
data: $("#registrationFrm").serialize(),
success: function() {
alert('success');
}
});
});
I get 200 "OK" back, but as of data I get this sent when I inspect it on "network":
Query string: country "[object HTMLSelectElement]
Query string: name "[object HTMLInputElement]
Query string: lastname "[object HTMLInputElement]"
My form looks like this:
<form id="registrationFrm" >
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="First Name" name="firstName" id="firstName" required />
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Last Name" name="lastName" id="lastName" required />
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="tel" class="form-control" placeholder="Phone No" name="phone" id="phone" required />
<span class="glyphicon glyphicon-earphone form-control-feedback"></span>
What am I doing wrong here?

Probably, you define your variables like:
const firstName = document.getElementById('firstName');
/*and so*/
But you should do this like:
const firstName = document.getElementById('firstName').value;
UPD:
$('#registrationFrm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url:
'https://pixel.plexop.com/?country=' +
countryid.value +
'&_v=6&name=' +
firstName.value +
'&lastname=' +
lastName.value +
'&phone=' +
phone.value +
'&email=' +
emailid.value +
'&ud=&e=2&adv=1&a=4&f=221161&FormId=1807&SerialId=1210053',
data: $('#registrationFrm').serialize(),
success: function () {
alert('success');
}
});
});

Related

Ajax Form Submit using jQuery

I am working with a form that I want to submit with ajax to a api that sends email to the email mentioned in it and the api was working in postman with raw data but I can't get it to work with the form using jQuery and ajax so if you guys can tell me why my function is not working and sending the email it will be of great help to me
Function for form submit:-
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
"url": "http://178.18.243.33:8089/email/sendmailusingtemplate",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({
"to": "nkulhari96#gmail.com",
"cc": "services#gmail.com",
"template": "contact_us_001",
"name": "name",
"email": "email",
"mobile": "phone",
"message": "message"
}),
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
Code for Form:-
<form name="sentMessage" id="contactForm" novalidate="">
<div class="control-group form-group">
<div class="controls">
<input type="text" placeholder="Full Name" class="form-control" id="name" required="" data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<input type="tel" placeholder="Phone Number" class="form-control" id="phone" required="" data-validation-required-message="Please enter your phone number.">
<div class="help-block"></div></div>
</div>
<div class="control-group form-group">
<div class="controls">
<input type="email" placeholder="Email Address" class="form-control" id="email" required="" data-validation-required-message="Please enter your email address.">
<div class="help-block"></div></div>
</div>
<div class="control-group form-group">
<div class="controls">
<textarea rows="5" cols="100" placeholder="Message" class="form-control" id="message" required="" data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
<div class="help-block"></div></div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>

How to send data to HTML page and how to use AJAX for Single Page Application in NodeJS Server using express.js framework?

How can I display the form submitted data in another HTML Page
From 1st page (page1.html)collecting the data from users and after appending this data in the database I want to show the submitted values in another page i.e.(page4.html)
Below is my code
I have tried using res.sendFile or res.send
server.post('/addname', (req, res) => {
const user = {
timestamp: new Date,
FName: req.body.FName,
LName: req.body.LName,
Phone: req.body.Phone,
Email: req.body.email,
Contact: req.body.business,
Business: req.body.contact,
OTP: req.body.otp_field
}
res.sendFile(__dirname + '/page4.html');
//along with file rediraction, how can i send or show the "User" vaules in respactivte filed
});
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
nAs I can see in your code
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
Your form method is "GET", it should be "POST" as your API is "POST".
server.post('/addname', (req, res) => {
<form action="/addname" method="GET">
//Just change to
<form action="/addname" method="POST">
While sending and HTML file you need to send your submitted data too.
res.sendFile(__dirname + '/page4.html');
In order to save your hurdle switch to Single Page Application and use some JavaScript frame work like AngularJs, ReactJs or if not then also stick to single page and use Ajax calls for submit calls.
Else see "ejs" in place of "HTML" and use scriptlet to send and show data over HTML.
To send data to "ejs" via expressJs
res.render('show.ejs', {message});
With Ajax you can do this:
HTML
<body>
<div>
<div align="center">
<form id="form1">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="button" value="Submit" onClick:"submitForm()"/>
</form>
<div id="showValue"></div>
</div>
</div>
</body>
JavaScript
function submitForm() {
$.ajax({
url: '/addName',
type: 'POST',
headers: headers,
data: {
"Fname": $("#FName").val(),
"Lname": $("#LName").val(),
"email": $("#email").val()
},
success: function(result) {
//append result to your html
//Dynamic view
$("#form1").hide();
var html = '<div><span>First Name: ' + result.fName + '</span><span>Last Name: ' + result.lName + '</span></div>';
$("#showValue").html(html);
},
error: function (error) {
alert('error ',error);
}
});
}
Server side code I'm assuming you are using express.js and body-parser
app.post('/addName', (req, res) => {
//Insert into db
var body = req.body;
res.send({
fName: body.FName,
lName: body.LName
});
});

Transfer table row data to html form page in angular

Using Angular JS I am trying to pass the data in a table row that is populated dynamically to an html page. The page would then use that object
that is passed to populate form data.
My html looks like below:
<form data-ng-submit="submit()" name="empRegForm" method="post">
<input type="hidden" type="text" ng-model="employee.employeeId" />
<fieldset class="table-striped">
<input placeholder="Employee Project Id" type="text" ng-model="employee.projectId" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="Employee Name" type="text" ng-model="employee.employeeName" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
Method that I have created on the controller is as follows:
$scope.updateEmployee = function(employee) {
var response = $http.put('localhost:8080/employeeManagement/employee', employee);
response.success(function(data, status, headers, config) {
$scope.result = data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
};
EmployeeList html table appears as below:
<tr ng-repeat="employee in result.listOfEntities">
<td>{{employee.employeeId}}</td>
<td>{{employee.employeeName}}</td>
<td><a ng-click="updateEmployee(employee)"> <span class="fa fa-pencil-square-o" aria-hidden="true"></span></a></td>
</tr>
I want to redirect the page to the Update html page that contains the form when this button on the row is clicked.
Thanks
Added ng-include to load different html page in your table page itself and to toggle it on need basis as like example below,
In controller:
$scope.loadEmployee = function(employee){
$scope.employee=employee;
$scope.employee.visible=true;
};
$scope.updateEmployee = function(employee) {
var response = $http.put('localhost:8080/employeeManagement/employee', employee);
response.success(function(data, status, headers, config) {
$scope.result = data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
$scope.employee.visible=false;
};
In Template:
<tr ng-repeat="employee in result.listOfEntities">
<td>{{employee.employeeId}}</td>
<td>{{employee.employeeName}}</td>
<td><a ng-click="loadEmployee(employee)"> <span class="fa fa-pencil-square-o" aria-hidden="true"></span></a></td>
</tr>
<div ng-include src="'/employee-update.html'" ng-controller="employeeController" ng-show="employee.visible"></div>
employee-update.html:
<form data-ng-submit="updateEmployee()" name="empRegForm" method="post">
<input type="hidden" type="text" ng-model="employee.employeeId" />
<fieldset class="table-striped">
<input placeholder="Employee Project Id" type="text" ng-model="employee.projectId" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="Employee Name" type="text" ng-model="employee.employeeName" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>

How to check if InputElement is a checkbox in Dart

I'm serializing some forms to JSON in dart:html
Map jsonifyForm(String formQuery){
FormElement form = querySelector(formQuery);
Map<String, String> data = {};
List<InputElement> inputs = form.querySelectorAll("input.json");
for (InputElement input in inputs) {
if (input is CheckboxInputElement){
print("checkbox: " + input.name + "|" + input.checked.toString());
data.putIfAbsent(input.name, () => input.checked);
} else {
print("text: " + input.name + "|" + input.value);
data.putIfAbsent(input.name, () => input.value);
}
}
print(data);
return data;
}
I have about a 100 input fields on the page, followed by only one checkbox:
<label>First Name</label>
<input type="text" class="form-control tip json" placeholder="First Name" name="firstName" value="" data-toggle="tooltip" data-placement="top" title="First Name"/>
<label>Last Name</label>
<input type="text" class="form-control tip json" placeholder="Last Name" name="lastName" value="" data-toggle="tooltip" data-placement="top" title="Last Name"/>
...
<label class="form-control tip" data-placement="top" title="VAT On Goods" data-toggle="tooltip">
<input class="json" type="checkbox" name="vatOnGoods">
VAT on goods
</label>
When I call jsonifyForm, I'm seeing that all inputs are being treated as checkboxes:
checkbox: firstName|false
checkbox: lastName|false
...
checkbox: vatOnGoods|false
{firstName: false, lastName: false, ..., vatOnGoods: false}
Is this a bug or am I doing something wrong here?
The class CheckboxInputElement only provides the value and checked attributes. I am still wondering why it says that those are all checkboxes. But you can just check the type attribute:
if(input.type == 'checkbox')
to check the type of the checkbox.

Putting value to hidden input and then getting it in POST variable

I am trying to get an input value with AngularJS from input field to another hidden input field (in another form in the same page) so I can transmit it later if user presses submit on the other form.
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
//down the code...
<form name="whatever" method="post">
<input type="hidden" ng-bind="name" value="">
</form>
</div>
When I inspect the code after I put data in the visible input field all looks fine - so when I change the data inside the visible input I can see it in the hidden input too but I can't see it in the POST variable after I submit the form - I guess it's because it doesn't change the value field in the hidden input just what between the and .
How can I get this to work so that I change the value of an hidden input - but not what between the opening and closing input field?
Just Replace ng-bind with ng-value like:
<input type="hidden" ng-value="name">
(Credit to Himmet Avsar)
I see you answered yourself already. Anyway you should go for more "angular way" when handling your forms, letting angular do the "posting". For example:
HTML template
<body ng-controller="MainCtrl">
<form name="form1"
ng-submit="submit()">
Name: <input type="text"
class="form-control"
name="name"
ng-model="user.name"
required>
<div class="alert alert-warning"
ng-show="form1.name.$error.required">
Required field
</div>
<input type="submit"
class="btn btn-primary"
value="submit">
</form>
<div class="alert"
ng-class="{ 'alert-success': response.status === 200, 'alert-danger': response.status !== 200 }"
ng-show="response !== null">
DATA: {{ response.data }}<br>
HTTP {{ response.status }} {{ response.statusText }}
</div>
<hr>
<form name="form2" ng-submit="submit()">
Name: <input type="text"
class="form-control"
ng-model="user.name">
Age: <input type="number"
class="form-control"
min="1"
max="100"
ng-model="user.age">
<input type="submit"
class="btn btn-primary"
value="submit" disabled>
</form>
</body>
JavaScript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.user = {};
$scope.response = null;
$scope.submit = function() {
$scope.response = null;
$http({
method: 'POST',
url: 'http://jsonplaceholder.typifcode.com/posts',
data: $scope.user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
$scope.response = response;
}).catch(function (response) {
$scope.response = response;
});
};
});
You'll get something like
Related plunker here http://plnkr.co/edit/M7zQzp