I am new to AJAX and I have a JSP page that looks like below:
The new username column allows me to input any string of text and when I hit update user button,it should update the table in my database.
My table in database structure has a unique column AUSERNAME which stores the username as shown in the screenshot. After clicking the update button, it shall pass the new username value and update that field in table. This is what I am trying to achieve.
I know I have to make an AJAX call in my JSP page which looks like below:
<script >
function update(param) {
var currentbal = document.getElementsByName('NewUserName' + param)[0].value;
console.log(currentbal);
$.ajax({
type: "POST",
url: "update.jsp",
data: { name: currentbal},
success:function( msg ) {
alert( "Data Updated: " + msg );
},error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
As for my update.jsp page, I am not too sure how to work on it and make the changes to the table. I believe I need to create a function in it but unsure how to pass the values to it and use sql statements to update it.
In your jsp page you can do something like this :
<%#page import= "java.sql.*" %>
<%#page import= "java.io.*" %>
<%
//getting data send from ajax request
String id= request.getParameter("id");
String user = request.getParameter("name"); //name for example
//data base code
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection con = null;
ResultSet resultSet = null;
Statement stmt = null;
int row=0;
try {
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/abc","root","swati");
String sql = "UPDATE `tablename` SET `user`=? WHERE `id`=?"; //updating table
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2, id);
row = statement.executeUpdate();
if (row > 0) {
String txt="updated";
// forwards to the message page
}
}
else {
String txt="not updated";
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(txt);
%>
Hope this help you !
Related
i need to view records in to the Datatable using jsp json. data is displayed to datatable successfully. my problem is only one row data is displaying.the last row of database record is repecting 4 times.i attached image below what was shown on the datatable and what are the data inside mysql database.
Record Shown one the datatable look like this.data duplicated
Mysqldata Data
Datatable
function get_all()
{
$('#tbl-projects').dataTable().fnDestroy();
$.ajax({
url : "all_project.jsp",
type : "GET",
dataType : "JSON",
success:function (data){
console.log(data);
$('#tbl-projects').dataTable({
"aaData": data,
"scrollX": true,
"aoColumns":
[
{"sTitle": "Name", "mData": "name"},
{"sTitle": "Course", "mData": "course"},
{"sTitle": "Fee", "mData": "fee"},
]
});
},
error: function (xhr) {
console.log('Request Status: ' + xhr.status );
console.log('Status Text: ' + xhr.statusText );
console.log(xhr.responseText);
var text = $($.parseHTML(xhr.responseText)).filter('.trace-message').text();
}
});
}
details.jsp
<%#page import="org.json.simple.JSONArray"%>
<%#page import="org.json.simple.JSONObject"%>
<%#page import="org.json.simple.parser.JSONParser"%>
<%#page import="org.json.simple.parser.ParseException"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
String query="select * from records";
Statement stmt=con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
String course = rs.getString("course");
String fee = rs.getString("fee");
obj.put("name", name);
obj.put("course", course);
obj.put("fee", fee);
obj.put("id", id);
list.add(obj);
}
out.print(list.toJSONString());
out.flush();
%>
You need to parse json in ajax success function i.e :
<script language="javascript">
function ClickMe_Click(){
$.ajax({
type: "post",
url: "details.jsp",
data: {"a": $("#accno").val()},
success: function(msg) {
//parsing json response
var obj = JSON.parse(msg);
alert(obj[0].bal);
//setting value in input field
$("#bal").val(obj[0].bal);
$("#name").val(obj[0].name);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
return false;
}
</script>
I am using jquery ajaxSubmit function for submitting my form. I also have file upload field in the form.
Here's the code of ajaxSubmit function.
$('#wizard-p-7').submit(function(e) {
$(".validationMessage").hide();
e.preventDefault();
var formURL = $(this).attr("action");
$(this).ajaxSubmit({
url : formURL,
async : false,
contentType: 'multipart/form-data',
success : function(data) {
if (data == "version match.") {
check = true;
} else {
check = false;
}
},
error : function(jqXHR,
textStatus,
errorThrown) {
alert("error:"+errorThrown);
window.location = "<%=application.getContextPath()%>/pages/error/globalError.jsp";
}
});
e.preventDefault(); //STOP default action
// e.unbind(); //unbind. to stop multiple form submit.
return false;
});
Here is my controller method
#RequestMapping(value = "/sectioneight", method = RequestMethod.POST)
public #ResponseBody Object sectioneight(#ModelAttribute("iepDTO") ProjectDTO iepDTO,
#RequestParam("id") String id) {
try {
List<MultipartFile> files = iepDTO.getPolicyBriefFiles();
if(files!=null){
for(MultipartFile file : files){
String filePath = "C:/temp/" + file.getOriginalFilename();
File dest = new File(filePath);
file.transferTo(dest);
}
}
}
catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
logger.error("ProjectController - sectioneight : "+ e.getMessage());
}
return "redirect:home";
}
Now the problem is if I select a file for uploading and submit the form everything works fine. But if I submit the form without selecting file it gives 400 Bad request error in the browser console. Can't find what is wrong.
Any clue?
Solved. Problem was because of ajax. If I don't select a file it sends null string in place of file.
The solution is now I check before submitting the form if file is selected or not. If not, I disable the field with jquery
if($("#policyBriefFiles").val()==""){
$("#policyBriefFiles").prop('disabled', true);
}
Life's good:)
My application was working but I was asked to change how message are displayed by using the JSONResponseFactory. But when I try that my ViewModel is empty going back to the JSonResult (which used to be ActionResult). I've been told I may have to serialize the form fields. Here are some present code excerpts:
cshtml:
function SubmitForm() {
$.ajaxSetup({ cache: false });
$.post('#Url.Action("StoreLevelPlanning", "StoreLevelPlanning")', { actionType: "Submit"})
.done(function (data) {
if (data.Success == true) {
CreateInformationMessage(data.Message, 'window.location.href = "#Url.Action("storemanagement", "AccountListing")";');
}
else {
CreateErrorMessage(data.Message);
}
});
}
Controller:
public JsonResult StoreLevelPlanning_Post(string actionType) // actionType is Save or Submit
{
// message to return to the view on success
string successMessage = "";
var model = new VM_StoreLevelPlanning();
TryUpdateModel(model);
try
{
if (ModelState.IsValid)
{
model.buttonPressed = actionType;
repo.UpdateCLPCategoryAndRemark(model);
//Render different message depending on ActionType
if (actionType == "Save")
{
successMessage = "Your plan was saved. You will now be directed to the Listing Screen";
}
else if (actionType == "Submit")
{
successMessage = "Your plan has been submitted. You will now be directed to the Listing Screen.";
}
else
{
//return RedirectToAction("storemanagement", "AccountListing");
// need to revisit to figure out if this can be removed
throw new Exception("Else case happened");
}
}
else
{
if (actionType == "Save")
{
// TODO : change this to throw an error so that the ErrorLog class is utilized
throw new Exception("Your plan was not saved. Please retry.");
}
else
{
// TODO : change this to throw an error so that the ErrorLog class is utilized
throw new Exception("Your plan was not submitted. Please retry.");
}
}
}
catch (Exception e)
{
return Json(JsonResponseFactory.ErrorResponse(e.Message));
}
return Json(JsonResponseFactory.SuccessResponse(successMessage));
}
I'm open to any suggestions since I'm new to MVC. The idea is to put out a successful save message and redirect the user to the Listing page. But he way I changed the code now the view model is empty. It does not use a form collection. The data is in a list in the view model.
Thank you in advance...
I am working on the MVC3 with ADO.Net Connectivity, an then i am updating the div with jQuery
Here i my code
Controller
public ActionResult GetData()
{
return this.Json(_db.MYMOVIELISTs, JsonRequestBehavior.AllowGet);
}
public void Insert(string Id)
{
var movieToInsert = new MYMOVIELIST { Title = "Ben", Director = "LEMe", ID = Id };
// Save new movie to DB
_db.AddToMYMOVIELISTs(movieToInsert);
_db.SaveChanges();
}
ClientSide
function insertCallback(result) {
readData();
}
function readData() {
info.empty();
$.ajax({
type: "GET",
url: 'Home/GetData',
async: false,
success: function (data) {
for (var i = 0; i < data.length; i++) {
var panel = $("<div class='panel' ></div>")
var d = data[i];
panel.append("ID: " + d.ID + "</br>");
panel.append("Title: " + d.Title + "</br>");
panel.append("Director: " + d.Director + "</br>");
panel.append("<hr>");
panel.data("info", d);
panel.appendTo(info);
}
}
});
}
$("#btnAdd").click(function () {
$.post("Home/Insert", $("form").serialize(), insertCallback);
});
This is works Fine, my problem is i want to update the Database table in "Save" buttom click. i tried to call the _db.SaveChanges(); in save button click instead of the Insert it is not adding the movieToInsert to table, here i want to know is how to save the database later, Here any thing am doing wrong or is there any best approach for DB connectivity
You are serializing a form, so eventually you may want below... which will bind your serialized form to the a movie model/entity:
[AcceptVerbs("POST")]
public void Insert(MovieEntity movie)
As for database practice, I recommend reading about the repository pattern and dependency injection as it pertains to ASP.NET MVC.
I can't work out what I'm doing wrong - I'm sure this used to work...:
<script type="text/javascript">
$("##containerId form").submit(function (event) {
event.preventDefault();
var form = $(this);
if (form.valid()) {
$.post(form.attr('action'), form.serialize(), function(data) {
$("##containerId").replaceWith(data.result);
}, "json");
}
});
</script>
I have a function that returns a view result as a string so I can return it as an object within the JSON response:
protected string RenderViewResultToString(ViewResultBase viewResult) {
using (var sw = new StringWriter()) {
if (string.IsNullOrEmpty(viewResult.ViewName))
viewResult.ViewName = ControllerContext.RouteData.GetRequiredString("action");
ViewEngineResult result = null;
if (viewResult.View == null) {
result = viewResult.ViewEngineCollection.FindPartialView(ControllerContext, viewResult.ViewName);
if (result.View == null)
throw new InvalidOperationException("Unable to find view. Searched in: " + string.Join(",", result.SearchedLocations));
viewResult.View = result.View;
}
var view = viewResult.View;
var viewContext = new ViewContext(ControllerContext, view, viewResult.ViewData, viewResult.TempData, sw);
view.Render(viewContext, sw);
if (result != null)
result.ViewEngine.ReleaseView(ControllerContext, view);
return sw.ToString();
}
}
So, in my controller I have:
[HttpPost, ValidateInput(false)]
public JsonResult Edit(/* stuff */) {
bool success = true;
try {
/* stuff */
} catch {
/* stuff */
success = false;
}
return Json(new { success, result = RenderViewResultToString(/* stuff - call to something that gives a ViewResult */) });
}
In Chrome, I get: "Resource interpreted as Document but transferred with MIME type application/json." and it renders the JSON in the browser as text.
In Firefox/IE, it prompts me to download a file.
What gives?
The form submission isn't getting suppressed. The messages you are getting are from an actual form submission to a page that returns JSON. If you check the browser address bar, you should see the URL is different.
If you run $("##containerId form") in the console, you should see that you're getting no results. "#" is an invalid character in a selector and needs to be escaped. $("#\\#containerId form") should work.