The following script is suppossed to return for me the requests booked and append the data I got through json to html.
function readUsers() {
//display ajax loader animation
$( '#ajaxLoadAni' ).fadeIn( 'slow' );
$.ajax({
url: 'user_transactions/get_request',
dataType: 'json',
success: function( response ) {
alert(response)
for( var i in response ) {
response[ i ].updateLink = updateUrl + '/' + response[ i ].id;
response[ i ].deleteLink = delUrl + '/' + response[ i ].id;
}
//clear old rows
$( '#records' ).html( '' );
//append new rows
$( '#readTemplate' ).render( response ).appendTo( "#records" );
//hide ajax loader animation here...
$( '#ajaxLoadAni' ).fadeOut( 'slow' );
}
});
} // end readrequest
I am able to get the data from the url but when I alert the response , it is empty , how can I pass the data through the success function?
It looks like you do not have a good response from the server side. First, define the type of you request, so add the type in your ajax request setting type: 'POST' or 'GET'. It would be better if you post here the server side code.
Related
I am able to get the data from ajax using system.out.println. However, I am unable to pass the data to servlet. It shows null always.
Here is my jQuery:
function expressCheck(number) {
var Self=[];
for(i=1;i<=<%=itemCodeList.size()%>;i++) Self[i-1] = document.getElementById("qtyGuestNumber_" + i).value;
$.ajax({
url: "ViewCategories.jsp",
data: {"expressData" : Self[number-1]}
});
};
I am trying to send an array of strings to a java/spring backend solution and after trying to do it in many ways I gave up cause I always have errors (malformed request, missing body...)
I am pretty surprised cause followed many examples without success. I am sure the problem is in the jquery side cause I changed the method to GET in order to see the request as clear as possible and I saw the data is not represented as expected.
This is the function:
function duplicateSection() {
var table = document.getElementById("tbody");
var ids = [];
var i = 0;
var totalRows = table.rows.length;
for(i; i < totalRows; i++){
var checkbox = table.rows[i].cells[0].children[0];
if(checkbox.checked){
var id = table.rows[i].cells[1].children[0].value;
ids.push(id);
}
}
var jsonString = JSON.stringify(ids);
alert(jsonString);
$.ajax({
url: './duplicatesections',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jsonString,
success: function(data) {
alert('sent');
}
});
}
When I show with alert the JSON string I get the expected result: ["1"]
When the request is sent I get this other result: http://localhost:8080/duplicatesections?[%221%22]
Why do I have this representation?: [%221%22]
As an extra information, I am using spring boot and thymeleaf in case it is relevant.
send a POST request.
$.ajax({
url: './duplicatesections',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jsonString,
success: function(data) {
alert('sent');
}
});
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);
}
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.
I am having some ajax difficulties (and am newish to ajax, but have done a fair bit of searching) when calling a java rest server that I have written. I have a test html page running within the Rest server (using Jetty) and I use the following call -- which works successfully using a .get:
$('#getRVLakeForm').submit(function(e) {
var handle = $('#insertRVLakeHandle').val();
var lakekey = $('#RVLakeKey').val();
var temp = $('#RVLakeTemp').val();
var speed = $('#RVLakeWindspeed').val();
var degrees = $('#RVLakeWindDegrees').val();;
$.get('${pageContext.request.contextPath}/api/recent/lake/' + handle + "/" + temp + "/" + speed + "/" + degrees + "/" + lakekey, function(data) {
alert(data.lake[0].oid);
$('#RMLakeResponse').text("back");
});
Here is the JSON the Rest server returns:
{"user":[],"lake":[{"oid":"519b9a1a3004f8fa1287502a","type":"Lake","handle":"nightstalker","viewedhandle":"","viewedlaketag":"TXFORK","viewedusername":"","timestamp":1369152026668}]}
This call executes the Rest Api and gets JSON back as expected... When I attempt to call the same Rest Api from HTML/PHP application, running under MAMP -- the ajax call works on the out bound call -- I can debug the Java Rest server and see the call come in, and it executes as designed creating JSON to send out. The problem is that I never get a call to the success function in the ajax call (I am not seeing the error function called either).
urlrecent = "http://localhost:8080/server/api/recent/lake/" + handle + "/" + temp + "/" + speed + "/" + degrees + "/" + lakekey;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "jsonp",
url: urlrecent,
success: function (data) {
alert("hello there!");
alert(data)
},
error: function () {
alert('failed');
}
});
I have even tried a getJSON instead..no luck. In the mean time I will continue search Stack and the web for something that will work. I have tried a dataType of just "json" as well.
Thanks in advance.
=====
Yes, munged the contentType, but that didn't matter.
Try it in IE8 and set dataType: "html"
urlrecent = "http://localhost:8080/server/api/recent/lake/" + handle + "/" + temp + "/" + speed + "/" + degrees + "/" + lakekey;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "html",
url: urlrecent,
success: function (data) {
alert("hello there!");
data = JSON.parse(data);
alert(data)
},
error: function () {
alert('failed');
}
});
if you get syntex error at data = JSON.parse(data) or "hello there" in alert , it is encoding problem. In this case you should use response.setCharacterEncoding("UTF8")