I have a form to edit user and i would like to insert user data from database into forms' fields. What i do is
Link
Edit
Script
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
}
Form
<div id="edit-form" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<form:form>
<fieldset>
<label for="elogin">Login</label>
<input type="text" name="elogin" id="elogin" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form:form>
</div>
My Spring controller returns following(in wrapper i have field login)
#RequestMapping(value="/edit/{userLogin}", method=RequestMethod.POST)
#ResponseBody
public Wrapper edit(#PathVariable String userLogin) {
return wrapper.wrap(userService.findByLogin(userLogin));
}
But the form is empty. I also tried to set manual values but still no use. Please help me set input field value.
You should send your form data with your post request.
$.ajax({
url: url,
type: "POST",
data:$('form').serialize(),
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('#elogin').val(resp.login);
}
})
}
Should work just fine, as you've set an ID for the input.
Not quite sure you have the order right, surely you would make the ajax call first and then open up the jQuery dialog?
Either way, you could supply data into the dialog as follows;
//call ajax method to get value you want to show.
var somevariable = etc.....
var dto = {
loginName: somevariable
}
$( "#edit-form" ).data('params', dto).dialog( 'open' );
Then in your dialog use the open() method.
$("#edit-form").dialog({
bgiframe: true,
autoOpen: false,
height: 280,
width: 320,
draggable: false,
resizable: false,
modal: true,
open: function () {
//so values set in dialog remain available in postback form
$(this).parent().appendTo("form");
//get any data params that may have been supplied.
if ($(this).data('params') !== undefined) {
//stuff your data into the field
$("#elogin").val($(this).data('params').loginName);
}
}
});
Related
I've googled for the past 2 days and still can't find a solution to this problem. I can upload fine using the input element with type attribute set to file. But I cannot upload the cropped image using croppie to the server.
Here is my register.scala.html:
#helper.form(action = routes.ProfilesController.upload, 'id -> "profileForm", 'class -> "", 'enctype -> "multipart/form-data") {
#CSRF.formField
<div class="col-6 col-md-3 pic-padding">
<div id="upload-demo" class="upload-demo pic-1 mx-auto d-block rounded">
</div>
<div class="pic-number" href="#">1</div>
<label for="upload-pic1" class="pic-control-bg">
<img src="#routes.Assets.versioned("images/plus.png")" class="pic-control">
</label>
<input type="file" id="upload-pic1" name="pic1" class="upload-btn" accept="image/*">
<button type="button" class="upload-result">Result</button>
<script>
Demo.init();
</script>
</div>
}
Here is my main.js:
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "http://localhost:9000/upload",
type: "POST",
data: {"image":resp},
success: function (data) {
alert(resp);
}
});
});
});
Here is my ProfilesController.java
public Result upload() {
File file = request().body().asRaw().asFile();
return ok("File uploaded");
}
Here is a snippet from routes file:
POST /upload controllers.ProfilesController.upload()
The error i get with the above solution is:
[CompletionException: java.lang.NullPointerException]
Please help! This has been stressing me out for the past 2 days, I just can't figure it out.
This is not fully solved, but i've progressed enough to produce a different problem. I ended up changing my ajax request in main.js to:
$.ajax({
url: "http://localhost:9000/upload",
type: "POST",
data: resp,
success: function (data) {
alert(resp);
Then I also changed the profilecontroller.java to
public Result upload() {
String dataUrl = request().body().asText();
System.out.println(dataUrl);
return ok("Data URI Passed");
}
This gave me the Data URI from javascript and passed it to the JAVA code. Now I need to try and upload the image using the Data URI. If you know the answer to this then please contribute to this post.
I'm trying to call my Spring controller using Ajax and submitting a form.
Function always retrieves the error window. I tried changing the URL parameter to "/profile", "profile" or "PrivateAreaController/profile", but I keep getting the same error.
My main.js file and controller are placed in the following order:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
My controller is called PrivateAreaController
Ajax Code
$('#sampleForm').submit(
function(event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
type : "POST",
dataType: "json",
url : '#Url.Action("callingcontroller","PrivateAreaController")',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
return false;
});
Spring code
#RequestMapping(value = "/profile", method = RequestMethod.POST)
public #ResponseBody
String processAJAXRequest(
#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname ) {
String response = "";
System.out.println("working");
return response;
}
HTML form
<form id="sampleForm" method="post" action="/profile">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<button type="submit" name="submit">Submit</button>
</form>
EDIT:
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
This worked for me using springboot with thymeleaf, made small modification to one of the answers on this post How do you get the contextPath from JavaScript, the right way?
In the HTML
<html>
<head>
<link id="contextPathHolder" th:data-contextPath="#{/}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
THEN IN JS
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + 'action_url', function() {});
What is error you are getting, Press F12 and go to Network tab and the press submit button now see the url, try adding url:"../your service URL..
Well. I never seen this part before.
#Url.Action("callingcontroller","PrivateAreaController")
I normally do like as below:
$.ajax({
type : "POST",
dataType: "json",
url : '/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
But it can have a problem with the contextPath.
So, What I do is adding 'request.getContextPath()/' as below:
$.ajax({
type : "POST",
dataType: "json",
url : '${request.getContextPath()}/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
The contextPath has the URL of your start page.
For instance, 'www.google.com' or 'www.naver.com'
But in general, Since I personally use the contextPath a lot, I make a value and keep it.
var context = ${request.getContextPath()};
Then, your code will look neat and easy to reuse.
And also you can figure it out with the error attribute.
error : function(err) {
console.log("not working. ERROR: "+JSON.stringify(err));
}
I hope this works out.
I am trying to communicate with a method using Ajax and AngularJS but I'm not getting a response and the alert outputs undefined.
Index.cshtml
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp">
// Displaying the table is working
<div>
<table class="table" ng-controller="UpdateController">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tr ng-repeat="c in cities">
<td>{{c.Id}}</td>
<td>{{c.City1}}</td>
<td>{{c.Country}}</td>
</tr>
</table>
</div>
// Here I add the controller for adding records -->
<div ng-controller="AddRecord">
<form id="form1" ng-submit="send()">
<table>
<tr>
<td>City: </td>
<td>
<input type="text" id="txtCity" ng-model="addCity" />
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<input type="text" id="txtCountry" ng-model="addCountry" />
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('UpdateController', function ($scope, $http) {
$http.get("http://localhost:50366/api/cities")
.success(function (response) { $scope.cities = response });
});
app.controller('AddRecord', function ($scope, $http) {
// Function responsible for communicating with backend
$scope.send = function () {
$.ajax({
type: "POST",
url: "AddCity.asmx.cs/PostCity",
data: "{'city':'" + $scope.addCity + "','country':'" + $scope.addCountry + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
//Here is one I tried using text as the datatype:
$.ajax({
type: "POST",
url: "AddCity.asmx/PostCity",
data: "city=" + $scope.addCity + "&country=" + $scope.addCountry,
dataType: "text",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
};
});
</script>
</body>
</html>
AddCity.asmx with the method I'm trying to access
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AngularWebApi.Models;
using AngularWebApi.Controllers;
namespace AngularWebApi.Views
{
/// <summary>
/// Summary description for AddCity
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AddCity : System.Web.Services.WebService
{
[WebMethod]
public string PostCity(string city, string country)
{
City newCity = new City();
newCity.City1 = city;
newCity.Country = country;
//Eventually I want to add the city to the database
CitiesController controller = new CitiesController();
controller.PostCity(newCity);
return "Posted!";
}
}
}
Index.cshtml resides in Views/Home and AddCity.asmx resides in Views. I tried to use url: "../AddCity.asmx/PostCity" as well.
Edit
I quickly created a new project and set it up, the exact same thing is happening, here are the steps:
New web api project
New ADO.net Entity data model and link it to my DB
New Web API 2 controller with actions using Entity Framework passing the table from DB and entity I got from pevious step.
Then I edit Index.cshtml to show the XML from API/CITIES as a table. This time I added my service in the root of the project and just trying to call the auto created HelloWorld with the $.ajax POST function.
I do see a warning in the FF error console. Literal translation from dutch: Cross-Origin-Request blocked: ....
Furthermore the error is triggered within the ajax call. The WebService is not being reached afaik.
This is the complete reply I get when I click the button:
<!DOCTYPE html>
<html>
<head>
<title>The resource cannot be found.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/Home/MyWebService.asmx/HelloWorld<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
</font>
</body>
</html>
<!--
[HttpException]: A public action method 'MyWebService.asmx' was not found on controller 'AngularTutorial.Controllers.HomeController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Edit
The POST method in the controller:
// POST: api/Cities
[ResponseType(typeof(City))]
public IHttpActionResult PostCity(City city)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Cities.Add(city);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = city.Id }, city);
}
hmmm, I think I got it: you try to create a new POST-Method, but according to the tutorial, there is already a POST-Method in the City-Controller:
By clicking on Add, we are able to create the Cities Web API using the scaffolding. The created controller class will have a Web API for all the CRUD operations on the city table.
that means you simply need to send your ajax-call to http://localhost:50366/api/cities:
$.ajax({
type: "POST",
url: "http://localhost:50366/api/cities",
data: "{'country':'" + country + "','name':'" + cityName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
Make sure you only have 1 web application running, so you can avoid unnecessary problems.
btw. I'm not sure, if the controller will accept json maybe you need to send the data as xml...
EDIT:
I updated the json data. Your city-object has 3 properties: country, id and name. If you send a POST request you are about to create a new object, so you don't need to send the id.
For PUT and DELETE (if you want to implement this functions) you will need to add the idto the url:
http://localhost:50366/api/cities/:id
EDIT2:
ok, the xml should looks like this:
data: "<City><Country>" + country + "</Country><Name>" + cityName + "</Name></City>",
don't forget to change:
contentType: "application/xml; charset=utf-8",
dataType: "xml",
Don't use ajax, even if it worked you would still have problems because $.ajax calls are not in Angular.js context and you would have to manually $scope.apply() the returned value. Use angular $http service instead. You can find how to use it in official documentation. It is very flexible, supports all request methods, query params, request body, etc... also supports interceptors to handle all your requests. All $http calls return promise by default (also use .then() handler instead of success and failure handlers).
I have the following being passed from browser to server
Status Code:204 No Content
Request Method:POST
Content-Type:application/x-www-form-urlencoded
Form Data
json:{"clientName":"PACK","status":"success","message":"successful!"}
and in jsp code
var loginData = {
clientName: cList,
status: "success",
message: "successful!"
};
$.ajax({
url: subUrl,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
data: {
json: JSON.stringify(loginData)
},
success: function (data) {
handleLoginResult(data);
}
});
And in Java code I have
#POST
public Object persistResetPasswordLogs(#FormParam("clientName")
String clientName) {
try {
log.info("in rest method ??? "+clientName);
.......
.......
In server I am getting clientName as null.
What could be the reason for this and how can I resolve this?
AFAIK, there is no Jersey (JAX-RS) mechanism to parse JSON into form data. Form data should be in the form of something like
firstName=Stack&lastName=Overflow (or in your case clientName=someName)
where firstName and lastName are generally then name attribute value in the form input elements. You can use jQuery to easily serialize the field values, with a single serialize() method.
So you might have something that looks more along the lines of something like
<form id="post-form" action="/path/to/resource">
Client Name: <input type="text" name="clientName"/>
</form>
<input id="submit" type="button" value="Submit"/>
<script>
$("#submit").click(function(e) {
$.ajax({
url: $("form").attr("action"),
data: $("form").serialize(),
type: "post",
success: processResponse,
contentType: "application/x-www-form-urlencoded"
});
});
function processResponse(data) {
alert(data);
}
</script>
Have you defined the Requestmapping like this:
#POST
#Path("/submitclient") // your request mapping for 'subUrl'
public Object persistResetPasswordLogs(#FormParam("clientName") String clientName)
and html:
<form action="submitclient" method="post">
...
</form>
Also look at your json object. I believe you should send something like this:
var loginData = {
clientName: "dit" // get it from input
};
?
I have an ajax call and i would like in the success function to loop through every label in a class and set their value to that which has been returned from the server response. Under is the code however this sets all the labels to the same value, this is not what i want i would like to access the index of that item and set only that index to the response value. Where am i going wrong here?:
JQuery:
function GetCitizenTypeDescription(citizenTypeId){
$.ajax({
type:'GET',
url:'getCitizenTypeDescription.htm',
data:{citizenTypeId:citizenTypeId},
dataType: 'text',
success: function (data) {
$('.citizenTypeDesc').each(function(i){
alert(data);
$('.citizenTypeDesc').text(data);
});
}
});
}
$(document).ready(function() {
$(".photos").each(function(i){
if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();
image.onload = function(){
var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}
});
$('.citizenTypeDesc').each(function(i){
var citizenTypeId = document.getElementsByClassName("citizenTypeId")[i].value;
GetCitizenTypeDescription(citizenTypeId);
});
});
The console returns the correct data i just need to write it to the labels
Console:
GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=2 200 OK 174ms
Response
CRIMINAL
GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=3 200 OK 174ms
Response
VICTIM
GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=4 200 OK 174ms
Response
....
html
</head>
<body>
<div id ="content">
<c:forEach items="${citizens}" var="citizen">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
Name:- ${citizen.fName} ${citizen.lName}
<input type="hidden" id="photo" value="${citizen.photo}" class="photos"/>
<input type="hidden" id="socialSecurityNumber" value="${citizen.socialSecurityNumber}" />
<input type="text" class="citizenTypeId" value="${citizen.citizenTypeId}"/>
<label class="citizenTypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>
Instead of looping over all of the .citizenTypeDesc labels you could loop over all of the .citizenTypeId. Test if each value matches the parameter and then set the label that is within the same parent element.
function GetCitizenTypeDescription(citizenTypeId){
$.ajax({
type:'GET',
url:'getCitizenTypeDescription.htm',
data:{citizenTypeId:citizenTypeId},
dataType: 'text',
success: function (data) {
$('.citizenTypeId').each(function(i){
//does this value match the parameter
if($(this).val() === citizenTypeId){
//find the parent div, in this case .table
var parent = $(this).parent();
//search for a child with class .citizenTypeDesc
var thisCitizenTypeDesc = parent.children('.citizenTypeDesc');
thisCitizenTypeDesc.text(data);
}
});
}
});
}