Unable to POST JSON object from Javascript to a Servlet via AJAX - javascript

I am trying to POST a JSON object to a servlet via AJAX. However, the object is null in the servlet. I am unable to figure out what's wrong with this code.
JAVASCRIPT
function submitValues(event, val1, val2)
{
var xmlHttpObj = new XMLHttpRequest();
if(window.XMLHttpRequest)
{
xmlHttpObj = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");
}
var jsonObject = submitTheValues(event, val1, val2);
alert("json is:" +jsonObject);
var json = JSON.stringify(jsonObject);
alert("json after stringify:" +json);
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/json");
xmlHttpObj.send(json);
}
SERVLET
String jsonObj = request.getParameter("json");

If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode.
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");
xmlHttpObj.send('json='+encodeURIComponent(json));

Related

How to pass multiple parameters to #RequestBody using JavaScript XMLHttpRequest

I have that POST method:
function saveSchemaInDatabase(schemaName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName);
}
and i am catching that shoot in my controller in that way:
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName) {
return "redirect:/user";
}
Can someone tell me how i can send multiple params to that controller? For example i want something like that:
//shoot
function saveSchemaInDatabase(schemaName, diagramJson) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName, diagramJson);
}
//catch
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName, #RequestBody String diagramJson) {
return "redirect:/user";
}
I hope you know what i mean. Of course my way doesn't work. Error 400 appears.
Can someone help me? Im done :(
You can crete FormData object and add as many values as you want inside it
var data = new FormData();
data.append("email", "eve.holt#reqres.in");
data.append("password", "pistol");
Then send this formData object to the post request
Like this
xhttp.send(data);

How can I pass a parameter from javascript to RESTful web service using XMLHttpRequest

When i try to print the received parameter at the web service.
The parameter is empty.
If I view domain server log of glass fish server I can see the following
print:
Inside getJson()
countryKey =
So I understand the request arruved to the web service, but the parameter
that was sent from the javascript url is empty
// This is the code of the web service method
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson(String countryKey) {
System.out.println("Inside getJson()");
System.out.println("countryKey = " + countryKey);
return "countryKey = " + countryKey;
}
// This is the javascript method
function populateDistrictList() {
var element = document.getElementById("selectCountry");
var selectedCountryKey = element.value;
var selectedCountry = element.options[element.selectedIndex].text;
var xmlHttp = new XMLHttpRequest();
var url = "http://localhost:8080/MissionWS/webresources/generic?selectedCountryKey="+selectedCountryKey;
xmlHttp.open('GET', url, true);
xmlHttp.responseType = 'json';
if (xmlHttp) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
} else {
alert("Something is wrong !");
}
}
};
xmlHttp.send();
}
}
Please try adding the #QueryParam to your method signature as follows.
public String getJson(#QueryParam("selectedCountryKey") String countryKey)

Send javascript arrays via ajax without using jquery

i have a javascript array with values like "correct", "wrong".
I want to send this array to my php file using ajax. But im not familiar with how.
This is what i have tried so far..and i would like to do this without jquery.
var hold=[];
for(t = 0;t <= 10; t++){
answers_Arr = document.getElementsByName("question"+t);
for (k = 0; k < answers_Arr.length; k++){
if(answers_Arr[k].checked){
hold[t] = answers_Arr[k].value;
//document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
break;
}else{
hold[t] = "no";
continue;
}
}
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();
}
Here is an example of sending the json string with POST through AJAX:
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//
}
xmlhttp.open("POST","result.php",true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonString);
Avoid sending json strings with GET method because if the request string gets too long, the browser will throw you an error.
Now in your php script you will have all the data in $_POST
Edit: Looks like on some versions of php, the requests that have other Content-type, like application/json, the $_POST has an empty value. To fix this you can do:
$_POST = json_decode(file_get_contents('php://input'));
replace this line
xmlhttp.open("GET","result.php?res="+hold[],true);
with
xmlhttp.open("GET","result.php?res="+jsonString,true);

Retrieving String array value in Ajax response

I am doing ajax call from a jsp page that will go to the servlet. The servlet is returing one String array. That I want to use in ajax response data but each time I am getting true not the string array. How can I get string array in response text.
if(window.XMLHttpRequest){
xmlDoc = new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
}
url="./MacroOperations?copyRoleId="+copyRoleId;
xmlDoc.open("POST",url, false);
xmlDoc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlDoc.send(null);
var status=0;
if(xmlDoc.readyState == 4){
if (xmlDoc.status == 200) {
status=xmlDoc.responseText;
alert(status);
}
}
I think you can just return the String value in your servlet.

How to pass a JSON object using form data to a rest service using JS

I have a rest webservice which can accept a string. I want to pass a json object as a string to this service. I have to use a HTML page with some textfields and has to pass the form data to the service. can any one help??
Thankyou
you can try this
function callWebService{
var field= document.getElementById('field').value;
//use jquery to convert to json object
//see comment for more info on this
var ws = 'http://localhost:8080/WebServicePath/';
var url = ws + field;
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Success");
}
else {
alert("Failure");
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}

Categories

Resources