Formdata not getting populated - javascript

I currently have a webpage hitting a webservice to send multipart/form-data but somehow the fields are not getting appended into the formdata object. Could someone help me out ?
index.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Sample upload</title>
<script type="text/javascript" src="webjars/jquery/3.2.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
/>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#dataform')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/save",
data: data,
//http://api.jquery.com/jQuery.ajax/
//https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
</script>
</head>
<body>
<h1>SampleCardSubmit</h1>
<form id="dataform" method="POST" enctype="multipart/form-data">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Section I:To be filled by Partner</h4>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-sm-5 control-label">Partner Name:</label>
<div class="col-sm-5">
<input id="name" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Photograph of
applicant:</label>
<div class="col-sm-5">
<input id="photo" type="file" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner OLM ID:</label>
<div class="col-sm-5">
<input id="olmid" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner Mobile
Number:</label>
<div class="col-sm-5">
<input id="mobile" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner Email:</label>
<div class="col-sm-5">
<input id="email" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Disability:</label>
<div class="col-sm-5">
<select id="disabibilty" class="form-control">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner Company Name:</label>
<div class="col-sm-5">
<input id="company" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Name of Partner on
Company ID:</label>
<div class="col-sm-5">
<input id="nameoncard" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-sm-5">
<input id="btnSubmit" type="submit" class="btn btn-primary"/>
</div>
</div>
</div>
</div>
</form>
<h1>Ajax Post Result</h1>
<span id="result"></span>
</body>
</html>
Controller
#RestController
public class CardController {
#Autowired
private CardService cardService;
#RequestMapping(value="/save", method = RequestMethod.POST)
public ResponseEntity<?> multiUploadFileModel(#ModelAttribute Card card) {
cardService.saveCard(card);
return new ResponseEntity("Successfully uploaded!", HttpStatus.OK);
}
}
Model
#Entity
public class Card {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private Blob photo;
#Column(unique=true)
private String olmId;
private String mobileNumber;
private String email;
private String disability;
private String partnerCompany;
private String nameOnCompanyCard;
Request Payload on clicking the submit button is this:
------WebKitFormBoundary1NqBHFrbwUgHBc7g
Content-Disposition: form-data; name="CustomField"
This is some extra data, testing
------WebKitFormBoundary1NqBHFrbwUgHBc7g--
Comments regarding handling on the backend are also appreciated.
Help please!!

As provided in my comment, you had forgotten the "name" parameter in your <input>, <select>, etc.
This causes the fields and their data not to be added to the resulting POST (since the browser doesn't know what to do with it).

You can try this below logic by adding x-www-form-urlencoded in the header and adding your data as shown below. Let me know if it works out for you.
$.ajax({
type: "POST",
url: "/save",
headers: {
'Content-Type': 'appliation/x-www-form-urlencoded',
'Authorization': 'Basic VGV.... Uy' // Add authorization if required
},
data: {
"CustomField", "This is some extra data, testing",
..... // More attributes if any
},
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});

Related

My data is not getting posted to the server in AngularJS

I have added all the scripts required. The services are in asp.net, I have added as well the HTTP POST method in web.config file.
HTML form:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="Scripts/angular.js"></script>
<script src="Scripts/InsertSession.js"></script>
</head>
<body ng-app="myModule1">
<div ng-controller="mycontroller1">
<form class="form-horizontal style-form" name="myform" >
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Event Title </label>
<div class="col-sm-10">
<input type="text" id="title" name="title" class="form-control" ng-model="title1">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Event </label>
<div class="col-md-4">
<input class="form-control" type="date" id="eventdate" name="eventdate" ng-model="eventdate">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Time of Event </label>
<div class="col-md-4">
<input class="form-control" type="time" id="eventtime" name="eventtime" ng-model="eventtime">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Event Location</label>
<div class="col-sm-10">
<input type="text" id="location" name="location" class="form-control" ng-model="eventlocation1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Event description</label>
<div class="col-sm-10">
<input type="text" id="description" name=" description" class="form-control" ng-model="description1">
</div>
</div>
<div>
<button class="btn btn-theme btn-block" value="Create Event" ng-click="registereventdata()"> Submit </button>
</div>
</form>
<!--ng-click="registereventdata()" , ng-click="Insert(formdata)" ,type="submit"-->
</div>
</body>
</html>
AngularJS code:
var myapp = angular.module('myModule1', []);
myapp.controller("mycontroller1", function ($scope, $http,$window) {
$scope.registereventdata = function () {
$http({
method: 'POST',
url: 'WebService1.asmx/InsertSessionData',
headers: {
'content-type': 'application/json; charset=utf-8',
'datatype': 'json'
},
data: { Title: $scope.title1, Date: $scope.eventdate, Time: $scope.eventtime, Location: $scope.eventlocation1, Description: $scope.description1, CreatedDate: $scope.eventdate, Email: "xyz", IsActive: true, IsDelete: false }
}).then(function (response) {
if (response.data.d > 0) {
alert("event add successfully.");
}
else {
alert("opss!!!not register event..try again");
}
})
}
});

Javascript code returns Unhandled Promise Rejection: AbortError: The operation was aborted

I am trying to run a simple contact form with html and javascript. I am trying to get filled out a contact form and then post the data to api. Upon page load I immediately get an error for Unhandled promise rejection.
HTML is:
<form id="contact-form"method="post" class="form-horizontal contact-form" action="#">
<!-- Honeypot SPAM Protection -->
<input type="text" name="cf[honeypot]" style="display: none">
<!-- END Honeypot SPAM Protection -->
<div class="form-group">
<div class="col-md-6">
<input type="text" name="cf[name]" class="form-control required" placeholder="İsim">
</div>
<div class="col-md-6">
<input type="email" name="cf[email]" class="form-control required email" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="url" name="cf[url]" class="form-control url" placeholder="URL">
</div>
<div class="col-md-6">
<input type="text" name="cf[subject]" class="form-control required" placeholder="Konu">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<textarea name="cf[message]" rows="6" class="form-control required" placeholder="Mesaj"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="submit" value="Gönder" class="btn btn-sm btn-block btn-primary">
</div>
</div>
</form>
<script type="text/javascript" src="assets/js/signup.js"></script>
And the javascript code is:
$(document).ready(function() {
$("contact-form").submit(function(e){
e.preventDefault();
var form=this;
var URL = "https://v9jg33e7pa.execute-api.us-east-1.amazonaws.com/beta/sendemail/";
var data = {
name: $(form).find("#cf[name]").val(),
email: $(form).find("#cf[email]").val(),
urlContact: $(form).find("#cf[url]").val(),
subject: $(form).find("#cf[subject]").val(),
message: $(form).find("#cf[message]").val()
};
console.log(data);
if (""===$(form).find("#cf[honeypot]").val()){
$.ajax({
type: "POST",
url: URL,
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("yay");
},
error: function () {
// show an error message
alert("boo");
},
});
}
});
});
But when loading the page I get the following error:
Could not figure out what I am doing wrong?

Sending POST request to REST endpoint using Jquery

I want to submit all fields from registration form and store them in PostgreSQL database. I'm using Spring MVC and jQuery. POST request to /save is working only using Postman. When I click on Register button to submit form it gives me -
"Request method 'POST' not supported".
Can anybody help me?
User Controller:
#RestController
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(method=RequestMethod.POST, value="/save", headers="Accept=application/x-www-form-urlencoded")
public void registerUser(#RequestBody User user) {
userService.registerUser(user);
}
}
PageController:
#Controller
public class PageController {
#RequestMapping("/login")
public String login () {
return "index.html";
}
}
Model:
#Entity
#Data
#Table(name="users")
public class User {
#Id #GeneratedValue
private long id;
#Column(name="sex")
private String sex;
#Column(name="skype")
private String skype;
#Column(name="username")
private String userName;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
protected User(){};
}
HTML:
<!doctype html>
<html>
<head>
<title>Login / Register</title>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
rel="stylesheet" type="text/css">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-
awesome.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/login.js"></script>
</head>
<body>
<br>
<div class="row">
<div class="container">
<div class="login-register-form-section">
<ul class="nav nav-tabs" role="tablist">
<li class="active"><a href="#login" data-
toggle="tab">Login</a></li>
<li>Register</li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active"
id="login">
<form class="form-horizontal" method="post" action="">
<div class="form-group " >
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user"></i></div>
<input type="text" name="login_email" class="form-control" placeholder="Username or email" required="required" value="">
</div>
</div>
<div class="form-group ">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-key"></i></div>
<input type="password" name="login_password" class="form-control" placeholder="Password" required="required">
</div>
</div>
<div class="form-group">
<input type="checkbox" id="rememberMe">
<label for="rememberMe">Remember Me</label>
Forgot password?
</div>
<input type="submit" value="Login" class="btn btn-success btn-custom">
</form>
</div>
<div role="tabpanel" class="tab-pane fade" id="register">
<form class="form-horizontal" method="post" action="">
<div class="form-group" id="sex">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user"></i></div>
<select type="text" name="gender" class="form-control">
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<div class="form-group ">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-male"></i></div>
<input type="text" name="register_username" class="form-control" placeholder="Username" required="required" value="">
</div>
</div>
<div class="form-group ">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-envelope"></i></div>
<input type="email" name="register_email" class="form-control" placeholder="Email" required="required" value="">
</div>
</div>
<div class="form-group ">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-skype"></i></div>
<input type="text" name="register_skype" class="form-control" placeholder="Skype name" required="required" value="">
</div>
</div>
<div class="form-group ">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-lock"></i></div>
<input type="password" name="register_password" class="form-control" placeholder="Password" required="required">
</div>
</div>
<input type="submit" id="submitbtn" value="Register" class="btn btn-success btn-custom">
</form>
</div>
</div>
</div>
</div>
</div>
jQuery:
jQuery(document).ready(
function($) {
$("#submitbtn").click(function(event) {
var data = {}
data["sex"] = $("#sex").val();
data["skype"] = $("#register_username").val();
data["username"] = $("#register_email").val();
data["email"] = $("#register_skype").val();
data["password"] = $("#register_password").val();
$("#submitbtn").prop("disabled", true);
$.ajax({
type: "POST",
contentType: "application/json",
url: "/save",
data: JSON.stringify(data),
dataType: 'json',
timeout: 600000,
success: function (data) {
console.log("DONE");
},
error: function (e) {
console.log("ERROR: ", e);
display(e);
}
});
});
});
You're sending application/json in your ajax call, but in your controller, you say that your endpoint only accepts application/x-www-form-urlencoded.
You can change your controller to accept application/json:
#RequestMapping(method=RequestMethod.POST, value="/save", headers="Accept=application/json")
To avoid typos, you could also use the #RequestMapping's consumes attribute, and pass it a MediaType constant:
#RequestMapping(method=RequestMethod.POST, value="/save", consumes=MediaType.APPLICATION_JSON_VALUE)
Or you can refactor your ajax call to send the serialized form data.
As #sparrow suggests, you may also want to change your button's type attribute to button in order to avoid the default browser submit behavior. Alternatively, you can call event.preventDefault(); inside your click handler function to accomplish the same thing, but it doesn't make much sense to use type="submit" unless you're actually wanting to use the browser's default submit behavior.
Instead of doing input type='submit' can you try using input type='button'
change the line data["username"] = $("#register_email").val(); to data["userName"] = $("#register_email").val();
Ok, the problem is that I wasnt selecting the dom elements correctly, instead of id="email" I was using name="email".
<input type="text" name="register_skype" ...... >

