executos
executos

Reputation: 15

How to transform $.post to $.ajax?

I have this $.post peace of code:

$.post("../admin-login",
{
   dataName:JSON.stringify({
   username:uname,
   password:pass,
   })

}, function(data,status){
    console.log("Data:"+data);
    answer = data;
    }
);

and I wont to transform it to $.ajax. On the servlet side I am demanding request.getParamter("dataName") but I do not know how to write data: section in $.ajax so that I can get parameters like that(request.getParamter("dataName"))? Also, it seems to be problem with this type of code, I am asuming cause of async, that I cannot do this:

var answer="";

function(data,status){
        console.log("Data:"+data);
        answer = data;
}

And that answer is keeping empty(""), even though in console is written in deed "true" or "false" as my server answers. What is this about? Thanks in advance.

I found out that problem is in the click() event. Ajax finishes when click() finishes, so I am not able to get data before event is done. What is bad in that is that I cannot fetch data because it is finished. Does anyone know how to solve this?

Upvotes: 1

Views: 91

Answers (3)

jsam
jsam

Reputation: 301

$.post("../admin-login",
{
   dataName:JSON.stringify({
   username:uname,
   password:pass,
   })

}, function(data,status){
    console.log("Data:"+data);
    answer = data;
    }
);

becomes

function getResult(data) {
  // do something with data
  // you can result = data here
  return data;
}

$.ajax({
  url: "../admin-login",
  type: 'post',
  contentType: "application/x-www-form-urlencoded",
  data: {
   dataName:JSON.stringify({
   username:uname,
   password:pass,
   })    
},
  success: function (data, status) {
    getResult(data);
    console.log(data);
    console.log(status);
  },
  error: function (xhr, desc, err) {
    console.log(xhr);
  }
});

Upvotes: 1

NightOwlPrgmr
NightOwlPrgmr

Reputation: 1374

You could try structuring your AJAX request like the below:

var dataName = username:uname, password:pass;

$.ajax({
    url: "../admin-login",
    data: JSON.stringify(dataName),
    type: "POST",
    cache: false,
    dataType: "json"
}).done(function(data, status) {
    console.log("Data:"+data);
    answer = data;
});

Upvotes: 0

arterzatij
arterzatij

Reputation: 82

You need to see how the information os arriving to your servlet as query parameter or payload.

See this HttpServletRequest get JSON POST data

Upvotes: 0

Related Questions