How to Use ajax& j Query in spring - javascript

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){
}
});

Related

Value passed by ajax from Javascript to C#, Replied but not saved

I pass a value to my C# part with ajax and I get a response back. But I can't save the value or use it in my C# code. More information below:
Ajax Call: (gallery.aspx)
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&typeIds=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
Code Behind (CodeFile):(gallery.aspx.cs)
Update: Full C# code snippet
public partial class gallery : System.Web.UI.Page
{
public List<string> images = new List<string>();
public List<string> imagesList = new List<string>();
public List<string> filteredImagesList = new List<string>();
public List<string> testList = new List<string>();
protected string imagesName;
protected string filterType;
protected void Page_Load(object sender, EventArgs e)
{
if (Request["call"].ParseString() == "ajax")
{
Response.Write(Request["typeIds"].ParseString().TrimEnd(','), true, ResponseType.Json);
filterType = Request["typeIds"].ParseString().TrimEnd(',');
}
else
{
filterType = "Not Assigned!";
}
}
}
Output on the page: Not Assigned!
Meaning <h1><%=filterType%></h1> in aspx file returns the else statement from aspx.cs file
But I get the response back in my javascript while console.log("From AJAX: " + resp) shows the result.
BUT I can't use filtertype's value in my c# codefile.
I can't understand how come the Response.Write(Request["type"].ParseString().TrimEnd(','), true, ResponseType.Json); gives back the Request["type"] to js part but don't save it for my codefile. Should it be anything like Response.Read or Response.Save or something?
Does someone know what is going on in here?
You can store the ajax response in a hidden field and then access that hidden field value in server side code.
<asp:HiddenField ID="HiddenField1" runat="server" />
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&type=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
$('#<%=HiddenField1.CliendId%>').val(resp);
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
You can then access in server side code like this:
HiddenField1.Value
OK. It will never be assigned in the way how you did it. Simply because when the page is loading and all controls are rendering no ajax calls are taking into account Page Life Cycles. Because of that on page load filterType is not assigned.
Although you have a couple of options
Use Ajax with update panel and PageRequestManager class
Change the value through JQuery or Vanilla JS by using <%=filterType.ClientID%>
If you need only front-end representation you can use either option. If you need it for further back-end I'm afraid option 1 only choice for you.

Calling a HTTP POST method in a MVC Controller from the View's Javascript & Database saving

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();
}

Object php and json encoding

i have this class on my php server:
class Voto implements JsonSerializable {
public $voto;
public $info;
public $codiceFiscaleStudente;
public $data;
public $idProva;
function __construct($voto,$idProva,$codiceFiscaleStudente,$data) {
$this->codiceFiscaleStudente=$codiceFiscaleStudente;
$this->voto=$voto;
$this->idProva=$idProva;
$this->data=$data;
$this->info=null;
}
public function jsonSerialize() {
return get_object_vars($this);
}
}
the problem is that the script doesn't send to the client the jsonObject.I've tried to find the error: the script works fine because i tried to send back not the jsonObject but a single properties of my class Voto.
this is my other server syntax
try{
$query="LOCK TABLES sostieneprova read;";
$success=mysqli_query($conn,$query);
if($success){
$voto=getVoto($conn,$_POST['idProva'],$_POST['studente_codiceFiscale']);
if(gettype($voto)==="object"){
$voto->info="Esiste giĆ  un voto dello studente in data ".$voto->data;
/*if in my Ajax-request i set datatype="html" and i send back echo($voto->info) it works fine.Instead if in my AJAX CALL in javascript i have set datatype "json" javascript doesn't receveid a jsonObject but an empty string.i think that the problem is with the function below json_encode*/
echo(json_encode($voto));
}
else{
throw new Exception ("Non esiste alcun voto dello studente nella prova: ".$_POST['idProva']);
//$query="UNLOCK TABLES;";
//mysqli_query($conn,$query);
}
}
else{
echo("Impossibile bloccare le tabelle per caricare il voto");
}
}
catch(Exception $e){
$query="UNLOCK TABLES;";
mysqli_query($conn,$query);
echo($e->getMessage());
}
JAVASCRIPT:
var ajax=$.ajax({
url:"responseregistrodocente.php",
data: queryString,
type:"POST",
datatype:"json",
cache:false,
ifModified:false});
ajax.done(
function(dettagliVoto){
alert(dettagliVoto.codiceFiscale);
});
ajax.fail(function(jqxhr){
alert(jqxhr.responseText);
});
Thanks for help.
if this could help: in my html page i have a the jquery document.ready and inside that i have:
$(".submitProve").on("click","button[name='visualizzaVoto']",caricaVotoHandler);
then in an exsternal file i have the function with the ajax request
function caricaVotoHandler(evento){
evento.stopPropagation();
//here there is other program code to build the queryString and the querystring //send the data correctly to the server.I've verified
var ajax=$.ajax({
url:"responseregistrodocente.php",
data: queryString,
type:"POST",
datatype:"json",
cache:false,
ifModified:false});
ajax.done(
function(dettagliVoto){
alert(dettagliVoto);
});
ajax.fail(function(jqxhr){
alert(jqxhr.responseText);
});
//}
}
If the script outputs properly if you only change echo json_encode($voto); to echo $voto->codiceFiscaleStudente; then your problem lies in your implementation of the JsonSerializable interface. try not using it:
If your class Voto only contains public members, all of which you are going to include in the JSON serialization, there's no need to implement JsonSerializable. Calling json_encode() on your object $voto will return the proper JSON string.
Also, in your first JS snippet, your alert call alert(dettagliVoto.codiceFiscale); looks like it should be using dettagliVoto.codiceFiscaleStudente instead, to match that property of your Voto class.

Ajax not calling controller method

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.

JQuery POST to Spring MVC Controller and parsing result in success function

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.

Categories

Resources