Pass button ID to the controller in AJAX calls - javascript

In my webpage I have different cities to select using buttons and i want to retrieve my data from my model based on the button ID. Since i have 400+ records for each city.
If I click on my button looks like it is not activating my controller method because my ajax call is not happening
my HTML code looks like this:
<table>
<tr>
<td id="A"><input value="A"type="button" id="btn_a" onclick="getValues(this)"/>
</td>
</tr>
<tr>
<td id="B"><input value="B"id="btn_b" type="button" onclick="getValues(this)"/>
</td>
</tr>
</table>
myController method
public JsonResult updateValues(string site)
{
list<string> dataList = new list<string>;
Model m = new Model();
dataList = m.myData(site);
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(dataList );
return Json(dataList , JsonRequestBehavior.AllowGet);
}
my Ajax call.
<script type="text/javascript">
function getValues(siteID) {
var id = siteID.id,
var data = id.value,
$.ajax({
type: "GET",
url: '#Url.Action("updateValues")',// the method we are calling
cache: false,
contentType: "application/json; charset=utf-8",
data: {"data": data},
dataType: "json",
success: function (data) {
for (var k = 0; k < 630; k++) {
document.getElementById(k).innerHTML = data[k];
}
}
});
}
</script>

Related

How do I save List of Checkboxes with value as Id to a database?

