I am new to Ajax. i am trying to call my controller method but call from Ajax not invoking url i am given.. here my controller method and ajax call in my jsp file..
#RequestMapping(value = "/getdata", method = RequestMethod.POST)
public #ResponseBody String add(#RequestParam(value="userDetailObject", required=true) User_Details u,Model model) {
System.out.println("In the controller method..");
String result=null;
result="From controller :"+u.getEmail();
System.out.println("at controller .."+result);
return result;
}
and my Ajax is
//script type="text/javascript" src="../jquery-1.4.4.js"
var jq = jQuery.noConflict();
function getData() {
alert("hello");
// get the form values
var email = $('#email').val();
// var education = $('#education').val();
$.ajax({
type : 'POST',
dataType: 'json',
url : "/SpringDemoSts/getdata",
data : 'email=' + email,
success : function(response) {
// we have the response
//$('#info').html(response);
$('#email').val(response);
//$('#education').val('');
},
error : function(e) {
alert('Error: ' + e);
}
});
}
/script
what is wrong i am doing wrong here ?
the url defined in ajax :
/SpringDemoSts/getdata
is didfferent to that in the requestmapping shown
/getdata
and the parameter is called userDetailObject and your ajax call defines data incorrectly,you are using request parameters style as the data. When in fact you need json/a plain primitive or string.
Related
I am trying to update a value in my database. When the user presses the update button this script is called.
View Code:
<script>
function scr_UpdateQuote(field) {
var r = confirm("Are you sure you want to update your quote?");
if (r == true) {
var textBox_UserTitle = document.getElementById(field);
*CODE TO POST METHOD HERE*
}
}
</script>
In the controller, the value is then revived and saved into the database. A message is sent back to let the user know their quote was updated.
Controller Code:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
*REPLACE QUOTE IN DATABASE*
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
I am having difficulty finding out how to write the code described between the **'s
(For the database part I have a user-id that can be used to identify the row)
You can use form posting like this:
$("#YourForm").submit(function() {
$.post("/YourController/UpdateQuote", $("#YourForm").serialize())
//this will serialize your form into:
// newQuote=someValue&&someOtherVariable=someOtherValue etc.
.done(function(data) {
// do what ever you want with the server response
});
})
or you can use an ajax post:
$.ajax({
type: "POST",
url: "/YourController/UpdateQuote",
data: {newQuote: document.getElementById(field)},
dataType: "json",
success: function(data) {
// do what ever you want with the server response
},
error: function(){
// error handling
}
});
For using the data, assuming you have an DbContext called MyDbContext:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
// get userID somehow, either from session, or pass as another parameter here
using (var dc = new MyDbContext)
{
var quoteToUpdate = dc.QuotesTable.FirstOrDefault(q => q.UserID == userID)
quoteToUpdate.quoteColumn = newQuote;
dc.SaveChanges();
}
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
I am new to Spring with AJAX.
My requirement is to check whether email is registered or not, when user clicks on check availability. I am successfully making calls to the controller class but the response is displayed in the browser instead of in same jsp and not entering the success block. I am unable to find the problem.
Below is sample code:
#Controller
public class CheckAvailbiltyEmailController {
#RequestMapping(value="/check",method = RequestMethod.GET)
public ModelAndView viewAjaxEmail(Map model){
return new ModelAndView("CheckEmailAvaliblity");
}
#RequestMapping(value="/check", method=RequestMethod.POST)
public #ResponseBody String ajaxEmailCheck(#RequestParam("email") String email){
System.out.println("Email is:"+email);
return "Please carry on registration";
}
}
My Ajax code:
$.ajax({
type:"POST",
url:"/check"
success:function(data){
alert("Inside Success");
$('#resp email').html(data);
}
error: function(e){
}
});
You need to specify the data you want to send to the server,
The controller will accept "email" as the RequestParam.
Do it like the following snippet :
$.ajax({
type:"POST",
url:"/check",
data: {"email":"email#to.check.com"},
success:function(responseData){
alert("Inside Success");
$('#resp email').html(responseData);
},
error: function(e){
}
});
this is my javascript code
<script type="text/javascript">
function callMe() {
var districtId = $("#district").val();
alert(districtId);
$.ajax({
type: "POST",
url: "addBranch",
data: "districtId=" + districtId,
success: function(response) {
}
});
}
</script>
this is my controller code
#RequestMapping(value = "/addBranch", method = RequestMethod.POST)
public #ResponseBody
List getForm1(#ModelAttribute Branch branch, Model model,#RequestParam("districtId")
int districtId) {
try {
districtVillageList = villageService.getDistrictVillageList(districtId);
} catch (Exception er) {
log.error("error in addLoanType=" + er);
}
return districtVillageList;
}
I am getting the list in the controller, but as i am new to ajax,i dont know how to retrieve the list in the ajax and use the retrieved values in jsp...Please can any one helo me??
As you have returned the list in the controller, just get in the response and iterate it using for-in loop
something like below,
<script type="text/javascript">
function callMe() {
var districtId = $("#district").val();
alert(districtId);
$.ajax({
type: "POST",
url: "addBranch",
data: "districtId=" + districtId,
success: function(response) {
for (var i in response){
// response[i].getterMethodHere
}
}
});
}
</script>
try using json objects to send the response instead of list. Learn More from jquery loop on Json data using $.each and jQuery loop over JSON result from AJAX Success?
I have integrated jQuery into a Spring MVC application. I have a form on my JSP page and I am doing an ajax POST to send the form to the controller:
$("#myform").submit(function() {
$.ajax({
type : 'POST',
url : '/MyApp/search/searchResults',
data : $(this).serialize(),
dataType: 'html',
success : function(data) {
$("#tabs-4").append(data);
}
});
return false;
});
The success function will load the data into a new tab. What I am finding is that data returns the HTML of my original page (from which I submitted). Instead, I would like to be able to parse the ModelAndView object that is being returned from the controller. For example:
${searchResults.searchStr}
Is it normal for data to return the page HTML? Is there anyway that I can parse the ModelAndView object in the success function, and then pass it to my new tab div?
Here is my Controller code:
#RequestMapping(value = "/searchResults", method = RequestMethod.POST)
public ModelAndView searchResults(
#ModelAttribute(value = "search") SearchVO search,
BindingResult result) {
// Set the view and search object
ModelAndView mv = new ModelAndView("newSearch");
mv.addObject("searchResults", searchResults);
return mv;
}
Thanks!
Yes you can return the html content from the controller to your ajax function. If you are interested in to use the instance in the jsp you would have to serialize it in to json and send it. Using jquery you could render it on the jsp. For example,
//Controller
public #ResponseBody<Class_name> search(...){
return searchResults;
}
//jsp
function renderResult(){
$.ajax({
url:'url',
dataType:'json',
...
..
success: function(data, status, xhr){
$.each(data, function(k, v){
$('#my_div').append(...k,v...);
}
}
});
}
Looking at your requirement I would suggest you to use the first method where you return the html itself and the jsp page which you return could be render with the searchResults.
I am trying to call a controller action from a jquery UI dialog.
What I have currently is this:
.html("<p><textarea name=\"TextMessage\" id=\"textItems\" rows=\"10\" cols=\"72\" /><br /><br /><input type=\"button\" style=\"float:right;\" id=\"submitData\" onclick=\"Test()\" value=\"Submit\" /></p>");
The script I am using to call the controller action is this one:
<script type="text/javascript">
function Test() {
$ajax({
url: '<%= Url.Action("GetData", "Report") %>',
success: function (data) {
alert(data);
}
});
};
</script>
And the controller action is this:
[HttpGet]
public JsonResult GetData()
{
return Json("success", JsonRequestBehavior.AllowGet);
}
I would like to know if I am doing something wrong, I am trying to get this to work but without any success. When I am trying directly to start the controller via http://localhost:1322/Report/GetData it works fine, so that means that the script is not setup properly.
You should try:
url:'#Url.Action("GetData", "Report")'
MVC will automatically add "Controller" to the end of the second parameter when it is looking for the controller.
Edit:
This code may work:
function Test() {
$.ajax({
type: "GET",
dataType: "json",
url: '#Url.Action("GetData", "Report")',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function(xhr, status, error) {
alert(error);
}
});
}
Edit 2:
Changed to use Razor syntax so that this code will work with Razor/MVC3.
You are using MVC-2 syntax on Url.Action. This should work:
function Test() {
$.ajax(
{
url: '#Url.Action("GetData", "Report")',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (x, err, desc) {
alert(desc);
}
}
);
};
Because you are calling an action method that is returning a json object you can use the jQuery.getJSON() method.
<script type="text/javascript">
function Test() {
$.getJSON(
'#this.Url.Action("GetData", "Report")',
function (data) {
alert(data);
}
});
};
</script>
You may try jsaction too:
http://jsaction.codeplex.com
We can call Controller method using Javascript / Jquery very easily as follows:
Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = null;
try
{
Processing...
Get Result and fill arr.
}
catch { }
return Json(arr , JsonRequestBehavior.AllowGet);
}
Following is the complex type (class)
public class A
{
public string property1 {get ; set ;}
public string property2 {get ; set ;}
}
Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.
function callControllerMethod(value1 , value2) {
var strMethodUrl = '#Url.Action("SubMenu_Click", "Home")?param1=value1 ¶m2=value2'
$.getJSON(strMethodUrl, receieveResponse);
}
function receieveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].property1);
}
}
}
In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.
receieveResponse is the callback function receiving the response or return value of the controllers method.
Here we made use of JSON , since we can't make use of the C# class object
directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:
Json(arr , JsonRequestBehavior.AllowGet);
and returned that Json object.
Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.
For more detail click here