I have two ajax calls in my jsp code which go to servlet. In first call, I am setting a value in the session and in another call, I am retrieving the same value from the session. Now this value goes as response of the ajax call(2nd ajax call). My problem is:-
This value contains "\n"(eg-("ABC \n def\n geh \n xyz")) . When I store this value in a js variable and try to access it, it takes "\n" as string only. It is not recognising it as newline
ajax calls in jsp:-
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=datagrid",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
$('#contentDiv').show();
fillDataGrid(msg);
}
});
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=chart",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
fillDataChartData(msg);
}
});
code in servlet:-
HttpSession session = request.getSession();
String method = request.getParameter("method");
if(method.equalsIgnoreCase("datagrid"))
{
JSONArray listjson = CSR.firstcalledMethod();
String chartformat = CSR.callingMethod2();
System.out.println("chartformat in servlet = "+chartformat);
String result = listjson.toString();
String checkDataExists = (String) (session.getAttribute("chartformat") == null ? "Invalid" : session.getAttribute("chartformat"));
if(!checkDataExists.equalsIgnoreCase("Invalid"))
{
session.removeAttribute("chartformat");
}
session.setAttribute("chartformat", chartformat);
out.write(result);
}
else
{
String chartResult = (String) session.getAttribute("chartformat");
session.removeAttribute("chartformat");
out.write(chartResult);
}
now in the same jsp which contains the ajax calls shown above I am trying to access the variable as :-
function fillDataChartData(dataVAR) {
var chartdata = dataVAR;
alert("chartdata = "+chartdata);
}
Suppose the response in ajax contains data "APAC-OTHER,0.05 \n FCS,99.95"(i.e. dataVAR = "ABC \n DEF \n GHI" ). Now, when I am trying to alert it in the function fillDataChartData(dataVAR), it shows "APAC-OTHER,0.05 \n FCS,99.95" in alert but I want it like APAC-OTHER,0.05
FCS,99.95
How should I do that?? Please help...
It's strange. May be there are some hidden chars in your response? Anyway, you can try to replace linebreaks by br tags:
function fillDataChartData(dataVAR) {
var chartdata = dataVAR.replace(/\\n/gm, '<br>');
alert("chartdata = "+chartdata);
}
Related
I am using jquery ajax to send my request from client to server. I modified my codes according to #Samuel J Mathew suggestion.
$('#create_kb_btn').click(function (e) {
e.preventDefault();
$.ajax({
url: 'create',
type: "POST",
data: $('#create_kb_form').serialize(),
success: function (data) {
$('#query_form').removeClass('hidden');
$('#query_res').removeClass('hidden');
<%
Gson gson = new Gson();
String probs = gson.toJson(request.getSession().getAttribute("probs"));
String years = gson.toJson(request.getSession().getAttribute("years"));
%>
var years = JSON.parse("<%=years%>");
var probs = JSON.parse("<%=probs%>");
if (years == null || probs == null) {
alert('null');
}
updatePlot(years, probs);
document.getElementById('query_div').scrollIntoView();
},
error: function(xhr, status, error){
alert(error);
}
});
})
I'm creating a session in my create method as follows
req.getSession().setAttribute("probs", probs);
req.getSession().setAttribute("years", ec.getYears());
But somehow I always get null for years and probs. However, when I refresh the page manually, I can get the value. can anyone tell me what I'm doing wrong?
Problem Analysis :-
Based on my primary analysis on the code I found following issues in your code
On Page loading
<%
Gson gson = new Gson();
String probs = gson.toJson(request.getSession().getAttribute("probs"));
String years = gson.toJson(request.getSession().getAttribute("years"));
%>
The values of probs and years will be null because you haven't created session at all and you are trying to create session on create_kb_form form submission.
Since you are using ajax post your page will not reloaded, so the values of
var years = JSON.parse("<%=years%>");
var probs = JSON.parse("<%=probs%>");
will always be null.
This is the reason why when you refresh the page you will find that it is working fine, because at that time you have session and all the values are populated correctly.
Solution:-
The solution for above problem is as follows
You need to create a ajax success handler method where you need to return the values of probs and years from the create method.
and move
var years = JSON.parse(data).years;
var probs = JSON.parse(data).probs;
if (years == null || probs == null) {
alert('null');
}
updatePlot(years, probs);
In short your ajax function look something like this
$('#create_kb_btn').click(function (e) {
e.preventDefault();
$.ajax({
url: 'create',
type: "POST",
data: $('#create_kb_form').serialize(),
success: function (data) {
$('#query_form').removeClass('hidden');
$('#query_res').removeClass('hidden');
var years = data.years;
var probs = data.probs;
if (years == null || probs == null) {
alert('null');
}
updatePlot(years, probs);
document.getElementById('query_div').scrollIntoView();
},
error: function(xhr, status, error){
alert(error);
}
});
})
and you need to move
<%
Gson gson = new Gson();
String probs = gson.toJson(request.getSession().getAttribute("probs"));
String years = gson.toJson(request.getSession().getAttribute("years"));
//Do json encode here and send as response here
%>
to your create method.
inside ajax success handler moreover you need consider the case when already session.
I have a hashmap which I have converted into a JSONObject. This JSONObject I am retrieving via a REST api using an AJAX call. What I wish to know is that how will the ajax look like in order to get the JSONObject which I can use afterwards.
My ajax call looks like this :
Ext.Ajax.request({
url : '...',
method:'GET',
scope : this,
success : function(result, request) {
console.log("2");
var data = Ext.decode(result.responseText)[0];
for (var i = 0; i < data.size(); i++) {
console.log("4. ");
}
}
})
The error which appears is
Ext.Error: You're trying to decode an invalid JSON String:
result.responseText returns the Invalid JSON String.Use this code
var responseArray = Ext.decode(response.responseText);
var data = responseArray.data;
console.log(data);
data variable will contain the JSON Object.
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
How can I pass a var from javascript to a servlet. Yes I know you can use getParameter on the servlet side, but I first need to do some javascript stuff then from there it need to pass that new variable to servlet.
See my Javascript example:
function openBrWindowAndSubmit() {
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //returns empty
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //works
}
As you can see in above example the first "alert" block returns empty, but the second one returns the correct encoded value because the document.forms[0].submit is already called. So is there a way I can get the second variable "textBodyValue" (which is outside of document.forms[0].submit) to the servlet? I'm calling this at the servlet side:
String test = req.getParameter("textBody");
Here's the JSP inside a form tag which calls the function on click:
<textarea id="textBody" name="textBody"></textarea>
<input type="button" onClick="openBrWindowAndSubmit();" value="Click Here to Preview Email">
Is there any workaround to this problem?
I've been trying to change the javascript function to:
function openBrWindowAndSubmit() { //v2.0
document.forms[0].target = "_blank";
document.getElementById("action").value = "view_template";
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
$.ajax({
url: 'http://localhost:8080/restricted/comm/Email',
data: textBodyValue,
// processData: false,
// contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
Can this work? i'm getting an undefined error when reaching the $ajax tag?
As an idea. Dont know if its correct ;) but you can check it at the jQuery api page.
$('#idOfTheForm').on('submit', function(e){
e.preventDefault();
data = { key : val , key2 : val2 };
$.ajax({
type: "post",
data: data,
url : "",
success : function(response){
console.log("return code was 200");
},
error : function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
return false;
}
Sending ajax request in UTF8 to the server that uses REST , disregards any part that is not English characters
I'm using JAVA with REST on the server side , and the client sends ajax requests in UTF8 , that includes Hebrew words .
The AJAX request :
var clientNumber = '12344432432';
var userID = '321321321';
var someHebrewWord = ...;
var someEnglishWord = ....;
var servletUrl = '/Management/services/manager/' + clientNumber + '/' + userID + '/' + someEnglishWord + '/' someHebrewWord;
alert('Sending this :' + servletUrl);
$.ajax({
url: servletUrl,
type: 'POST',
cache: false,
data: { },
success: function(data){
alert('Return value is:' + data);
window.location = "./replyPage.html";
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err + " " + JSON.stringify(jqXHR));
}
});
On the server side , I use REST :
#Produces({ "application/json" })
#Path("/manager")
public class Management {
#POST
#Path("{clientNumber }/{userID }/{someEnglishWord}/{someHebrewWord}")
#Produces("application/json")
public boolean insert(#PathParam("clientNumber") String clientNumber, #PathParam("userID") String userID,
#PathParam("someEnglishWord") String someEnglishWord, #PathParam("someHebrewWord") String someHebrewWord)
{
// do some stuff
}
#POST
#Path("{clientNumber }/{userID }/{someEnglishWord}")
#Produces("application/json")
public boolean updateSomething(#PathParam("clientNumber") String clientNumber, #PathParam("userID") String userID , #PathParam("someEnglishWord") String someEnglishWord)
{
// do other stuff
}
// more code
}
So , when the AJAX request is sent , the updateSomething() is invoked instead of insert() ,
even though I'm sending 4 fields , and not 3 !
What causes this , and how can I fix it ?
Much appreciated
Allowed characters in a URL is restricted. You have to encode the URL with encodeURIComponent.
A better option might be posting those parameters in a data -variable and using #FormParam instead of #PathParam.
in facebook fql theres this code
https://developers.facebook.com/docs/reference/api/batch/
curl \
-F 'access_token=…' \
-F 'batch=[ \
{"method": "GET", "relative_url": "me"}, \
{"method": "GET", "relative_url": "me/friends?limit=50"} \
]'\
https://graph.facebook.com
it suppose to to be sent with json
but I really dont understand how to do this
any help ?
thanks
You can simple use the BatchFB api its very powerful and easy , you dont have to deal will all of these stuff and it use the fql
for example to get all your friends
Later<ArrayNode> friendsArrayList = this.Batcher.query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
for (JsonNode friend : friendsArrayList.get()) {
.......
}
and its batched
I believe your question is how to execute a batch request using Facebook Graph API. For this you have to issue a POST request to
"https://graph.facebook.com"
and the post data to be sent should be
"batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#accesstoken"
in your case [#accesstoken must be replaced with your access token value].
This request will return the details of the owner of the access token(normally the current logged in user) and a list of 50 facebook friends(contains id and name fields) of the user along with page headers(can be omitted).
I am not sure whether you meant java or Javascript. Please be specific on it.
I am a C# programmer basically. Will provide you a code to execute the above request in C# here.
WebRequest webRequest = WebRequest.Create("https://graph.facebook.com");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-UrlEncoded";
byte[] buffer = Encoding.UTF8.GetBytes("batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#ACCESSTOKEN");
webRequest.ContentLength = buffer.Length;
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
if (webResponse != null)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string data = streamReader.ReadToEnd();
}
}
}
}
Here the variable data will contain the result.
Salah, here is the example i use as reference, i am sorry though i do not remember where i found.
FB.api("/", "POST", {
access_token:"MY_APPLICATION_ACCESS_TOKEN",
batch:[
{
"method":"GET",
"name":"get-photos",
"omit_response_on_success": true,
"relative_url":"MY_ALBUM_ID/photos"
},
{
"method": "GET",
"depends_on":"get-photos",
"relative_url":"{result=get-photos:$.data[0].id}/likes"
}
]
}, function(response) {
if (!response || response.error) {
console.log(response.error_description);
} else {
/* Iterate through each Response */
for(var i=0,l=response.length; i<l; i++) {
/* If we have set 'omit_response_on_success' to true in the Request, the Response value will be null, so continue to the next iteration */
if(response[i] === null) continue;
/* Else we are expecting a Response Body Object in JSON, so decode this */
var responseBody = JSON.parse(response[i].body);
/* If the Response Body includes an Error Object, handle the Error */
if(responseBody.error) {
// do something useful here
console.log(responseBody.error.message);
}
/* Else handle the data Object */
else {
// do something useful here
console.log(responseBody.data);
}
}
}
});