I have client side code that looks like this:
<form name="sendCoordinates" action="http://localhost:8080/geodata" method="post">
<label> MinLat: </label>
<input type="text" name="MinLat" value="0"><br>
<label> MaxLat: </label>
<input type="text" name="MaxLat" value="1"><br>
<label> MinLong: </label>
<input type="text" name="MinLong" value="0"><br>
<label> MaxLong: </label>
<input type="text" name="MaxLong" value="1"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData();
params = $form.serializeArray();
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log(result + "you");
}
});
});
</script>
I am sending this form data to an endpoint /geodata.
app.post("/geodata", function(req, res) {
console.log(req.body);
});
My question is, under a successful post, what would console.log(req.body) print on the server side? I am unable to tell yet as my client is not sending any information yet due to some bug. This will help me write my server side code according to the data I receive in the post request.
Looks like you're using Express. In general practice, request bodies are parsed as JSON (see Express req.body docs), but it depends on the parsing middleware you're using (body-parser is the common one in Express apps).
It also depends on the Content-Type header of the request. From the Express docs I mentioned above, they give an example:
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
It looks like you currently set contentType: false in your AJAX request, so that will just send raw data to your server.
To answer your question more concretely
My question is, under a successful post, what would console.log(req.body) print on the server side?
It depends on the Content-Type and what middleware (if any) you are using the parse request bodies.
Related
I am trying to send some form data to an endpoint.
Here's my client side code:
<form name="form" action="http://localhost:8080/geodata" method="post">
<label for="minlat"> MinLat: </label>
<input type="text" name="MinLat" value="0"><br>
<label for="maxlat"> MaxLat: </label>
<input type="text" name="MaxLat" value="1"><br>
<label for="minlong"> MinLong: </label>
<input type="text" name="MinLong" value="0"><br>
<label for="maxlong"> MaxLong: </label>
<input type="text" name="MaxLong" value="1"><br>
<button type="submit" class="btn btn-success"> Submit <span class="fa fa-arrow-right"></span></button>
</form>
<script>
$(document).ready(function() {
$("#form")
.submit(function(event) {
var formData = {
'minLat' : $('input[name=MinLat]').val(),
'maxLat' : $('input[name=MaxLat]').val(),
'minLong' : $('input[name=MinLong]').val(),
'maxLong' : $('input[name=MaxLong]').val()
};
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
dataType: 'json',
processData: false,
type: 'POST',
}).done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
I have an enpoint on the server side code (express.js):
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/geodata", function(req, res) {
console.log(req.body);
res.send("hi");
});
I wish to send this form data to the endpoint /geodata, and use that data to send a result back to the client side. First of all, when I hit submit, I get an empty {} in my terminal (which is the server side request.body). I was expecting form values in this request.body but don't receive them. How do I make sure my form values are being sent?
Secondly, res.send("hi") re-directs my initial page to a new page and prints "hi" there. Since I had made an ajax call, shouldn't the response just be logged and the webpage stays on the initial page?
Change the form action to '/geodata'(the endpoint)
also you dont need to make a ajax request as HTML5 forms will perform the request itself if a tag() is pressed/clicked.
after you click summit your page will become what ever response that is sent back from '/geodata' route
and req.body will return a object that represents the form data
dataType: 'json' means you are expecting json data from the server. remove dataType, and add this
data : JSON.stringify(formData),
contentType: 'application/json',
contentType would be the type of data you are sending to the server.
I have a basic script that is as follows:
$(".submit").click(function(){
var fd = new FormData();
fd.append('username', 'Bob');
$.ajax({
url: '/signup',
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log("Success: ", data);
}
});
});
When the request hits my server, I receive a req.body of {} (empty) and there is nothing in req that points to data being sent. Whats going on here? How can I send data with FormData?
I wanted to test getting basic preset data from FormData and was unsuccessful. The values console logged in Chrome show an empty formData object, with only its constructor and the available 'append' method.
I am using jQuery v 2.1.4 and HTML5 and have confirmed that window.FormData is a valid object in Google Chrome.
My goal is to have a form that a user can enter an email, password, avatar, and a profile background image with the following form:
<form id="msform" enctype="multipart/form-data" name="msform">
<!-- Progress Bar -->
<ul id="progressbar">
<li class="active">Basic Information</li>
<li>Profile Customization</li>
</ul>
<!-- Step One -->
<fieldset>
<h2 class="title">Basic Information</h2>
<input type="text" name="username" placeholder="Username" />
<input type="text" name="password" placeholder="Password" />
Avatar Image <input type='file' id='avatarImage' accept="image/*" name='avatarImage'>
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<!-- Step Two -->
<fieldset>
<h2 class="title">Profile Customization</h2>
<select id="dropdown" name="profileColor">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
Background Photo <input type='file' id='bgPhoto' accept="image/*" name='bgPhoto'> </div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit" />
</fieldset>
</form>
Whats going on with FormData, it seems like a valid object, but I'm unable to append anything to it. I've looked, and it appears that others have seen an empty object in their console, but the data 'automagically(?)' appears on their server? My first code block is basically a copy for the docs and I'm having trouble with it. Would and CORS issues or CDN errors be the case? Something maybe not able to access as it should? No errors print in the log, only a blank object on my post request.
Thanks for the help!
If you are using Express as the backend, body-parser does not handle multipart/form-data, and you are referred to using multiparty instead. You can integrate Express with multiparty like so :
var express = require('express');
var multiparty = require('multiparty');
var app = express();
var data = new multiparty.Form();
app.post('/signup', function(req, res) {
data.parse(req, function(err, fields, files) {
if(err) throw err;
Object.keys(fields).forEach(function(name) {
console.log('got field named : ' + name + ', value : ' + fields[name]);
});
Object.keys(files).forEach(function(name) {
console.log('got file named : ' + name);
});
});
});
Do include event.preventDefault() in your click event handler
$(".submit").click(function(e){
e.preventDefault();
var fd = new FormData();
fd.append('username', 'Bob');
...
});
You aren't preventing the default form submit event and neither are you catching a submit by keyboard if user hits enter.
Try:
$("#msform").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append('username', 'Bob');
$.ajax({
url: '/signup',
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log("Success: ", data);
}
});
});
If you aren't sending files I would suggest using the simpler approach of removing the processData and contentType options and using $(this).serialize() for the data value
I have an HTML form with two buttons (along with other text input areas), and I have some front end javascript code to handle the submit. On the submit, I create a FormData object and store the file in it. Then I send that through an jquery ajax request to a node.js server. However, this is where the problem is - when I try to access the file in the server, the file is always undefined - i've tried accessing it with req.body, req.files, req.file but its always undefined. Is this a problem with the ajax request, or the way i'm receiving it?
upload file button:
<input id="element_3" name="element_3" class="element file required" accept="application/pdf" type="file"/>
submit button:
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit"/>
handle submit:
$('#form_1039889').submit(function(event) {
event.preventDefault();
event.stopImmediatePropagation();
var file = $('#element_3').get(0).files[0];
var fd = new FormData();
fd.append('pdf', file);
$.ajax({
url: '/addPdf',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(response) {
//success TODO code
}
});
});
relevant server code:
app.post('/addPdf', [multer({dest: "./uploads/"}).single('avatar'), function(req, res) {
console.log("file: " + req.file);
}]);
Instead of single('avatar') use single('pdf.file') because you set pdf object for file.
Name that we pass inside Single should match with form-data key. So Change .single('avatar') with .single('pdf').
So your node js code will look like this:
app.post('/addPdf', [multer({dest: "./uploads/"}).single('pdf'), function(req, res) {
console.log("file: " + req.file);
}]);
I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.
I have searched the whole internet and I can't find a working way to log in to SugarCRM with Javascript. This is as close as I've gotten:
var params = {
user_auth:{
user_name:'jim',
password:'jim',
encryption:'PLAIN'
},
application_name: 'SugarCRM RestAPI Example'
}
var restdata = JSON.stringify(params);
$.ajax({
type: "POST",
url: "http://alzjgk0569.trial.sugarcrm.com/service/v4/rest.php?jsoncallback=?",
data: {
method: "login",
input_type: "JSON",
response_type: "JSON",
rest_data: restData
},
dataType:"jsonp",
success: function(result) {alert("result: " + JSON.stringify(result));},
failure: function() {alert("failed");}
});
Anyone have any ideas?
Thanks.
p.s. I should mention that the following works just fine:
<form action="https://alzjgk0569.trial.sugarcrm.com/rest/v10/oauth2/token" method="post">
grant_type: <input type="text" name="grant_type" value="password"><br>
client_id: <input type="text" name="client_id" value="sugar"><br>
client_secret: <input type="text" name="client_secret" value=""><br>
username: <input type="text" name="username" value="jim"><br>
password: <input type="text" name="password" value="jim"><br>
platform: <input type="text" name="platform" value="base"><br>
<input type="submit" value="Submit">
</form>
Edit:
I got it working by changing the url to begin with "https://" when this page is served with "https". But the response is this:
{\"user_auth\":{\"user_name\":\"jim\",\"password\":\"jim\",\"encryption\":\"PLAIN\"},\"application_name\":\"SugarCRM RestAPI Example\"}" = {"id":"1cg0ji99ouq0st6jndlcbo3075","module_name":"Users","name_value_list":{"user_id":{"name":"user_id","value":"seed_jim_id"},"user_name":{"name":"user_name","value":"jim"},"user_language":{"name":"user_language","value":"en_us"},"user_currency_id":{"name":"user_currency_id","value":"-99"},"user_is_admin":{"name":"user_is_admin","value":false},"user_default_team_id":{"name":"user_default_team_id","value":"1"},"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"},"user_default_timeformat":{"name":"user_default_timeformat","value":"h:ia"},"user_number_seperator":{"name":"user_number_seperator","value":","},"user_decimal_seperator":{"name":"user_decimal_seperator","value":"."},"mobile_max_list_entries":{"name":"mobile_max_list_entries","value":10},"mobile_max_subpanel_entries":{"name":"mobile_max_subpanel_entries","value":3},"user_currency_name":{"name":"user_currency_name","value":"US Dollar"}}}
This is completely useless information. It has no token, so it's not really even a real login. I'm giving up on client side SugarCRM login, and going back to server side with PHP, which I know works.
You actually have the answer here. Your login token is the id value in the response you posted.
SugarCRM API calls are better on the server side:
1. More secure
2. Does not have cross domain request issue due to the Same Origin Policy enforced by browsers. So JSONP is not needed.