Data not going to controller using Ajax - ajax

I am new to AJAX and I am trying to send some data to the controller using the AJAX. on clicking the button "Start Event", nothing is happening..
This is my jsp page where I have written the AJAX code
<c:forEach items="${scheduledEvents}" var="event">
<div class="col-md-3" id="eventId">
<div class="card-counter primary">
<div id="head" class="card-counter head-color"></div>
<span class="count-head">${event.eventName}</span>
<br>
<span class="count-name">Date : ${event.date}</span>
<span class="count-name">Location : ${event.location}</span>
<span class="count-name">Hosted By : ${event.hostName}</span>
<span class="count-name">Description : ${event.description}</span>
<br>
<br>
<div class="count-join">
<button class=" btn" id="${event.linkId}" style="background-color: #cc3300;"><font style="color: white;">Start Event</font></button>
</div>
</div>
</div>
</c:forEach>
<script type="text/javascript">
$(function() {
$('.count-join').on('click',function(){
var eventData = $(this).attr("id")
.ajax({
url : 'startEvent?data=' +eventData,
type : 'GET',
contentType : 'application/json',
success : function(data){
$
.get(
'${pageContext.request.contextPath}/startEvent',
function(data,status) {
$("#eventId").html(data);
}
);
}
});
});
});
</script>
And this my controller mapping
#RequestMapping(value="/dashBoard/startEvent")
public ModelAndView startScheduledEvent(#RequestParam("data")String data)
{
System.out.println(data);
return new ModelAndView("DashBoard");
}
Where am I wrong? please give some detailed explanation as I do not know much about AJAX. Thanks in advance.

As per you controller #RequestMapping, you have missed the /dashBoard in ajax call.

Related

can i refresh a table from presently showing model-popup

I need to reload a table or div inside a model popup continuously, i failed with my code can you help me....
i tried with ajax ..code is below but its is not updating chats (i am doing a chat task)
**My Ajax code to check new message is or not**
function check_msg()
{
$.ajax({
type: "POST",
url: "<?php echo site_url('member/check_message')?>/",
datatype: "JSON",
success: function(data) {
data = JSON.parse(data);
if(data.MsgStatus == "1")
{
$('#newchat').ajax.reload();
} });}
**HTML**
<div class="modal-body form">
<form action="#" id="chatform" class="form-horizontal">
<input type="hidden" value="" name="UserId"/>
<div class="form-body">
<div class="container" id="container">
<table id="newchat">
<div class="Scroll" id="Scroll">
<div id="messagesout"></div>
</div> </table> </div</div>
function reload_table()
{
table.ajax.reload();
}
Use this code in your ajax and call it

How to use Ajax to update RenderBody()

I am trying to work with ajax in order to update only a partial view and not the whole view. In the following example I want to refresh the page-content section.
this is my layout.html.
<body>
<div id="container" class="effect">
#Html.Partial("_head")
<div class="boxed">
<section id="content-container">
#if (ViewData["Errors"] != null)
{
<div class="panel" style="background-color:white;">
<div class="panel-heading">
<h3 class="panel-title">
Page title
</h3>
</div>
</div>
}
<div id="page-content" class="container">
#RenderBody()
</div>
</section>
</div>
</div>
</body>
Partial view _head contains the menu with href links for example:
<a id="a1" href="">Menu Item 1</a>
In layout I am trying to use the following:
<script>
$(document).ready(function () {
$("#a1").click(function () {
A1();
});
function A1( ) {
$.ajax({
url: '#Url.Action("PartialViewMethodFromController", "HomeController")',
success: function (response) {
$('#page-content').html(response);
}
});
}
});
</script>
And my HomeController
public ActionResult PartialViewMethodFromController()
{
var model = service.GetAll();
return PartialView("PartialViewMethodFromController", model);
}
It kinda works - the partialview is refreshing for a moment and the partialview is show correctly and then the whole page goes on and refreshes.
Am I missing something crucial here?

Kendo Mobile - Submit Entire Form

I have a kendo mobile form that I will be using to capture some information from my users.
I would like to post the data to a web service or aspx(test page) using ajax. It seems like overkill to use MVVM for a form that the user fills out and there will be no reads/updates/deletes.
The ajax call happens but I cannot figure out how to post the data . Nothing goes over if i use $(this).serialize(). If I hard code some data, then it works.
There are going to be a lot of controls on the page and i hope i don't have to manually build the form data. I cannot add a <form> tag as it breaks the styling of the page.
If there is a more "kendo" way of doing this please show me how. Thanks
Here is what I have so far.
//Submit Form
function submit_form(e) {
$.post('TestPost.aspx', $(this).serialize(), function (data) {
// This is executed when the call to web service was succesful.
// 'data' contains the response from the request
alert(data);
}).error(function (xhr, ajaxOptions, thrownError, request, error) {
alert('xrs.status = ' + xhr.status + '\n' +
'thrown error = ' + thrownError + '\n' +
'xhr.statusText = ' + xhr.statusText + '\n' +
'request = ' + request + '\n' +
'error = ' + error);
});
e.preventDefault();
}
//Example of html controls
<div id="checks" data-role="view" data-title="Foo" data-layout="checklayout">
<ul data-role="listview" data-style="inset" data-type="group">
<li>Floor
<ul>
<li>
<label for="Foo">
<input type="radio" name="Foo" id="FooOk" value="Ok" />
Ok</label>
</li>
<li>
<label for="Foo2">
<input type="radio" name="Foo" id="FooNotOk" value="NotOk" />
Not Ok</label>
</li>
<li id="Comment1" class="divComment" style="display: none;">
<label>
Comments
<input type="text" name="TextComment" id="TextComment" placeholder="Type Comments" autocomplete="off" tabindex="1" />
</label>
</li>
<li id="C1" class="divComment" style="display: none;">
<label>
Charges
<select id="Charges" name="Charges" >
<option value="nc">test</option>
</select>
</label>
</li>
</ul>
</li>
</ul>
<ul data-role="listview" data-style="inset" data-type="group">
<li>Picture
<ul>
<li>
<label>
Select a Photo
<input type="file" id="kitFile" style="display: none;" />
<a data-role="button" data-click="select" style="float: right;">Select</a>
</label>
</li>
</ul>
</li>
</ul>
</div>
//Submit button
<a data-align="right" data-role="button" class="nav-button" data-click="submit_form">Save</a>
Here $(this) will give u only the button element. The easy way to do this is use the built in MVVM feature in Kendo UI Mobile. create an model as JS object and set data-model attribute of your view as this object. Now on click of the submit button, just send this object to your server using ajax. This way u are reducing the amount of data sent to the server.
Documentation on mobile and mVVM integration: http://docs.kendoui.com/getting-started/mobile/mvvm .
I have used a PageMethod previously.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Would something like this help your cause?
Let's take an example of such a method in the code behind:
[WebMethod]
public static string MyMethod(string Id)
{
return string.Format("Thanks for calling me with id: " + Id);
}
Things to note: the method must be static and decorated with the [WebMethod] attribute.
And on the client side you could invoke this method using the jQuery.ajax() function like this:
$.ajax({
url: 'default.aspx/MyMethod',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ID : ID }),
success: function (result) {
alert(result.d);
}
});
Make sure that in your WebForm you have actually added reference to the jQuery library before using it.
For example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>

