Fetching name based on id in ajax - ajax

In the console,I am getting name based on id.How to bind that name into the html page.
Here is my code..
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok" + clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok" + data);
(what to do to bind the name in the html page)
}
});
}
Now the HTML is;
<td class="bg1">
Event Id :
</td>
<td class="bg1" width="25%">
<input name="eventid" type="text" id="eventid" size="10" maxlength="10" onblur="getEventname()"/>
</td>
<td class="bg1" width="40%">
Event Name :
</td>
<td class="bg1" width="25%">
<input type="text" name="eventname" id="eventname">
</td>
In the console,I am getting name as i am ok seminar .How to bind that name in the HTML page automatically when id is given.
Can anyone help?

So your Javascript function should be;
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok"+clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok"+data);
//The one line change
$("#eventname").val(data);
}
});
}

So you had already implemented everything. All you need to do is add data in some element. If you want to add it in td then use this:
$.ajax({type: "GET",url: "EduManage.jsp",data: {control:'ajax', ch:'1', key:'1_0a1m_1', eventid:clid},
success: function(data) {
console.log("i am ok"+data);
$("td.last").append(data);
(what to do to bind the name in the hmtl page)
}
});
and add a new html tag:
<td class="last"></td>
You can also update the html using jquery but its not a practice to do so.
Hope this works.

Related

getting data to array in knockout JS

I am trying to get data to knockout from the database using Ajax. But I am not getting any data to my observableArray.
Here is the knockout js model:
self.alldata = ko.observableArray();
self.viewAllInvoice = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/moneyexchange/learn_Ko/',
contentType: 'application/json; charset=utf-8'
})
.done(function(invoices) {
invoices.forEach(function(invoice) {
self.alldata.push(invoice);
});
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.viewAllInvoice();
And here is the html code I am trying to put my data in
<tbody data-bind="foreach: alldata">
<tr>
<td class="text-center"><span data-bind="text: $data.payment_amount "></span></td>
<td class="text-center"><span data-bind="text: $data.allocated_amount"></span></td>
</tr>
</tbody>
I did not create a viewmodel showing all the data from the database since I know what I need to show in the table. And for extra information, I am getting the data from a controller in codeigniter framework. Please do guide me in steps since I am totally new in all this.

Best Way for Getting Value from a Clicked Checkbox, with JQuery

All,
Is this the best way to get the value of a currently-checked/unchecked checkbox?
The number of checkboxes is arbitrary so I need a way to get the value of the checkbox that was checked or unchecked.
By looking at Firebug, I see that by using:
this.defaultValue
I can get the value of the currently-checked/unchecked checkbox but not sure if that's really the best way.
Here is the HTML and below is the Javascript click handler
<div id="ClubSponsorshipPartial">
<table class="table-grid">
<tr>
<td>
<input type="checkbox" value="000000244187" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #1
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #2
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #3
</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#ClubSponsorshipPartial input[type=checkbox]").click(function (e) {
var queryStr = '';
var clubKeyNumber = '';
var receivedBackgroundCheckChecked = false;
var memberId = this.defaultValue
clubKeyNumber = 'K06253';
receivedBackgroundCheckChecked = ($("#ClubSponsorshipPartial input[type=checkbox]").is(":checked") ? "true" : "false");
queryStr = "memberId=" + memberId + "&isChecked=" + receivedBackgroundCheckChecked;
$.ajax({
type: "POST",
url: '/Dashboard/BackgroundCheck',
data: queryStr,
datatype: 'json',
success: function (data) {
$.notification({
content: 'SLP Advisor Background Check status saved.',
error: false,
timeout: 5000
});
},
failure: function (data) {
$.notification({
content: 'Error saving SLP Advisor Background Check status.',
error: true,
timeout: 5000
});
},
timeout: 5000
});
});
});
</script>
the id should be unique in your page document, and you should use $(this) to mapping current DOM, you can try below code, may help;
http://jsfiddle.net/kJQr9/

update div with jquery on ajax call without refreshing the page

