Reputation: 3819
I am trying to send JSON string
var json = {"city":value1, "country":value2};
$.ajax({
url : url,
data : json,
dataType : 'json',
success : function(response) {
alert(response);
}
})
In the URL
to which I make ajax call I am not getting how to get this string value there? What should I use request.getParameter
? What should be the value in the parameter?
Upvotes: 2
Views: 1002
Reputation: 3819
This might be a bad idea but has done the job. Thanks everyone for sharing your thoughts had hard time sending data. I saw all the suggested answers by @baadshah but, I couldn't implement a single one. :(. I reanalyzed the problem.
My problem is I can't retrieve the JSON
data in the server side page where as I was able to access other elements. My HTML page had one of these
<input type = "text" name = "fname" class = "imp"/>
In my JSP page I could use
String fname = request.getParameter("fname");
After being stuck for more than couple of hours and getting frustrated I thought for another way. This is the solution I found. This problem would be solved if I can club the JSON
string with any input tag with a valid name. The next moment I added this line in script tag
$('input[name=hide]').val(json);
var dataToBeSent = $("form#hidden").serialize();
In the HTML part I added following snippet.
<form name="hidden" id="hidden">
<input type="hidden" name="hide"/>
</form>
This solved my problem. This might not be the best way around but it did the job.
Upvotes: 2
Reputation: 121998
Ajax request :
var jsonObj= { jsonObj: [... your elements ...]};
$.ajax({
type: 'post',
url: 'Your-URI',
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (data) {
...
}
});
on server side :
String city = request.getParameter("city");
String country= request.getParameter("country");
Upvotes: 3