I am new to jquery/Ajax .
My Server code return the json data
But it did not received in jquery/ajax .
for which i have tried
this is my ajax request code
$.ajax({
type: 'post',
url:'http://localhost:8080/eduvib/webapi/question/getPaper',
dataType:'json',
data: {"subject":subject,"cls":classes,"diff":dificultylevel,"marks":marks},
success:function(response) {
alert(JSON.stringify(response));
},
error:function() {
alert("request failed");
}
});
And this is my server Side Code Which also return the response
#POST
#Path("/getPaper")
#Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_JSON})
#Produces(MediaType.APPLICATION_JSON)
public List<Question> getPaper(#FormParam("subject") String subject, #FormParam("cls") String cls,
#FormParam("diff") int diff, #FormParam("marks") int marks) throws Exception {
ArrayList<Question> mylist = new ArrayList<Question>();
mylist = getQuestionList.getData(subject, cls, diff, marks);
System.out.println(mylist);
return mylist;
}
And this is the Logs at server side which prints the response after hitting the ajax request
[Question [questionid=questionid, questiontext=kk, topicname=k,...... complete list
But in Ajax request its not getting
Related
I'm trying to send and ajax post request to my springboot mvc controller, but with no success. I've looked a number of similar topics, tried the given solutions, but with no success at all.
If I change the request type to GET, it triggers the controller endpoint.
The endpoint function is not even being triggered in the controller. It is showing only the following error in browser console: jquery-3.4.1.js:9837 POST http://localhost:8080/rede-credenciada 500
I made the same request with postman and it gives the following error:
{
"timestamp": "2020-07-09T17:46:20.920+0000",
"status": 999,
"error": "None",
"message": "No message available"
}
Note: It only happens with POST request, if I change to GET, it works fine. The request is "listened" by the controller.
Here is my ajax request:
const json = {
idGrupoProcedimento: 0,
idTipoEspecialidade: $("#especialidade").val(),
uf: $("#estado").val(),
codCidade: $("#cidade").val()
}
const jsonString = JSON.stringify(json);
$.ajax({
url: "/rede-credenciada",
type: 'POST',
contentType: "application/json",
dataType: "application/json",
data: jsonString,
success: function(data){
console.log(data);
},
error: function(e) {
console.log(e.message);
}
});
Here, my endpoint:
#RequestMapping(value = "/rede-credenciada", method = RequestMethod.POST, consumes = "application/json")
#ResponseBody
public RedeCredenciadaResponse buscaRedeCredenciadaPorFiltro(#RequestBody RedeCredenciadaRequest request) {
... some logic
RedeCredenciadaResponse redeCredenciada = new RedeCredenciadaResponse();
redeCredenciada.setPessoasFisicas(pessoas);
redeCredenciada.setEmpresas(empresas);
return redeCredenciada;
}
And here is my wrapper class:
public class RedeCredenciadaRequest {
private int idGrupoProcedimento;
private int idTipoEspecialidade;
private String uf;
private String codCidade;
public int getIdGrupoProcedimento() {
return idGrupoProcedimento;
}
public void setIdGrupoProcedimento(int idGrupoProcedimento) {
this.idGrupoProcedimento = idGrupoProcedimento;
}
public int getIdTipoEspecialidade() {
return idTipoEspecialidade;
}
public void setIdTipoEspecialidade(int idTipoEspecialidade) {
this.idTipoEspecialidade = idTipoEspecialidade;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCodCidade() {
return codCidade;
}
public void setCodCidade(String cidade) {
this.codCidade = cidade;
}
The error:
In your ajax request you are using dataType:'application/json', According to jQuery’s Ajax-Related Methods Description
// The type of data we expect back
dataType : "json",
Value of dataType shoud be json, or xml, or html, etc.
i tried accessing my controller through ajax to get DB results but it wont work. The ajax is inside a submit button and executes well without the ajax. The code is supposed to execute a query and check if the input exists.
Here's my ajax
var jsonData = {
"appname": appname,
"txtype": txtype,
"ipaddress": ipaddress
};
$.ajax({
type: 'POST',
url: "checkaccesspermission.html",
data: jsonData,
success: function(data) {
if(data == "exists"){
alert('Permission Already Exists!');
return false;
}else{
alert('Add Permission test Succesful!');
return true;
}
},
async: false
});
here's my controller
#RequestMapping(value="/checkaccesspermission", method=RequestMethod.GET)
public String checkaccesspermission(#ModelAttribute("loginForm") IpAccessManagementModel loginForm, Model model,
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID) throws IOException{
System.out.println("CHECKACCESSPERMISSIONs");
IpAccessManagementModel sub = new IpAccessManagementModel();
//System.out.println("<script language='JavaScript'>alert('Hello');</script>");
sub.setAppName(appID);
sub.setTxtType(txtype);
sub.setIpAddress(ipaddress);
System.out.println(ipaddress);
ipAccessMGTDAO.addPermission(sub);
String resultCheckExist = ipAccessMGTDAO.checkAccessPermission(sub);
return resultCheckExist;
}
Remove the .html extension and Change your method annotation in the controller to method=RequestMethod.POST
also remove
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID
because its a Post request
I am using Play 2.2.6 and need to get List<String> or String[] from controller to my jQuery Ajax call.
My controller looks like:
public static Result list(){
List<String> cname = new ArrayList<String>();
String[] arr= new String[]{"abc","abc2"};
return ok(index.render(arr));
}
Code for Index method:
public static Result index(){
String[] arr= new String[]{"abc","abc2"};
return ok(index.render(arr));
}
and my jQuery function looks like:
<script>
$(function() {
ajaxCall();
});
var ajaxCall = function() {
var ajaxCallBack = {
success : onSuccess,
error : onError
}
jsRoutes.controllers.Application.list().ajax(ajaxCallBack);
};
var onSuccess = function(data) {
console.log(data)
}
var onError = function(error) {
alert(error);
}
</script>
This script is in index.scala.html file and routes are:
GET / controllers.Application.index()
POST / controllers.Application.list()
GET /javascriptRoutes controllers.JavascriptRoute.javascriptRoutes
Ajax response works perfect for String type e.g. if I say
return ok("This is string");
Then I can see it in Ajax response but can't figure out why array or list throws below error:
Internal server error, for (GET) [/] ->
cannot find symbol [symbol: method ok(java.lang.String[])] [location: class controllers.Application]
Just to mention I defined this method as POST in routes.
Any suggestions?
The problem is that you are responding with a rendered index template and the exception is being thrown when trying to render that template. What you want to do is respond with the JSON data.
public static Result list(){
String[] arr= new String[]{"abc","abc2"};
return ok(Json.toJson(arr));
}
tested it locally in my browser with the following code
$.ajax({
method: "POST",
url: "/",
dataType: "script",
success : function(data) {
console.log(JSON.parse(data));
}
});
EDIT:
So you could do something like this:
List<ObjectNode> objectNodes = new ArrayList<>();
ObjectNode objectNode = Json.newObject();
objectNode.put("Latitude", "13.679389");
objectNode.put("Longitude", "-13.679389");
objectNodes.add(objectNode);
// create loop to add more nodes
return ok(Json.toJson(objectNodes));`
And in your ajax response you will now have a list of nodes with Longitude and Latitude values
For my application I am writing a POST request to send array of parameters from a checkbox list. Its working for get request but not working for post request. What is the error in my code.
My code on the client side for sending ajax request to the server.
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "POST",
url : '/rest/channelstats/my/rest/controller',
data : {
// monitoring : monitoring,
// nonMonitoring: nonMonitoring,
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
}
});
})
My java code on the server side.
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
}
}
Its working for HTTP GET requests but not working for POST requests.How should I solve this problem?
According to your jquery post request, you should use DAO(Data Access Object) to parse the request data. So you should add class Request
public class Request {
private int monitoringLength;
private int nonMonitoringLength;
//getters and setters
}
And change controller to
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestBody Request request){
System.out.println("MonitoringLength =>"+request.getMonitoringLength());
System.out.println("NonMonitoringLength=>"+request.getNonMonitoringLength());
}
I try to send array of integers from ajax to jersey web service.
javascript
var myFoods = [];
// adding items via push
$.ajax({
url: "ws/food/" + idParam + "/recomendation",
type: "POST",
data: {'foods[]': myFoods,
async: false,
});
web service
#POST
#Path("/{id}/recomendation")
public void updateRecomendations(
#PathParam("id")
Long id,
#FormParam("foods[]")
List<Long> recomendedFoodIds
) {
...
}
With non empty arrays this code work good but if myFoods is empty i have error
"HTTP Status 500 - java.lang.IllegalStateException: The #FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded"
How to fix it?
I solved the problem with this:
#POST
#Path("/{id}/recomendation")
public void updateRecomendations(
Form form,
#PathParam("id")
Long id
) {
List<Long> foods = getFoodIdsFromForm(form);
...
}
private List<Long> getFoodIdsFromForm(Form form) {
Map parametrsMap = form.asMap();
final List<Long> foodIds = new ArrayList<Long>();
if (parametrsMap.get("foods[]") != null) {
List<String> idsString = (List<String>)parametrsMap.get("foods[]");
for (String id : idsString) {
foodIds.add(Long.parseLong(id));
}
}
return foodIds;
}