can anyone help please. I have a problem updating "div" inside of "table" to update "tr with_id". However when I run test and
place without_"id" outside of table my script runs greate and i'm getting server "TEST" response
<table style="border: none; border-bottom: 1px solid #2F2E2F;">
<tr>
<th colspan="4">Notifications</th>
</tr>
<div id="update_118">
<tr class="read_118">
</div>
<td>... </td>
<td> Comment on your Photo </td>
<td>today 21:43</td>
<td>... </td>
</tr>
</table>
Now I want to up update this "div" when mouseover on success: function() without page refreshing to have its value change to class="light" to have NOT TO CALL ajax url: "/alerts/ajax_read/118" over and over while mouse is over on it.
<div id="update_118">
<tr class="light">
</div>
here is my script,...
<script>
$(document).ready(function(){
$('.read_118').on('mouseover', function(){
var id = $(this).attr("id")
var data = 'id=' + id ;
$.ajax({
type: "GET",
url: "/alerts/ajax_read/118",
data: data,
cache: false,
success: function(){
$('#update_118').fadeOut('slow').load('/alerts/ajax_load/118').fadeIn("slow");
return false;
}
});
});
});
</script>
here is my server response file:
$response = " <tr class='light'> ";
echo $response;
thanks in advance,...
chris
Update following line
success: function(){
To
success: function(data){
and set the "data" variable value to your respective "div" or other place where you want.

ASP.NET MVC3: Ajax postback doesnot post complete data from the view

Hi Greetings for the day!
(1) The view model (MyViewModel.cs) which is bound to the view is as below...
public class MyViewModel
{
public int ParentId { get; set; } //property1
List<Item> ItemList {get; set;} //property2
public MyViewModel() //Constructor
{
ItemList=new List<Item>(); //creating an empty list of items
}
}
(2) I am calling an action method through ajax postback (from MyView.cshtml view) as below..
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {$('#MyForm').html(html);}
});
}
The below button click will call the ajax postback...
<input type="button" value="Add" class="Previousbtn" onclick="AddItem()" />
(3) I have an action method in the (MyController.cs controller) as below...
public ActionResult AddItem(MyViewModel ViewModel)
{
ViewModel.ItemList.Add(new Item());
return View("MyView", ViewModel);
}
Now the issue is, after returning from the action, there is no data in the viewmodel. But i am able to get the data on third postback !! Can you pls suggest the solution..
The complete form code in the view is below...
#model MyViewModel
<script type="text/javascript" language="javascript">
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function RemoveItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/RemoveItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function SaveItems() {
var form = $('#MyForm');
var serializedform = forModel.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/SaveItems")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
</script>
#using (Html.BeginForm("SaveItems", "MyController", FormMethod.Post, new { id = "MyForm" }))
{
#Html.HiddenFor(m => Model.ParentId)
<div>
<input type="button" value="Save" onclick="SaveItems()" />
</div>
<div>
<table>
<tr>
<td style="width: 48%;">
<div style="height: 500px; width: 100%; overflow: auto">
<table>
<thead>
<tr>
<th style="width: 80%;">
Item
</th>
<th style="width: 10%">
Select
</th>
</tr>
</thead>
#for (int i = 0; i < Model.ItemList.Count; i++)
{
#Html.HiddenFor(m => Model.ItemList[i].ItemId)
#Html.HiddenFor(m => Model.ItemList[i].ItemName)
<tr>
#if (Model.ItemList[i].ItemId > 0)
{
<td style="width: 80%; background-color:gray;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%; background-color:gray;">
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
#Html.HiddenFor(m => Model.ItemList[i].IsSelected)
</td>
}
else
{
<td style="width: 80%;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%">
#if ((Model.ItemList[i].IsSelected != null) && (Model.ItemList[i].IsSelected != false))
{
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
}
else
{
#Html.CheckBoxFor(m => Model.ItemList[i].IsSelected, new { #style = "cursor:pointer" })
}
</td>
}
</tr>
}
</table>
</div>
</td>
<td style="width: 4%; vertical-align: middle">
<input type="button" value="Add" onclick="AddItem()" />
<input type="button" value="Remove" onclick="RemoveItem()" />
</td>
</tr>
</table>
</div>
}
You must return PartialViewResult and then you can do something like
$.post('/controller/GetMyPartial',function(html){
$('elem').html(html);});
[HttpPost]
public PartialViewResult GetMyPartial(string id
{
return PartialView('view.cshtml',Model);
}
In my project i get state data with country id using json like this
in my view
<script type="text/javascript">
function cascadingdropdown() {
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
alert(data);
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
in my controller return data in json format
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
i think this will help you ....
I resolved the issue as below...
Issue:
The form code i have shown here is actually part of another view page
which also contains a form. So, when i saw the page source at
run-time, there are two form tags: one inside the other, and the
browser has ignored the inner form tag.
Solution:
In the parent view page, earlier i had used Html.Partial to render
this view by passing the model to it.
#using(Html.BeginForm())
{
---
---
#Html.Partial('/MyArea/Views/MyView',MyViewModel)
---
---
}
But now, i added a div with no content. On click of a button, i'm
calling an action method (through ajax postback) which then renders
the above shown view page (MyView.cshmtl) into this empty div.
#using(Html.BeginForm())
{
---
---
<div id="divMyView" style="display:none"></div>
---
---
}
That action returns a separate view which is loaded into the above
div. Since it is a separate view with its own form tag, i'm able to
send and receive data on each postback.
Thank you all for your suggestions on this :)

Passing Id from javascript to Controller in mvc3

How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '#Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller
instead of
$.post(url,data, function (result) {
// });
My View
#using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { #id = "myAjaxForm" }))
{
<table id="tblclick">
#for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='#Model.names[i].Id'>
#Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { #id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
I would avoid using the Ajax Beginform helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
#foreach(var name in Model.names)
{
<tr>
<td id="#name.Id">
#Html.ActionLink(name.Name,"listpage","yourControllerName",
new { #id = name.Id },new { #class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load function to load the response from thae listpage action method to the div with id showPage.
Assuming your listpage action method accepts an id parameter and returns something
I am not sure for $.post but I know window.location works great for me.
Use this instead and hopefully you have good results :)
window.location = "#(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Just use a text box helper with html attribute ID.
#Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});

Resources