I've an HTML form where I'm getting 2 inputs, which is submitted to a spring boot REST api. But in this simple application, I'm still receiving null as request in backend api.
Form
<div>
<label>alphaID</label>
<div>
<input id="alphaID" name="alphaID" type="text"/>
</div>
</div>
<div>
<label class="col-md-4 control-label">Domain Name</label>
<div class="col-md-4">
<input id="domain" name="domain" type="text"/>
</div>
</div>
Upon submit, I'm calling ajax call, like:
function formSubmit() {
$("#productForm").submit(function(e) {
e.preventDefault();
var requestJson = createRequestJSON();
var url = config.myurl;
$.ajax({
url: url,
type : "POST",
data: JSON.stringify(requestJson),
success: function( data, textStatus, jQxhr ) {
console.log("sucess: " + data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( "error: " + errorThrown );
}
});
});
}
The backend is a spring-boot application with REST call:
#RequestMapping(value = "/validate", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Map<String, List<String>> validate(#Valid MyDTO myDTO) {
System.out.println(myDTO.getId()); // GETTING null
System.out.println(myDTO.getDomain()); // GETTING null
}
MyDTO.java
public class MyDTO {
#JsonProperty("alpha_id")
private String alphaID;
#JsonProperty("domain")
private String domain;
....
}
Change your Content-Type to
consumes = MediaType.APPLICATION_JSON_VALUE
Add #RequestBody annotation
public Map<String, List<String>> validate(#Valid #RequestBody MyDTO myDTO)
Make sure you are calling proper URL and sending proper content-type from your browser request too.
It might be interesting to see if your requestJson actually has the correct format in order for the MyDTO to consume it.
You also don't have to Json.stringify you data. When you do this, you basically just send an string to the backend. The backend does not know that it hast to parse this string to get a valid document. You either just send the JavaScript object directly in the data property or you change the API to expect a String and parse it in the function later.
Related
My jQuery AJAX implementation does not work properly, so if i want add, delete, update a product, or retrieve all sites, it simply does not react to my clicks.
Here is my simple web-page that allows me to click but i donot get any result.
When someone wants to submit the form with the specified ID, all form fields are assigned to appropriate variables. After that, a new JSON document is generated based on the form field variables. Then the AJAX call is performed. It is directed to URL which is specified in the action attribute of form tag. The JSON is used as a data which needs to be processed.
You can downlaod my project from here
I get there errors:
localhost:8080/api/sites Failed to load resource: net::ERR_CONNECTION_REFUSED
2localhost:8080/api/sites/ Failed to load resource: net::ERR_CONNECTION_REFUSED
From my Java class:
#RequestMapping(method = RequestMethod.GET, value = "/api/sites")
public List<Site> getAllSites(){
return siteService.getAllSites();
}
#RequestMapping(method = RequestMethod.POST, value = "/api/sites")
public void addSite(#RequestBody Site site){
siteService.addSite(site);
}
A webpage to replicate the problem:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<hr><p> New page </p>
<input name="search" type="text" maxlength="100" id="search"/>
<button onclick="getAllSites()"> Show All </button>
<hr>
<hr>
<p> Id: <input name="search" type="text" maxlength="100" id="id"/></p>
<p> First name: <input name="search" type="text" maxlength="100" id="name"/></p>
<button onclick="addSite()"> Save </button>
<div id="site"></div>
<script>
function addSite()
{ var data = {
id: document.getElementById("id").value,
name: document.getElementById("name").value
}
$.ajax({
url: "http://localhost:8080/api/sites",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "POST",
dataType: "json",
data: JSON.stringify(data)
});
}
function getAllSites()
{
$("#site").html("");
$.getJSON("http://localhost:8080/api/sites/", function(data)
{
for (var i in data) {
$('#site').append("<p>ID: " + data[i].id + "</p>")
$('#site').append("<p>Name: " + data[i].name + "</p>")
}
});
}
</script>
</body>
</html>
Assuming that the ajax implementation is in a file for example: mySites.html and you need to test it directly from browser or from other site try this:
Go to SiteController.class
If you need to test your api outside of your localhost:8080 then add #CrossOrigin annotation to the specific method of SiteController.class, for example in this case I'm enabling CrossOrigin for two specific methods:
Method 1
#CrossOrigin(origins = "*")
#RequestMapping(method = RequestMethod.GET, value = "/api/sites")
public List<Site> getAllSites(){
return siteService.getAllSites();
}
Method 2
#CrossOrigin(origins = "*")
#RequestMapping(method = RequestMethod.POST, value = "/api/sites")
public void addSite(#RequestBody Site site){
siteService.addSite(site);
}
For more information about #CrossOrigin see the following documentation from spring site #CrossOrigin Document
My conclusion of this answer is because the first time that I ran the ajax implementation I got the No 'Access-Control-Allow-Origin' header exception from console developer, wich means that for security reasons the browser block the ajax request when it is outside of the rest api host.
All the rest of the components (backend java classes, spring) worked perfect after I get imported to my development environment.
Is it possible to automatically bind ASP.NET controllers model with an ajax request that submits data as FormData.
in my provided example I'm required to use HttpContext.Current.Request.Form["property_name"]
to receive data because if I provide a model that is identical to the submitted form data, all values are equal to null;
or does ASP.NET model binding only work on JSON requests ?
Simple code bellow:
View:
#using (Html.BeginForm("Post", "Test", FormMethod.Post, new { #class="test-form"}))
{
<input type="text" name="firstName"/>
<input type="text" name="lastName"/>
<button type="submit">Submit</button>
}
Scripts:
<script>
$('.test-form').on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "#Url.Action("TestPost", "Test")",
method: "POST",
data: formData,
processData: false,
success: function(e){
}
});
});
</script>
Controller:
[HttpPost]
public ActionResult TestPost()
{
var firstname = HttpContext.Current.Request.Form["firstName"];
var lastName = HttpContext.Current.Request.Form["lastName"];
return PartialView("TestPost");
}
Does Not Work Controller:
public class User
{
public string firstName { get; set; }
public string lastName { get; set; }
}
[HttpPost]
public ActionResult TestPost(User model) //model values are null
{
return PartialView("TestPost");
}
When you use a FormData object with ajax the data is sent as multipart/form-data and the content type header is set automatically for you with the correct boundary.
You can override the content type and set tit to whatever you want, which is what happens here.
You might be thinking well I didn't do it, well you good friend jQuery did it for you. It set the default content type for $.ajax for you (application/x-www-form-urlencoded) which pretty much craps up the request.
To stop this action i.e. to stop jQuery from setting a content type header you have to set the contentType parameter to false.
I am trying to display some data from my database that is dependent on some input from the user. I am using an ajax request to get the data, send it back to a function in my controller, and then export it back to my view. I would like to collect this data and display it without going to another view (I just hide the previous form and unhide the new form).
Here is the relevant code:
Javascript:
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
Controller functions:
public function pick_favorite() {
$fbid=Input::get('fbid');
return Artist::specific_artist($fbid);
}
public function getWelcome() {
return View::make('fans.welcome')
->with('artists', Artist::artists_all())
->with('favorite_artist', Artist::favorite_artist())
->with('pick', FansController::pick_favorite());
}
Model function:
public static function specific_artist($fbid) {
$specific_artist = DB::table('artists')
->where('artists.fbid', '=', $fbid)
->get();
return $specific_artist;
}
The view is on the "welcome" page. My question is how do I display the model data in my view and make sure it is printing out the correct data from the fbid input?
I tried something like this:
#foreach($pick as $p)
<span class="artist_text">{{$p->stage_name}}</span>
<br>
<span class="artist_city">{{$p->city}}</span>
#endforeach
but this is not printing out anything. Any ideas?
i see lots of issues here.
Server side:
public function pick_favorite().... what does it do? it just returns some data.
in public function getWelcome() { , you wrote, FansController::pick_favorite(). supposing both are the same method, you are accessing a static method whilst the method is non static. you are getting an error for this but you are not seeing it because you didn't define fail().
and i don't see what the point of declaring a method which does nothing else then a model call which you can do directly.
e.g let's say i have a fooModel
public function index(){}
in controller, i can just write,
public function bar()
{
$model = new fooModel;
return View::make(array('param1'=>$model->index()));
}
or if i declare index() method in fooModel as static, then i can write,
public function bar()
{
return View::make(array('param1'=>fooModel::index()));
}
Client side:
now in your javascript,
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
why it should print any data? you didn't asked the script to print anything. where is your .done or .success param in your code?
If you look at your console, you'l get lots of php errors, i am almost sure of.
an advice, you need to lear some basics. e.g. jquery ajax call.
a basic ajax call can be
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
implement it in your code and then see what errors it throws.
Conclusion:
1st one will be (supposing rest of your codes are ok) the static error. if you want to call it as static, declare it as static. but a static function in controller? i don't see any purpose of it.
and then start the debug. your problem is both client and server side. deal one by one.
Below code returns me a object response:
#RequestMapping(value = "/NewLogin",method = RequestMethod.POST)
public #ResponseBody Token getAllBooks(
Token token = new Token();
token.setValue(encryptedMessage);
return token;}
On clicking the following button on jsp page :
<input type="button" onClick="madeAjaxCall();" value="Ajax Submit">
<script type="text/javascript">
function madeAjaxCall(){
$.ajax({
type: "post",
url: "http://localhost:8011/nLiveSite/livesearch/NewLogin",
cache: false,
success: function(response){
$('#result').html("");
var obj = response;
console.log(obj);
$('#result').html("Message:- " + obj );
},
error: function(){
alert('Error while request..');
}
}).responseText;
} ;
</script>
Ajax Submit button is returning me content of jsp page as response. I need only object (i.e. token) as response on button click.
Do like this.....#url
url:"${pageContext.request.contextPath}/NewLogin"
Well, you are expecting a HTTP POST request in your Rest API (besides the typos), however you are setting the Request type to "GET" in your AJAX request. Furthermore, the URL in your request doesn't match to "/NewLogin".
I'm trying to complete some ajax requests to insert a textarea into a database without refresh. Here is my code:
HTML:
<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
JS:
function UpdateStatus(Status)
{
var Status = $(this).val();
$(function()
{
$.ajax({
url: 'Ajax/StatusUpdate.php?Status='.Status, data: "", dataType: 'json'
});
});
}
My Questions:
1) How do I send the contents of the text area into the onclick function?
2) How do I escape/urlencode etc.. So it retains line breaks
<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>
You have few problems with your code like using . for concatenation
Try this -
$(function () {
$('input').on('click', function () {
var Status = $(this).val();
$.ajax({
url: 'Ajax/StatusUpdate.php',
data: {
text: $("textarea[name=Status]").val(),
Status: Status
},
dataType : 'json'
});
});
});
Tried and working. you are using,
<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
I am using javascript, (don't know about php), use id="status" in textarea like
<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
then make a call to servlet sending the status to backend for updating using whatever structure (like MVC in java or any other) you like, like this in your UI in script tag
<script>
function UpdateStatus(){
//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({
type:"GET",//or POST
url:'http://localhost:7080/ajaxforjson/Testajax',
// (or whatever your url is)
data:{data1:var1},
//can send multipledata like {data1:var1,data2:var2,data3:var3
//can use dataType:'text/html' or 'json' if response type expected
success:function(responsedata){
// process on data
alert("got response as "+"'"+responsedata+"'");
}
})
}
</script>
and jsp is like the servlet will look like:
//webservlet("/zcvdzv") is just for url annotation
#WebServlet("/Testajax")
public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String data1=request.getParameter("data1");
//do processing on datas pass in other java class to add to DB
// i am adding or concatenate
String data="i Got : "+"'"+data1+"' ";
System.out.println(" data1 : "+data1+"\n data "+data);
response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}