This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I am very new to ajax and I am getting null values with ajax call to servlet,don't know why?any idea?here below i mentioned my code,For any help thanks in advance.
function addSubjectMarks(){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
var selectedStudent=document.getElementById("selectedStudent").value;
var selectedSubject=document.getElementById("selectedSubject").value;
var marks=document.getElementById("stMarks").value;
$.ajax({
type: "POST",
url: "WeeklyMarks",
data:postData,
success: function(data,status){
//var res = data.split(',');
}
});
}
//servlet code is:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String selectedSubject=request.getParameter("stSubjectMarks");
System.out.println("selectedSubject :"+selectedSubject);//here getting null value
}
my html form is:
form id="ajaxform" action="weeklyMarks" method="post">
<table>
<td>
<label id="stForm" for="Marks">Marks Obtained:</label>
<input type="text" id="stMarks" name="stMarks" style="margin-left: 33px; width: 150px;" />
<label id="stMarksError" style="display: none; color: red;">*Please enter marks</label>
<br>
<br>
</td>
</tr>
<tr>
<td>
<input type="button" value="Add" id="addButton" class="btn-warning" style="margin-left: 200px;"" onclick="addSubjectMarks() ">
</td>
</tr>
</table>
</div>
</div>
postData = $('#ajaxform').serializeArray();
Related
**when i tried to convert my grid-view data into PDF i got null reference exception grid-view header row but data is available in grid view.please help me to solve this error. i am using asp.net web API in this.. and i tried to on another grid-view to bind data..it shows same error null reference exception but when i tried on direct button click it works fine..only it shows error when i tried on using web API..please help me to solve this
i have attached my programming below data load and bind
public void GetData()
{
string conn = ConfigurationManager.ConnectionStrings["con"].ToString();
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("select * from api", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "api");
//DataTable dta = new DataTable();
//dta = ds.Tables["api"];
//da.Fill(dta);
GridView2.DataSource = ds;
GridView2.DataBind();
}
convert to pdf
public string Button3_Click()
{
PdfPTable pdfTable = new PdfPTable(GridView2.HeaderRow.Cells.Count);
foreach (TableCell headercell in GridView2.HeaderRow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.HeaderRow.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(headercell.Text, font));
pdfcell.BackgroundColor = new Basecolor(GridView2.HeaderStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
foreach (GridViewRow gridviewrow in GridView2.Rows)
{
foreach (TableCell tablecell in gridviewrow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.RowStyle.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(tablecell.Text));
pdfcell.BackgroundColor = new Basecolor(GridView2.RowStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
}
Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
pdfdoc.Open();
pdfdoc.Add(pdfTable);
pdfdoc.Close();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=Employyes.pdf");
Response.Write(pdfdoc);
Response.Flush();
Response.End();
return "success";
}
ajax function call
$(document).ready(function () {
$("#Button2").click(function () {
alert("ajax call");
$.ajax
({
method: "GET",
url: "api/Employees",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success");
},
error: function (responce) {
alert("error");
},
});
});
});
<asp:Button ID="Button1" runat="server" Style="width: 136px" Text="Export to Excel" Width="175px" />      
<asp:Button ID="Button2" runat="server" Text="Export to PDF" Width="175px" />
<br />
<br />
<div class="auto-style1" id="NewData">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</div>
here is my controller class
public class EmployeesController : ApiController
{
// success s = new success();
BusinessLogicLayer bal = new BusinessLogicLayer();
public string Get(string username, string password)
{
return bal.login(username, password);
}
[System.Web.Mvc.HttpPost]
public string POST(string firstname, string lastname, string username, string password, string email)
{
return bal.Register(firstname, lastname, username, password, email);
}
[System.Web.Http.HttpGet]
public string buttonclick()
{
// MessageBox.Show("come");
return bal.ExportConvert();
}
here is my business logic layer class method
public string ExportConvert()
{
success s = new success();
return s.Button3_Click();
}[enter image description here][1]
here my login page code
**<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body style="padding-top:20px;">
<div class="col-md-10 col-md-offset-1">
<div class="well">
<table class="table table-bordered">
<thead>
<tr class="success">
<th colspan="2">
Existing User Login
<a class="btn btn-success pull-right" href="Registration.html">Register</a>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>UserName</td>
<td>
<input type="text" id="username" placeholder="username"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="password" placeholder="Password" />
</td>
</tr>
<tr class="success">
<td colspan="2">
<input type="button" id="btnlogin" class="btn btn-success" value="login" />
</td>
</tr>
</tbody>
</table>
<div class="modal fade" tabindex="-1" id="successmodel"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4>Success</h4>
</div>
<div class="modal-body">
<h2>Registraton success</h2>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-success">
Close
</button>
</div>
</div>
</div>
</div>
<div id="divError" class="alert alert-danger collapse">
<a id="linkClose" class="close" href="#" >×</a>
<div id="divErrorText"></div>
</div>
</div>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$('#linkClose').click(function () {
$('divError').hide('fade');
})
});
$('#btnlogin').click(function () {
$.ajax({
url: '/api/Employees/?username=' + $("#username").val() + '&password=' + $("#password").val(),
method: 'Get',
contentType: 'application/json',
data: { id: 1 },
dataType: 'json',
success: function (data) {
console.log(data);
//var data = data.d;
//alert("success " + data);
if (data == 'success') {
window.location = "/success.aspx";
}
else {
alert("Wrong Username and Password");
}
/* if (data != null) {
$.each(data, function (i, obj) {
var c = new WorkflowsEntity(data[i]); //logic
self.WorkflowList.push;
});
alert("success");
//window.location.href = "/success.html";
}*/
},
error: function (jqXHR, textStatus, errorThrown) {
alert(" un correct username password ");
$('#divErrorText').text(jqXHR.responceText);
$('#divError').show('fade');
}
});
});
</script>
</body>
</html>**
I am trying post a request to my controller and everytime when I hit submit button it gives an error of bad request.
I am not able to find out what is wrong with the code.
Home.jsp
<div id="setReminder">
<label class="generalReminder" style="text-decoration: none;">General
Reminder</label>
<table>
<tr>
<td>Date</td>
<td><input type="text" readonly="readonly"
id="birthdayDate"></td>
</tr>
<tr>
<td>Time</td>
<td><input type="text" readonly="readonly" id="callTime"
></td>
</tr>
<tr>
<td>Message</td>
<td><textarea id="reminderTag" rows="5"></textarea></td>
</tr>
</table>
</div>
<div id="reminderDot" style="margin-top: 24%; position: relative;">
<button class="submitReminder" onclick="saveReminderDetails();">Submit</button>
</div>
Home.js
function saveReminderDetails(){
var x="";
x=scheduleBirthdayReminder();
if(x){
$.ajax({
type:"POST",
url:"submitBirthdayRequest.do",
data : {
birthdayDate :$("#birthdayDate").val(),
birthdayTime : $("#callTime").val(),
birthdayReminder : $("#reminderTag").val()
},
success : function(data) {
alert('data is'+data);
$("#birthdayDate").val('');
$("#callTime").val('');
$("#reminderTag").val('');
}
});
}
}
Controller.java
#RequestMapping(value="submitBirthdayRequest.do",method=RequestMethod.POST)
public #ResponseBody String submitSchedulerDetails(#RequestParam("birthdayDate")String birthdayDate,#RequestParam("callTime")String birthdayTime,#RequestParam("reminderTag")String reminderTag,HttpServletRequest request ){
System.out.println("adding reminder details with birthdayDate "+birthdayDate+"and time"+birthdayTime);
String userIdentity=((UserDetails)request.getSession(false).getAttribute("loginDetails")).getName();
try{
boolean schedulerObj= schedulerService.addSchedulerBirthdayDetails(userIdentity,birthdayDate, birthdayTime,reminderTag);
}catch(Exception e){
e.printStackTrace();
}
return birthdayTime;
}
Error
http://localhost:8083/Testing/submitBirthdayRequest.do 400 (Bad Request)
the names of the parameters in the request don't match the expected. Try changing the
#RequestParam("birthdayTime") String birthdayTime
#RequestParam("birthdayReminder") String reminderTag
or change the param names on the client side
in my form I have table to show some of customer data.user can click on row to see all of customer data.
<div class="container">
<table class="table table-bordered" style="direction: rtl">
<thead>
<tr>
<th style="text-align: center">customer name</th>
<th style="text-align: center">customer ID</th>
</tr>
</thead>
<tbody>
<c:forEach items="${customers}" var="customer" varStatus="loop">
<tr onclick="retrieveCustomer('${loop.index}')">
<td id="id-${loop.index}">${customer.customerId}</td>
<td>${customer.customerName}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<script>
function retrieveCustomer(id) {
debugger;
$.ajax({
url: "<%=request.getContextPath()%>/show_selected_customer",
data: {customerId: $('#id-' + id).text()},
type: "GET",
success: function (response) {
},
error: function (xhr, status, error) {
alert(error);
}
});
};
</script>
and in my controller:
#RequestMapping(value = "/show_selected_customer", method = RequestMethod.GET)
public ModelAndView showSelectedCustomer(#RequestParam("customerId") String customerId) {
Map<String, Object> model = new HashMap<>();
Customer customer = coreService.getCustomer(customerId);
model.put("customer", customer);
return new ModelAndView("showCustomerData", model);
}
tiles:
<definition name="showCustomerData" extends="base.definition">
<put-attribute name="title" value="customer data"/>
<put-attribute name="content" value="/WEB-INF/jsp/show_customer_data.jsp"/>
</definition>
until now every thing work correctly.
my problem is, it doesn't show show_customers.jsp page,and even I have no error in my log.
what is my problem,Is because of ajax call? I did`t use #responsebody and want to show customers.jsp page with return modelandview. thank you
Use the response body annotation and convert your entity to JSON and return it instead.
I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.
guys.
I'm trying to call some AJAX Post trhu AngularJS, and I want to send all properties from my $scope variable. I have this form:
<div ng-controller="DiscountPrintsCtrl">
<div>
Choose the year:
<select ng-model="selectedYear" ng-change="searchCourses()">
<option ng-repeat="year in years" value="{{year.ID}}">{{year.Name}}</option>
</select>
</div>
<div>
Choose the course:
<select ng-model="selectedCourse" ng-change="searchStudents()">
<option ng-repeat="course in courses" value="{{course.ID}}">{{course.Nome}}</option>
</select>
</div>
<div>
Choose the student:
<select ng-model="selectedStudent" ng-change="searchStudentDetails()">
<option ng-repeat="student in students" value="{{student.ID}}">{{student.Name}}</option>
</select>
</div>
<div ng-model="studentDetails">
Details about the student:<br /><br />
<label>Name: {{studentDetails.Name}}</label><br />
<label>Number: {{studentDetails.Number}}</label><br />
<label>Print quote: {{studentDetails.PrintQuote}}</label><br />
</div>
<div>
<table>
<thead><tr>
<td></td>
<td>Title</td>
<td>Grade</td>
<td>Summary</td>
<td>Author</td>
<td>Number of pages</td>
</tr></thead>
<tbody>
<tr ng-repeat="publication in publications">
<td><input type="checkbox" ng-model="publication.Selected" /></td>
<td>{{publication.Title}}</td>
<td>{{publication.Grade}}</td>
<td>{{publication.Comments}}</td>
<td>{{publication.Author}}</td>
<td>{{publication.NumberOfPages}}</td>
</tr>
</tbody>
</table>
</div>
<button ng-click="submitForm()" value="Confirm discounts" />
And I have this JS:
<script type="text/javascript">
function DiscountPrintsCtrl($scope, $http) {
$http.get(url).success(function (years) {
$scope.years = years;
$scope.selectedYear = '';
});
$scope.searchCourses = function() {
var url = '/json/GetCoursesFromYear?' +
'selectedYear=' + $scope.selectedYear;
$http.get(url).success(function (courses) {
$scope.course = courses;
$scope.selectedCourse= '';
});
}
$scope.searchAlunosAnoSemestre = function() {
var url = '/json/GetStudentsFromCouse?' +
'selectedCourse=' + $scope.selectedCourse;
$http.get(url).success(function(students) {
$scope.students = students;
$scope.selectedStudent = '';
});
}
$scope.searchStudentDetails = function() {
var url = '';
url = '/json/GetStudentDetails?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(studentDetails) {
$scope.studentDetails= studentDetails;
});
url = '/json/GetPublicationsForStudent?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(publications) {
$scope.publications = publications;
});
}
$scope.submitForm = function () {
// How to submit the entire $scope???
}
}
Any idea? Any considerations about my JS code??
Thanks all!!!
You have typos to fix, friend:
In the .js:
$scope.course = courses;
Should be $scope.courses!
In the html:
{{course.Nome}}
Shouldn't it be:
{{course.Name}}
?
I see some Spanish (?) above there but everywhere else you say .Name so it's best to be consistent, right?
That said, it seems fine to load an object into your $scope from the external json data store as you seem do be doing in each function, loading from the json URLs. The commenters on your post didn't seem to recognize this? I think they believe you're trying to permanently store this data in $scope? Maybe I'm not seeing something that they are... but if you don't add your data model object sometime into $scope.something then {{something}} simply won't work, and neither will {{something.else}}.
Am I way off base here?