Not getting Formdata in post using ajax

I'm trying to get formdata to my php file. but i'm getting not any value on post. please advice me what i'm doing is right? i'm doing something wrong in post
// add item to additem
<script type="text/javascript">
$(document).ready(function(){
$("#additembutton").click(function(evt){
evt.preventDefault();
var formData = new FormData($("form #itemform")[0]);
alert(formData);
$.ajax({
url: 'additem.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
</script>
// form submit image
This is my additem.php file
<?php
include '../class/dbconfig.php';
$filename=$_POST['myfile']['name'];
echo $_POST['myfile'];
This is my html form
<form class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="select" class="col-md-3 control-label">Menu Type</label>
<div class="col-md-6">
<select class="form-control" id="menutype">
<option>Select Menu</option>
<option value="fastfood">FastFood</option>
<option value="other">Other</option>
</select>
</div>
</div>
<!--
<div class="form-group" id="otherdiv">
<label for="menuorder" class="col-md-3 control-label">Other Menu Type</label>
<div class="col-md-6">
<input type="number" class="form-control" id="othermenu" placeholder="Enter Order">
</div>
</div>
-->
<div class="form-group">
<label for="menuorder" class="col-md-3 control-label">Menu Order</label>
<div class="col-md-6">
<input type="number" class="form-control" id="menuorder" pattern="[0-9]+" placeholder="Enter Order">
</div>
</div>
<div class="form-group">
<label for="select" class="col-md-3 control-label">Menu Status</label>
<div class="col-md-6">
<select class="form-control" id="menustatus">
<option value="1">Active</option>
<option value="0">Deactive</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="button" class="btn btn-primary" id="addmenubutton" >Submit</button>
</div>
</div>
</form>
You just need to send the form via post:
<form method="POST">

How to change view in Knockout JS

i have a short question. I am using Knockout JS and having this view and ViewModel:
var LoginViewModel = function () {
var self = this;
self.userName = ko.observable();
self.userPassword = ko.observable();
self.signin = function () {
data = ko.toJSON(self);
$.ajax({
url: "/signin",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data, textStatus, xhr) {
alert(xhr.status);
// If status == 200(OK) change view
},
error: function (jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
}
ko.applyBindings(new LoginViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<div class="container">
<div class="col-md-4 col-md-offset-4" data-bind="visible: isVisible">
<div class="panel panel-default">
<div class="panel-heading" style="text-align: center;">
<strong class="">SEHA</strong>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="username" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input class="form-control" required="" type="text" data-bind="value: userName">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-3 control-label">Password</label>
<div class="col-sm-9">
<input class="form-control" required="" type="password" data-bind="value: userPassword">
</div>
</div>
<div class="form-group last">
<div class="col-sm-offset-3 col-sm-9">
<button class="btn btn-success btn-sm" data-bind="click: signin">Sign in</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">
~
</div>
</div>
</div>
</div>
I want now to change the "view" if the user logs in. How can i accomplish that?
I also would to like to select a new view model for the next view. How would i do that?
That are my first steps with javascript / knockout, so please be kind.
If you handle the Server part of your application, you might want to return a Redirect Code 301 and specifying the URL to redirect.
Else, you can handle this Client Side, with the javascript code:
window.location.replace("./Home.html");

Categories

Resources