I have lists of courses from different table displaying on the same view as shown below
I want a user to select the courses he wants to register by selecting the checkboxes.
How do I get the Id's of the courses selected, then pass to the controller to save to another table.
I have my HTML code as this
#model FlexSchool.Data.Models.ClassModelIndex
<tbody>
#foreach (var item in Model.AdmInstAssignCourses.Where(m => m.IsCompulsory == true))
{
<tr>
<td>
<input type="checkbox" class="checkBox" name="check" value="#item.AdmInstCourses.CourseId" />
</td>
<td> #Html.DisplayFor(modelItem => item.AdmInstCourses.CourseCode) </td>
<td> #Html.DisplayFor(modelItem => item.AdmInstCourses.CourseName)</td>
<td> #Html.DisplayFor(modelItem => item.AdmInstCourses.Units)</td>
</tr>
}
</tbody>
Where ClassModelIndex is a class of IEnumerable Classes which i used in displaying different tables to list.
My button goes thus <input type="submit" value="Register Courses" id="register" class="btn btn-rose" />
My script looks like this
<script>
$(document).ready(function () {
$("#register").click(function () {
var selectedIDs = [];
$('input[type=checkbox]').each(function () {
selectedIDs.push($(this).val());
});
$.ajax({
url = "/Course/RegisterCourse",
type = "POST",
data = JSON.stringify({ courseIDs: selectedIDs }),
contentType = "application/json; charset=utf-8",
dataType = "json",
success = function (data) {
alert(data);
},
error = function () {
alert("Error while registering courses!");
},
});
});
</script>
My Controller is
[HttpPost]
public async Task<ActionResult> RegisterCourse(List<string> courseIDs)
{
var user = HttpContext.Session.GetString(InstName);
if (user == null)
{
return RedirectToAction("Login", "Account");
}
foreach (string courseID in courseIDs)
{
AdmInstCourses obj = await _context.AdmInstCourses.FindAsync(courseID);
var mycourses = new CourseRegModel { CourseCode = obj.CourseCode, CourseTitle = obj.CourseName, CourseUnit = obj.Units};
_context.Add(mycourses);
}
await _context.SaveChangesAsync();
return RedirectToAction("MyCourses", "Course");
}
But when I run the code in debugging mode, I notice my courseIDs is not getting any list of string as Id. So it is either the script is not getting the checked boxes to pass to the controller.
What exactly am I doing wrong?
The issue is with the JavaScript Code. You have missed :checked.Use following code to get all checked values. And make sure no space between input[type="checkbox"] and :checked.
var selectedIDs = [];
$('input[type="checkbox"]:checked').each(function () {
// looping through each checkbox and storing values in array for checked ones.
selectedIDs .push($(this).val());
});
Please try below Ajax code :
var selectedIDs = [];
$('input[type=checkbox]').each(function () {
selectedIDs.push($(this).val());
});
$.ajax({
url : '/Course/RegisterCourse',
type : "POST",
data: JSON.stringify(selectedIDs),
contentType : "application/json; charset=utf-8",
dataType : "json",
success : function (data) {
alert(data);
},
error : function () {
alert("Error while registering courses!");
}
});
Directly pass json string(JSON.stringify(selectedIDs)) to server side , and in the controller method, use [FromBody] to get the values :
[HttpPost]
public async Task<ActionResult> RegisterCourse([FromBody]List<string> courseIDs)
{
}
First and foremost you can't put ids in checkbox value, because the value of checkbox can has true or false.
Try to use html.HiddenFieldFor(model => model.YourModel[i]) and replace foreach by for.

Unable to retrieve data from html

As for my below code i am not able to get sectionID from tr, i need to get dynamic id of sectionID on each delete button click but it is always giving me null
Here is the Jquery Script :
<script>
$(function () {
$('.btnDelete').click(function () {
var sectionID = $(this).closest('tr').find('.sectionID');
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'CheckSectionIDagainststudentID',
data: JSON.stringify({ sectionID: sectionID.html() }),
success: function (data) {
if (data == true) {
$.alert("Cannot delete | Students exsisting in this
Section!");
}
else if (data == false) {
var secCode = JSON.parse(this.data);
var code = sectionid['sectionid'];
window.location.href = "SectionDelete?Page=data&sectionid="
+ code;
}
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
and here is Razor Page
#foreach (var item in Model)
{
<tr class="sectionID">
<td >
#Html.DisplayFor(modelItem => item.sectionID)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td class="secCode">
<button style="width:49.5%" ID="Button2" type="button" onclick="location.href='#Url.Action("SectionEdit", "Section",new { id = item.sectionID, name = item.name })'">Edit</button>
<button style="width:49.5%" ID="deletebtn" runat="server" type="button" onclick="location.href='#Url.Action("SectionDelete", "Section",new { id = item.sectionID, name = item.name })'">Delete</button>
<button class="btnDelete">Delete</button>
</td>
</tr>
}
This is Controller Which i need to pass data to
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string sectionID)
{
return Json(sectionID);
}
As per your question you are not able to get value from var sectionID = $(this).closest('tr').find('.sectionID');
therefore here is a way you can achieve your result
//Your Dynamic Button should look like this
//in value Bind your sectionID # MVC
<button class="btnDelete" value="5" onclick="AjaxDelete(this)">Delete</button>
//For Function
function AjaxDelete(values) {
//Write this in Ajax
//Fetch Value from attribute value
var sectionID = $(values).attr("value"); // you will get 5 as value
//Your Ajax Call with SectionId as Parameter
}
Edit :
as you have got value
U can split the value by below code
where string is your var of sectionID
if ((~string.indexOf('\n '))) {
string= string.split('\n ')[1].split('\n')[0];
}
Use string array :
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string[] sectionID)
{
return Json(sectionID);
}

How to pass Array to MVC Controller with Jquery?

I am beginner to develope .Net MVC 5 application. But I have some problem with passing array or object to controller with Jquery.
I'm adding dynamically input fields with button. I want to pass input's data to controller. But I couldn't succeed.
Html Section is like that;
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1'>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
Get Value button function is like that;
$("#getButtonValue").click(function () {
var list = new Array();
for (i = 1; i < counter; i++) {
list[i] = $('#textbox' + i).val();
alert(list[i]);
}
var postData = { values: list };
$.ajax({
type: "POST",
url: "/Surveys/PostQuestionAndOptions",
data: postData,
success: function (data) {
alert(data);
},
dataType: "json",
traditional: true
});
});
Even I set "traditional" by true , the model is null.
[HttpPost]
public JsonResult PostQuestionAndOptions(string[] model)
{
return Json(true);
}
Could any one help me ? Thank you.
You need to have a strongly typed object.
JavaScript
$("#getButtonValue").click(function (e) {
e.preventDefault();
var list = [];
for (var i = 1; i < counter; i++) {
list.push($('#textbox' + i).val());
}
var postData = { values: list };
$.ajax({
type: "POST",
url: "/Surveys/PostQuestionAndOptions",
data: postData,
success: function (data) {
alert(data);
},
dataType: "json",
traditional: true
});
});
Strongly typed object
public MyValues {
public list<string> values {get; set;}
}
Controller method
[HttpPost]
public JsonResult PostQuestionAndOptions(MyValues model) {
return Json(true, JsonRequestBehavior.AllowGet);
}

populating data to html table using ajax, jquery and making it searchable

I'm loading data dynamically to html table as below. I'm using Datatable for ssearch.
Technology stack used is:
Spring MVC
Hibernate
Ajax
JQuery
function getdata()
{
$.ajax({
type: "GET",
url: "/controllerURL.html", //controller URL
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
console.log(results)
var success = results.success;
if(success){
var finaldata = "<tbody><thead><tr><th>ID</th><th>data1</th><th>data2</th><th>Update</th></tr></thead>"; //data
var data = results.message;
data = jQuery.parseJSON(data);
alert(data);
for(var i = 0; i < data.length; i++){
var value = data[i];
finaldata = finaldata+ "<tr><th>"+value.ID+"</th><th>"+value.variable1+"</th><th>"+value.variable2+"</th></tr>";
}
finaldata = finaldata + "</tbody>";
$("#tableID").html(finaldata);
}
},
error: function (data) {
alert("fail");
console.log('ajax call error');
}
});
}
I'm now be able to load data into table. but can someone explain how to add search option to it.
You can use datatables click here
It will provide you various inbuilt functionality that you may want to integrate
<!--dependencies for data table -->
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js" type="text/javascript"></script>
Your html should look like this
<table id="stable" class="display table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Data1</th>
<th>Data2</th>
<th>Data3</th>
<th>Data4</th>
</tr>
</thead>
finally write this script
$(document).ready(function () {
$('#table').DataTable();
});

How to get the data from ajax in controller codeigniter

I have an editable table in my view.. At first, there's no data in the table but the user can add data in the table since it is editable. And there's no exact number of rows in the table since I have also a button that can add new row. I want to get the data that the user have added and save it in the database.
I have this code:
VIEW:
<table class="table " id="memberTB">
<thead><tr><th >First Name</th><th >Middle Name</th><th>Last Name</th></tr></thead>
<tbody>
<tr id="first"><td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td></tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow"><span class="fa fa-plus"> Add new row</span></button>
</table>
<br><button type="button" class="btn" id="savebtn">Save</button> Reset
JS:
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.showbuttons = false;
$.fn.editable.defaults.url = '/post';
$.fn.editable.defaults.type = 'text';
// make all items having class 'edit' editable
$('.edit').editable();
// this is to automatically make the next item in the table editable
$('.edit').on('save', function(e, params){
var that = this;
// persist the old value in the element to be restored when clicking reset
var oldItemValue = $(that)[0].innerHTML;
if (!$(that).attr('oldValue')) {
console.log('persisting original value: ' + oldItemValue)
$(that).attr('oldValue', oldItemValue);
}
setTimeout(function() {
// first search the row
var item = $(that).closest('td').next().find('.edit');
console.log(item);
if (item.length == 0) {
// check the next row
item = $(that).closest('tr').next().find('.edit');
}
item.editable('show');
}, 200);
});
$('#resetbtn').click(function() {
$('.edit').each(function() {
var o = $(this);
o.editable('setValue', o.attr('oldValue')) //clear values
.editable('option', 'pk', o.attr('pk')) //clear pk
.removeClass('editable-unsaved')
.removeAttr('oldValue');
});
});
$('#savebtn').click(function() {
var person = [];
var x=1;
$('tbody tr',$('#memberTB')).each(function(){
for(var i = 0 ; i < cells ; i++)
{
person[x][i]=$(this).find('td').eq(i).text();
}
x++;
});
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: { values: arraylng },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
});
$('#addrow').click(function() {
$('#memberTB > tbody:last').append(' <tr><td><span class="edit"></span></td><td><span class="edit"></span></td><td><span class="edit"></span></td></tr>');
$('.edit').editable();
});
Controller: [inside the test.php]
public function saveData(){
$this->load->model('test_model');
$myArray = $_REQUEST['values'];
echo sizeof($myArray);
}
Whenever I click the save button, there's no response at all.. Where did I go wrong? please help me..
ADDED INFO:
I didn't include my SQL insert statement here because I want to test first if there's data in $myArray if I added data in the table.
Better use this ajax
var arraylng = [3,4,7];
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: {values: JSON.stringify(arraylng)},
cache: false,
success: function (response) {
alert(response);
}
});
arraylng is an array, which doesn't exist in the code. I added it here for debugging.
Suppose you want to send person[] array, you write, data: {values: JSON.stringify(person)}.
Now, the person array may not exist, because of the "i < cells" in for. What is cells?
The word response is just a name, any name, but better avoid 'data'.
In test.php, what is sizeof($myArray)? Just, echo $myArray;
When you click save you must get the $myArray content in an alert.

Categories

Resources