Javascript post String with ajax to backend(java) - javascript

I'm programming a commentary box for a Web Client.
I have two tables, one for the Comments and one for the Users. I want to send Input Data from my <input> tags in HTML form to my Java Service. In this Service, I handle the received data. My Problem now is, that I get an HTTP-415 error and I don't know what to do Right now.
I am using AJAX in JavaScript to post the Data.
HTML
ID: <input type="text" name="id" value="1" readonly/> <br/>
Author: <input type="text" name="author"/> <br/>
comment: <input type="text" name="comment"/> <br/>
<button id="submit" type="Button" >Submit</button>
Javascript
function addPost(givenID){
var $author = $("#author");
var $comment= $("#comment");
var $id = $("#id")
$("#submit").on("click", function(){
var post = $author.val()+"*"+ $id.val()+"*"+ $comment.val();
$.ajax({
type: "POST",
url: "api/kommentar",
data: post,
success: function(){
console.log("SUCCESS");
},
error: function(){
console.log("FAILIURE");
}
});
});}
Java
#Path("/kommentar")
public class KommentarService {
#EJB
private KommentarManagement postMgmt;
public KommentarService() { }
#POST
#Consumes("text/plain")
public void addPostsAsJson(String income) {
System.out.println(income);
//CODE TO HANDLE...
}

jQuery's default content type for the Ajax function is 'application/x-www-form-urlencoded; charset=UTF-8'.
Because the service is expecting 'text/plain' the content type needs changed.
Add a content type:
data: post,
contentType: 'text/plain', //<--- insert
success: function(){

Related

Null value when posting data from a html form to a c# controller method using a JavaScript function

I am teaching myself how to program and I am having a hard time identifying an issue with my most recent experiment. The following is within the context of an 'ASP.NET Web Application (.NetFramework) C#' and MVC architecture.
I am attempting to post data from a html form to a c# controller method using a JavaScript function.
The JavaScript function invokes the controller method; however, the string passed to the method always has a null value. (I know that the new 'Organisation' instance is successfully created, as new instances appear with an ID in my database yet with a null name - as per my model).
I have searched similar questions and tested contentType: application/json; charset=utf-8 also; however, my issue persists.
The error reads: System.ArgumentNullException: 'Value cannot be null. Parameter name: s' and occurs at var jsonDataParsed = JObject.Parse(jsonData); in my c# controller method.
I was hoping someone may be kind enough to help me :)
The form:
<form id="createOrganisationForm">
<label for="organisationName">Organisation name</label>
<input type="text" id="organisationName" />
<input type="submit" onclick="createOrganisation()" value="submit" />
</form>
The Javascript function:
function createOrganisation() {
var formData = {
"OrganisationName": $("#organisationName").val()
}
$.ajax({
url: '#Url.Action("CreateOrganisation", "Organisations")',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: JSON.stringify(formData)
})
}
The c# method in a controller:
[HttpPost]
public void CreateOrganisation(string jsonData)
{
var jsonDataParsed = JObject.Parse(jsonData);
var organisationName = jsonDataParsed["OrganisationName"].ToString();
var organisation = new Organisation();
organisation.Name = organisationName;
db.Organisations.Add(organisation);
db.SaveChanges();
}
The model:
public class Organisation
{
public int OrganisationID { get; set; }
public string Name { get; set; }
}
Try this:
function createOrganisation() {
var formData = {
"OrganisationName": $("#organisationName").val()
}
$.ajax({
url: '#Url.Action("CreateOrganisation", "Organisations")',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: 'json',
data: {'formData': formData }
})
}
Thank you everyone for your help. Special thanks go to #Teemu for pointing me towards the final solution.
Below is a working solution; I hope this may help others with future issues.
Key changes:
name="organisationName" atrribute added to input
<input type="submit" edited to <button type="button"
"parameter=" added to data: in ajax request
["OrganisationName"] edited to ["organisationName"] in C# method
Please refer to #Teemu advice in the question's comment section for the rationale behind these changes.
The HTML form:
<form id="createOrganisationForm">
<label for="organisationName">Organisation name</label>
<input type="text" id="organisationName" name="organisationName" />
<button type="button" onclick="createOrganisation()">Submit</button>
</form>
The JavaScript function:
function createOrganisation() {
var formData = JSON.stringify({ organisationName: $("#organisationName").val()})
$.ajax({
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: "jsonData=" + formData,
url: '#Url.Action("CreateOrganisation", "Organisations")',
type: "POST"
})
}
Helpful note: the above script should be in the view file (not an external file) if you are using a razor #URL.Action
The c# controller method:
[HttpPost]
public void CreateOrganisation(string jsonData)
{
var jsonDataParsed = JObject.Parse(jsonData);
var organisationName = jsonDataParsed["organisationName"].ToString();
var organisation = new Organisation();
organisation.Name = organisationName;
db.Organisations.Add(organisation);
db.SaveChanges();
}

Form ajax post data to php file [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 5 years ago.
Hi i trying make form using ajax. But i get some problems to sending form vars to php file. I get error: Undefined index: name.
I check chrome dev tools and i see variable is sending. But when made echo json_encode i see in php file i get empty array. So i dont have any idea where i made misstake.
file Main.js
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
function formLogin(name, lname)
{
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
Html form:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin(name, lname)">
</form>
Php Code:
$dane = $_POST;
echo json_encode($dane);
Chrome dev:
I just want figure how can i echo this variables(name,lname) in php file register.php
Version with serialize:
function formLogin() {
var dane = $('form').serialize();
$.ajax({
url: 'database/register.php',
data: {'dane': dane},
method: 'post',
success: function(data) {
console.log(data);
}
});
}
Then result console:
<pre class='xdebug-var-dump' dir='ltr'>
<small>D:\xampp\htdocs\szkola\database\register.php:8:</small>
<b>array</b> <i>(size=1)</i>
'dane' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>''</font> <i>(length=0)</i>
</pre>
jquery-3.2.1.min.js:4 XHR finished loading: POST "http://localhost/szkola/database/register.php".
But when i go to http://localhost/szkola/database/register.php
i get this:
D:\xampp\htdocs\szkola\database\register.php:8:
array (size=0)
empty
You need to change the way you define your variables in your Javascript and declare them inside your function, not outside :
function formLogin(){
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
And you need to update your HTML the same way (formLogin() instead of formLogin(...,...)) :
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin()">
</form>
Try using method instead of type.
The HTML:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name" name="name"><br />
Nazwisko: <input type="text" id="user_lastname" name="lname"><br />
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin();">
</form>
The JavaScript:
function formLogin() {
// Serialize the form
var data = $('form').serialize();
// Ajax call
$.ajax({
url: 'database/register.php',
data: data,
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
}
Also remember that you're requesting a JSON so you have to echo a json_encode($array) in your PHP file for a simple string will not be returned.

How to send values and image form javascript to controller in spring MVC

This is the jsp code,
Username: <input type="text" name="user_name"/>
File: <input type="file" name="profile_img" />
<input type="submit" value="Save" onclick="saveProfileData()"/>
And this is the javscript code,
function saveProfileData() {
var user_name = document.getElementById("user_name").value;
var profile_img = document.getElementById("profile_img").value;
$.ajax({
type: "POST",
url: /login/saveProfileData,
data:{
"user_name": user_name,
"profile_img":profile_img
},
success: function(response){
//other code
},
error: function(e){
//alert('Error: ' + e);
}
});
}
#ResponseBody
#RequestMapping(value="/saveProfileData", method=RequestMethod.POST)
public int saveProfileData(#RequestParam(required=false) String user_name, MultipartFile profile_img) {
System.out.println(user_name);
//int i = code for save profile data.
return i;
}
When I click on save button, It gives this error The current request is not a multipart request.
Why this is happening and how to fix this? How can I send the values with image?
Please anyone help me.?
Have you tried adding the encodingtype of the input field for the file, like such:
File: <input type="file" name="profile_img" enctype = "multipart/form-data"/>

MVC 4 Ajax Asynchronous File Upload Always Passing Null Value To Controller

I'm having a problem when trying to upload file asynchronously from ajax to my controller. I have 3 variables to pass (PictureId, PictureName, and PictureFile). The problem lies on my "PictureFile" variable which should be holding the uploaded file itself but instead it always pass null value to the controller.
Here is my view model
public class PictureUpload
{
public int PictureId { get; set; }
public string PictureName { get; set; }
public HttpPostedFileBase PictureFile { get; set; }
}
Here is my controller
public JsonResult EditPicture(PictureUpload picture)
{
//do something here
}
Here is my form
<div class="thumbnail" id="uploadForm">
<form name="uploadForm" enctype="multipart/form-data">
<input type="text" name="fileId" hidden="hidden" />
<input type="file" name="file" style="max-width: 100%" />
<input type="button" name="cancel" value="cancel" />
<span>
<input type="button" name="upload" value="upload" />
</span>
</form>
</div>
Here is my script
$("input[name=upload]").click(function () {
var $pictureId = $("input[name=fileId]").val();
var $pictureFile = $("input[name=file]").get(0).files[0];
$.ajax({
type: 'POST',
url: '#Url.Action("EditPicture", "Restaurant")',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify({ PictureId: $pictureId, PictureName: $pictureFile.name, PictureFile: $pictureFile }),
});
In my controller parameter. "PictureId" and "PictureName" holds the correct value, but "PictureFile" is always null. So it means something is going just not right when the system passes the parameter from ajax to controller. Somehow the system treats "file" type differently from others. Could you help me so the file get passed successfully to the controller and tell me what is wrong with this approach?
As mentioned rightly in the comments use FormData. Below is a code snippet :
var fd = new FormData();
fd.append('file', fileObject);
fd.append('PictureId', pictureId);
fd.append('PictureName', pictureName);
$.ajax({
url: '/Restaurant/EditPicture',
async: true,
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function (response) {
}
});
You cannot upload files with AJAX. One way to achieve this is to use a hidden iframe which will simulate an AJAX call and perform the actual file upload or use Flash.

post html form in json format using ajax to Django

I have the below html form, which I would like to post to a url using ajax in JSON format,
I am unable to receive the response in Django (backend), please advise where I am going wrong.
Here is my html form.
<form id ="addressform" >
<input type="text" name="DoorNo" id="text-basic" value="" placeholder="Door no.">
<input type="text" name="BuildingName" id="text-basic" value="" placeholder="Building/Road Name">
<button type="submit" onclick="addressform()" >Submit</button>
</form>
Here is my jQuery
function addressform() {
var data = $('#addressform').serializeArray();
$.post('/suggestions', data);
}
Here is my function in views.py in Django (backend).
def suggestions(request):
data = json.loads(request.body)
#print data
return HttpResponse( json.dumps({"status" : 1}) )
Can you add the URL above that you direct to?
function addressform() {
$.ajax({
url : "{% url 'app:your_view' %}",
type: "POST",
data: { ... },
success : function(json) {
//success!
console.log(json);
},
error : function(xhr,errmsg,err) {
// what to do it there is an error
}
});
};
})
Also depending on the version of python you are using. You could use
return JsonResponse(data_you_want)
I'm a little confused as to what you're doing in your view...

Categories