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>
Related
i wrote some code to view my all showing events details using bootstrap modal popup when click read more button. but when i click read more button every response repeats same id.
this is my laravel code
#if(!empty($event))
#foreach($event as $value)
<!-- Single Blog Post -->
<div class="single-blog-post d-flex" id="event_tag">
<div class="post-thumbnail">
<img src="{{asset('images/'.$value->image)}}" alt="">
</div>
<div class="post-content">
<a class="post-title">
#if(strlen($value->title) <= 35)
{{$value->title}}
#else
{{substr($value->title, 0, 35) . '...'}}
#endif
</a>
<div class="post-meta d-flex justify-content-between">
<center><button id="event_button" class="post-cata cata-sm cata-success text_white" data-toggle="modal" data-target="#myModal">Read More</button></center>
</div>
</div>
<input type="hidden" name="event_id" id="event_id" value="{{$value->id}}"></div>
#endforeach
#endif
and this is javascript code to get id and show every id detail.
<script>
$(document).on("click", "#event_button", function() {
var id = $("event_id").val();
console.log(id);
$.ajax({
url: "/event/" + id + "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
})
</script>
every time repeats id no 2 when click each event read more button. how can i fix this?
Your code has some mistakes in html too. For example, has fixes ids in html.
'event_id'
'event_button'...
Try this...
<button id="event_button-{!! $value->id !!}" data-target="event_id-{!! $value->id !!}"
<input type="hidden" name="event_id" id="event_id-{!! $value->id !!}"
The code above will fixed the id issue.
Now let's to the JS code... Change the click event:
$(document).on("click", "button.post-cata", function() {
var id = $("#" . $(this).data("target").val();
...
Do you need to associate tags to work with the right value. Avoid to put fixes ids inside a php loop. The html id element must be unique in document.
So, has many ways to do this. In this case, the input hidden fild is not necessary. you can put the id in a attribute in the button tag too.
<button data-id="{!! $value->id !!}...
So in the jquery click event do:
var id = $(this).data('id');
It's more ease and clean.
give class name to button and add attribute to button
<button class="event_button post-cata cata-sm cata-success text_white" data-eventid="{{$value->id}}">Read More</button>
so no need to use hidden input id
now using jQuery :
$(document).on('click','.event_button',function(){
var event_id = $(this).attr("data-eventid");
$("#myModal").modal("show");
$.ajax({
url: "/event/" + event_id+ "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
});
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.
i'm dealing with this ajax call:
HTML:
A form has a textarea in which user can type some text
<div id="step-3">
<h2 class="StepTitle">Testo</h2>
<form id="text" class="form-horizontal form-label-left">
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Textarea <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea id="textarea" name="testo" data-parsley-required="true" class="form-control col-md-7 col-xs-12"></textarea>
</div>
</div>
</form>
<ul id="error3_ul" class="list-unstyled">
<li id="error3_li"></li>
</ul>
</div>
JS:
This function is called by smartwizard. When user types some text and pushes button, an ajax call starts to do a server side check before to effectively insert text into db.
function onFinishCallback()
{
var data = $('#textarea').val();
$.ajax({
method: 'post',
data: data,
dataType: 'html',
url: "include/library/pull_sim.php",
success: function(result) {
successmessage = 'Data was succesfully captured';
$("#error3_li").text(result);
},
});
}
PHP:
Php receives the posted textarea value, check if a similar_text is already into db and if yes, it alerts that to user by the ajax call result.
if((!ISSET($_POST['testo'])))
$val='';
else
$val=$_POST['testo'];
$q_sim='select nciarfata from nciarf.nciarfata';
$s_sim=mysqli_query($conn,$q_sim);
$n_sim=mysqli_num_rows($s_sim);
if ($n_sim>0)
{
$simil=array();
for ($i=0;$i<$n_sim;$i++)
{
$rou=mysqli_fetch_row($s_sim);
similar_text($val, $rou[0], $percent);
if ($percent>=95.0)
{
array_push($simil,$rou[0]);
}
}
echo"val=$val, rou[0]=$rou[0], percent=$percent";
}
Question:
In my opinion something goes wrong in server side, probably in the 1st if.
Php doesnt recognized the posted value and then assign val="" instead of real text typed by user before..
Why?
Thanks for helping me.
I find the solution here:
Can't figure out why PHP not receiving POST data from $.ajax call
It wasn't a textarea issue but an ajax jquery one (data option).
I have a statistical panel which displays the last registered users. I want to implement a AJAX call to upload the panel without having to reload the full page.
I have the following code in my view:
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
<div class="mt-comment">
<div class="mt-comment-img">
<g:if test="${user?.avatar}">
<img src="${createLink(controller:'controllerUser',
action:'image', id: user?.id)}" />
</g:if>
<g:else>
<img class="img-circle"
src="${resource(dir: 'img/profile', file: 'user_profile.png')}"/>
</g:else>
</div>
<div class="mt-comment-body">
<div class="mt-comment-info">
<span class="mt-comment-author">${user?.username}</span>
<span class="mt-comment-date">
<g:formatDate date="${user?.dateCreated}"/>
</span>
</div>
<div class="mt-comment-text">${user?.email}</div>
<div class="mt-comment-details">
<g:if test="${user?.enabled}">
<span class="mt-comment-status label label-sm label-success circle">
</g:if>
<g:else>
<span class="mt-comment-status label label-sm label-info circle">
</g:else>
<g:formatBoolean boolean="${user?.enabled}"/>
</span>
<ul class="mt-comment-actions">
<li>
<g:link controller="user" action="edit" id="${user?.id}">Edit</g:link>
</li>
</ul>
</div>
</div>
</div>
</div>
</g:each>
Also, I have a button when it is clicked calls the AJAX function. The Ajax function receives the data successful in JSON format. From there, I don't know upload my g:each tag.
I have tried the remoteFunction of Grails to use the upload attribute, but an error appears: No javascript provider is configured and I have searched the solution but anything works me.
The AJAX call:
$('.button').click(function() {
$.ajax({
url: URL,
success: function(data) {
console.log(data[index]);
console.log(val.username);
console.log(val.dateCreated);
console.log(val.email);
console.log(val.enabled);
console.log(val.avatar);
console.log(val.id);
},
error: function(){
},
});
Thanks for helping me.
Instead of Using JSON Data, You can do this using grails templates and jQuery load method. Here is a quick POC.
Template (_userComments.gsp)
This will act as a reusable view which can be called via AJAX or can be included directly in other views.
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
.....
</div>
</g:each>
View (main.gsp)
Our Main View.
<div class="userComments">
<!-- When the Page is Loaded, We need render this without an Ajax Call -->
<g:render template="userComments" model="['lastUsers':lastUsers]"/>
</div>
Javascript
$('.button').click(function() {
$( ".userComments" ).load( "user/userComments" );
});
Controller
We are defining two methods one for the main view and one for the ajax call.
def index() {
def lastUsers = User.list();
render(view:'main', model: [lastUsers: lastUsers])
}
// Ajax Call
def userComments() {
def lastUsers = User.list(); // what ever your fetch logic is
render(template:'userComments', model: [lastUsers: lastUsers])
}
I have a controller(SearchController) which fetches data on clicking a search button (inside myview.gsp) i want to populate 2 text fields present in the same myview.gsp with the data i have in my controller (SearchController) .I know i need to do ajax calling because i want to populate only 2 fields and dont want to reload the page which contains other valuable information . How can i achieve it please guide me
here is my Controller
def searchItem() {
def itemFound = MyService.searchP20Code(params["item"])
def resultMap = [:]
if (itemFound!=null)
{
resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])
}
println "Result:"+resultMap
session.setAttribute("searchResult", resultMap)
render(view: myview" )
}
myview.gsp
myview.gsp
<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Code" />
</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Code" maxlength="30"
value=""
id="i_code" />
</div>
</div>
<div class="formLables">
<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Description" />
</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Desc" maxlength="30"
onkeyup="fieldMaxlength('material_code')" value=""
id="i_description" />
</div>
</div>
<g:actionSubmit
value="${message(code:'Normal.button.search', default: 'Search Code')}"
action="searchItem" />
please help my how can i update only these two text fields in myview.gsp onclicking search button using ajax .I am using grails 2.1.0
Here you can find a detailed example with Grails build-in Ajax support.
You can also use JQuery (example here)
EDIT:
Your controller needs to look like this:
import grails.converters.JSON
class ExampleController {
....
def searchItem() {
def itemFound = MyService.searchP20Code(params["item"])
def resultMap = [:]
if (itemFound!=null) {
resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])
}
println "Result:"+resultMap
//session.setAttribute("searchResult", resultMap)
render(resultMap as JSON )
}
}
and your gsp
<head>
...
<g:javascript plugin="jquery" library="jquery" src="jquery/jquery-{WRITE_YOUR_VERSION_HERE}.js"/>
<script>
function callAjax(e){
e.preventDefault();
$.ajax({
url: "example/search",
type:"post",
dataType: 'json',
success: function(data) {
console.log(data);
$("input[name='Code']").val(data.CODE);
$("input[name='Desc']").val(data.DESC);
}
});
}
</script>
...
</head>
<body>
....
<input type="submit" value="Call Ajax Function" onclick="callAjax()">
....
</body>