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);
}
}
Related
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.
Ajax not working. This is my form. ajax not validating my server side code. As per the below code it is not showing the error .
<form id="postMveForm" action="movieDetails">
<input type="text" name="mvetitle" id="mveTitleId"><br/>
<div id="errormvetitle"></div><br/>
<textarea name="mveDescription" id="mveDescrId" rows="10" cols="50"></textarea><br/>
<div id="errormveDescr"></div><br/>
My ajax validation is not working. I need error to appear below the textfield if user focus the field and leaves it as an empty field. No error showing when I focus the textfield and leaves it empty. ajax not working.
<script>
$(document).ready(function() {
$('#mveTitleId').blur(function() {
$.ajax({
url : 'movieDetails',
data : {
mvetitle : $('#mveTitleId').val()
},
success : function(responseText) {
$('#errormvetitle').text(responseText);
}
});
});
$('#mveDescrId').blur(function() {
$.ajax({
url : 'movieDetails',
data : {
mveDescription : $('#mveDescrId').val()
},
success : function(responseText) {
$('#errormveDescr').text(responseText);
}
});
});
});
</script>
This the movieDetails servlet class.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
{
String mveTitle = request.getParameter("mvetitle");
String mveDescrptn = request.getParameter("mveDescription");
if(mveTitle.length()==0)
{
String mveTitleError = "Error movie Title field is Empty";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(mveTitleError);
}
if(mveDescrptn.length()==0)
{
String mveDescrptnError = "Error movie Description is empty";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(mveDescrptnError);
}
else {
response.getWriter().append("success ").append(request.getContextPath());
}
}
please check null on if conditionn.
if(mveTitle == null) instead of if(mveTitle.length()==0)
and if(mveDescrptn == null) instead of if(mveDescrptn.length()==0)
I have a create,edit,delete application On my Index view i have Button for Edit. by clicking this button it should open pop up in which all data should be displayed for editing.
To achieve this i passed ID of that row which is getting Edited. see code below :
<td>
<button type="button" onclick="EditPopup(#item.Id)">Edit</button>
</td>
here i am passing ID to my EditPopup javascript method. see the method below :
<script type="text/javascript">
$(document).ready(function () {
$("#EditDialog").dialog({
autoOpen: false,
title: 'Title',
width: 'auto',
height: 'auto',
modal: true
});
});
function EditPopup(Get_Id) {
alert(Get_Id) // I am getting correct ID here.
$.ajax({
method: "POST",
url: '#Url.Action("Edit","Home")',
dataType: 'json',
cache: false,
data:{Get_Id}, // tried : {id:Get_Id} , {id:"Get_Id"} not working
success: function (data) {
$('#EditDialog').html(data);
}
});
$("#EditDialog").dialog("open");
}</script>
I am sending value of ID to my Controller method Edit thats why i am using Post method in ajax call. Edit is name of method and Home is name of controller.
HomeController Edit methods
[HttpPost]
public JsonResult Edit(int? id)
{
FloorFactor floorFactor = db.FloorFactors.Find(id);
return Json(floorFactor, JsonRequestBehavior.AllowGet);
}
// POST:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
FloorFactor floorFactor = db.FloorFactors.Find(id);
return View(floorFactor);
}
in few examples i saw that in ajax call they usually use json result method. so that is the reason i also used json result method.
finally Code which is in my index view where i will show pop up result.
<div id="EditDialog" style="display:none;">
<label> Floor Factor </label>
<br />
<label> Effective From :</label>
So the Whole scenario is :
I send id value on button click event to javascript.
on javascript i make a call to my controller method to get data.
those should pass in EditDialog box of div.
on div block it should display in pop up.
Current output :
I also want to understand how url field works in ajax call.
if i am getting multiple column results as output of that url how can i collect all output in Data part of ajax call.
please also explain on success what parameters i can pass in function.
Thank you for explanation and help.
Edit : It shows no error on console tab.
as shown in this script tab i think it is sending a request as it generates request Id.
Try the below changes
Action Code :
[HttpPost]
public JsonResult Edit(int? id)
{
FloorFactor floorFactor = db.FloorFactors.Find(id);
return Json(floorFactor, JsonRequestBehavior.AllowGet);
}
View Changes
<div id="EditDialog" style="display:none;">
<label> Floor Factor </label> <span id="floorFactor"></span>
<br />
<label> Effective From :</label> <span id="effectiveFrom"></span>
Success method changes
if(data)
{
// GET VALUES
var floorFactor = data.Property_Having_FloorFactor;
var effectiveFrom = data.Property_Having_EffectiveFrom;
// ASSIGN VALUES
$('#floorFactor').text(floorFactor);
$('#effectiveFrom ').text(effectiveFrom );
// OPEN DIALOG
$("#EditDialog").dialog("open");
}
Hope it will work for you.
Change the Controller as
[HttpGet]
public JsonResult Edit(int? id)
{
FloorFactor floorFactor = db.FloorFactors.Find(id);
return Json(floorFactor, JsonRequestBehavior.AllowGet);
}
// POST:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
FloorFactor floorFactor = db.FloorFactors.Find(id);
return View(floorFactor);
}
Change the 'ajax' as
$.ajax({
method: "GET",
url: '#Url.Action("Edit","Home")',
dataType: 'json',
cache: false,
data: {id:Get_Id},
success: function (data) {
$('#EditDialog').html(data);
}
});
Note: Code is untested. It should have work for you.
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.
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 7 years ago.
I created a jsp page with 2 variables and using jquery that is passed to Servlet and displayed in console, now i need to pass a variable back to jquery.How to write it??Please see the servlet and js i used.
jquery
$(document).ready(function(){
$("#click").click(function(){
var form = $('#new');
alert("serialize :"+form.serialize());
$.ajax({
url: 'login',
data: form.serialize(),
type: 'post',
success: function(data){
alert("Reached Servlet"+data);
}
});
});
});
Servlet do post as follows
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("in POST");
String a=request.getParameter("txt_name");
String ad=request.getParameter("txt_address");
PrintWriter ins_writer= response.getWriter();
System.out.println("console");
ins_writer.write("In servlet POST > value for Name : "+a);
System.out.println("a > "+a +">>>>>"+ad);
System.out.println("----------------------------From Jquery-------------");
System.out.println("Name from JSP> "+a);
System.out.println("Address from JSP> "+ad);
String pq="Amanda";
}
I just wanted to pass this 'pq' value to jquery ?Please help me!!
You can pass back a hidden element and then output it when ajax request finishes:
In servlet:
System.out.println("<input type='hidden' id='pqId' value='"+pq+"'/>");
And then in ajax append the response to a hidden area, and get the value of the field:
$.ajax({
url: 'login',
data: form.serialize(),
type: 'post',
success: function(data){
$('body').append('<div style="display:none;">'+data+'</div>');
alert($('#pqId').val());
}
});
Change System.out.println to ins_writer.write
like:
ins_writer.write("<input type='hidden' id='pqId' value='"+ad+"'/>");
and previous answer should work fine.