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.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
In the code added here, I pass on value from PHP parameter to JS parameter:
Both parameters are called 'stv'.
I wonder how do I do the exact opposite?
Thanks!
<script>
var stv="<?php echo $stv; ?>";
</script>
send a request with ajax using jquery if using jquery already in document.
If you don't have Jquery added, you can add it ath the end of your html body using a script tag and getting the download adress from google:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
function ajax(value) {
var x = {
'info': value //data to send can be json or something else
};
$.ajax({
url: 'index.php', //page where to send
type: 'POST', //type of request
data: x, // data to send
success: function(data) { //what happends when request is success
try {
getAjPromise(JSON.parse(data));
} catch (e) {
console.log("error");
}
}
});
}
in PHP you check if there is a $_POST['info'], get the value and do something
I am trying to use ajax function inside javascript, but its not calling its goes to failure part,
JS code :
Yii::app()->clientScript->registerScript('my-event-listener',"
$('#dedup_id').change(function(data){
$.ajax({
type: 'POST',
url: '".$this->createUrl('CheckDedupField')."',
data: {crm_base_contact_id:1652},
success: function(msg){
alert('Sucess')
},
error: function(){
alert('failure');
}
});
});
");
My controller code :
public function actionCheckDedupField($id)
{
echo "Inside CheckDedup".var_dump($_POST);
}
Please anyone find out what mistake am doing here.
You have to call ajax url as
url: '".$this->createUrl('checkDedupField')."', // change C to c
In URL, controller function names will start with lower case.
as per the comment. you are calling controller function with wrong name.
Then For missing parameter, change as
data: {id:1652},
Goal: Call a server side method asynchronously from changing a dropdown to get data and populate a separate listbox not using UpdatePanels.
Currently I'm using a static ASP.NET page method asynchronously using jQuery and an ajax call as shown in this post (How to wire up a DropDownList to make AJAX calls to the server?) and it is working well.
The whole purpose was to prevent using the UpdatePanel tangled mess that I had been in previous years and this seems to be a good alternative. What I didn't realize is that the page method has to be static and you can not access any of the page's controls or context. So trying to make this call from a dropdown selection to populate another control's data is not possible. I can't see the other controls.
So what I'd like to do before I give up and go back to updatepanels is try to do 1 of the following:
Have my static page method return a json string with my collection data that I then use in the original jQuery method wired up to the change method of the dropdown to populate the separate listbox.
Same as above but return a .NET IList<> or comparable if returning json is not a good idea.
Point is I want that static method to return the needed data to bind to my listbox control. However I don't know how to do this. Here is my current jQuery method:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the control.
$("<%= MyDDL.ClientID %>").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
});
</script>
Here is the original dropdown:
<asp:DropDownList ID="MyDDL" runat="server" Width="340px" />
Here is the control that needs populated based on the selection of the dropdown after calling the static method named MyDDL_SelectedIndexChanged:
<asp:ListBox ID="ListBox2" runat="server" Width="340px" SelectionMode="Multiple" />
Here is my current static page method:
[WebMethod]
public static string MyDDL_SelectedIndexChanged()
{
var myClass = new MyClass()
var data = myClass.GetDataCollection()
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonString = serializer.Serialize(data);
}
Is there a way to take this returned data and bind it in the jQuery method above? My bailout is to go back to using an UpdatePanel where my server-side method can access other controls, but I really do not want to do this.
There is a javascript project called jsRender that may be what you need:
http://weblogs.asp.net/stevewellens/archive/2011/12/01/goodby-jquery-templates-hello-jsrender.aspx
I actually was looking for a more complete exaample and have the solution working with the code below:
$(document).ready(function () {
MyDDL_OnChangeHandler();
});
function MyDDL_OnChangeHandler() {
// Add the page method call as an change handler for the MyDDL DropDownList.
// This will call the static page method, and use the returned results to populate the 'MyListBox' listbox control.
$('#<%=MyDDL.ClientID %>').change(function () {
var val = $(this).val();
var text = $(this).children("option:selected").text();
var $lbxCtrl = $('#<%=MyListBox.ClientID %>');
$lbxCtrl.attr('disabled', 'disabled');
$lbxCtrl.empty();
$lbxCtrl.append('<option value="0">< Loading Please Wait... ></option>');
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'ID':'" + val + "', 'Name':'" + text + "'}",
success: function (data) {
$lbxCtrl.removeAttr('disabled');
$lbxCtrl.empty();
if (data.d == null) {
return;
}
$.each(data.d, function (i, data) {
$users.append('<option value="' + data.Value + '">' + data.FullName + ' (' + adUser.data+ ')' +'</option>');
});
},
error: function () {
$lbxCtrl.empty();
$lbxCtrl.append('<option value="0">< Error Loading Data ></option>');
alert('Failed to retrieve data.');
}
});
});
As Michael B mentioned in the comments, you can handle any data returned from the ajax call by using success:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the control.
$("#<%= MyDDL.ClientID %>").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// do stuff with the "data" that is returned
},
error: function(data) {
// handle any errors here
}
});
});
});
</script>
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);
}
}