POST method with AJAXOption in MVC3 call GET request

I am confused with AjaxOption in MVC3 , i would like to make post request but it's always make get request and redirects to new url.
my .cshtml code as per below
<div >
#Html.ActionLink("Check Availability", "ValidateUsername", "Wizard", new { username = "arun"},
new AjaxOptions()
{
Url="/Wizard/ValidateUserName",
UpdateTargetId = "msg",
HttpMethod = "POST",
LoadingElementId = "progress"
})
</div>
<div id="progress">
<img alt="" src="../../Content/Images/progress.gif" width="20px" height="20px" style="display: none" />
</div>
<div id="msg">
</div>
and controller action as per below
public ActionResult ValidateUsername(string username)
{
Thread.Sleep(200);
//return Json(!username.ToLower().Equals("arun"));
return Json(true , JsonRequestBehavior.AllowGet);
}
it's always make get request instead of POST request and redirect to new URL http://localhost:55152/Wizard/ValidateUsername?username=arun , why?
and HTML code generated as per below
<div >
<a Confirm="" HttpMethod="POST" InsertionMode="Replace" LoadingElementDuration="0" LoadingElementId="progress" OnBegin="" OnComplete="" OnFailure="" OnSuccess="" UpdateTargetId="msg" Url="/Wizard/ValidateUserName" href="/Wizard/ValidateUsername?username=arun">Check Availability</a>
</div>
<div id="progress">
<img alt="" src="../../Content/Images/progress.gif" width="20px" height="20px" style="display: none" />
</div>
<div id="msg">
</div>
You need to use #Ajax.ActionLink instead of #Html.ActionLink to post data by ajax
Anchor tags in HTML always does a get request. You should either use Jquery post.
See here for more details

How to trigger Ajax with flash buttons?

I'm working on something where there are 2 links which triggers some Ajax. However I need to turn the links into Flash buttons (AS3). I've never worked with Ajax before, and I have no idea how this can be done.
Edit:
The Ajax:
<script>
$(document).ready(function() {
$('a.catlink').unbind('click').click(function(e)
{
e.preventDefault();
var link = $(this);
var inputs = [];
var cat_type = $(this).attr('href').replace('#', '');
link.attr('disabled', 'disabled');
inputs.push('cat_type=' + escape(cat_type));
$.ajax(
{
type: "POST",
cache: false,
dataType: "html",
url: window.location.href,
data: inputs.join('&'),
success: function(html)
{
var json = $.parseJSON(html);
if (json['status'] == 1)
{
$('div.listing').html(json['html']);
}
link.removeAttr('disabled');
}
});
});
});
</script>
The HTML
<h1 class="section-head">Products
// **The 2 links*** //
<a class="catlink" href="#cinema">cinema</a> <a class="catlink" href="#smart">smart</a></h1>
<div class="listing">
<ul class="listing">
{foreach from=$products item="product_info"}
<li class="clearfix">
<div class="inner-left">
<img height="68" width="90" src="{$product_info.image}" />
<h2 class="normal mt-5">{if $product_info.price != '0'}${$product_info.price}{else}Click for price ยป{/if}</h2>
</div>
<div class="inner-right">
<h3 class="mb-0">{$product_info.productName}</h3>
<p class="small mb-5"><span class="quiet">{$product_info.category}</span></p>
<p class="mb-15">{$product_info.description}</p>
<a class="button getprice" href="{$product_info.url}">Buy Now</a>
<br><br>
</div>
</li>
{/foreach}
</ul>
</div>
If you're going to use AS3 then you can use ExternalInterface.call() to call a JavaScript function on the page. Though, using Ajax may not be required if you're using AS3 because you can make use of the URLLoader class to do the same thing (call a PHP script and decode a result).
If you describe more accurately what you want to achieve then I shall provide some example code and clarify a little more.

Resources