Jquery keyup function doesn't work (using ajax, asp.net mvc) - javascript

I'm trying to build search filter with .keyup function. When i write one char in search textbox its works fine, but when i try to delete char, or add one more then it crushes and throws error "Internal server error". What im i doing wrong? I tried to parse given/taken data to json/html and it didn't help. Here is my script code:
<script>
$(document).ready(function () {
$("#Search").keyup(function () {
var searchby = $("#searchby").val();
var searchVal = $("#Search").val();
var setData = $("#dataSearching");
var catId = $("#categoryID").val();
setData.html("");
$.ajax({
async: true,
type: "get",
url: "/Default/GetSearchingData?categoryID=" + catId + "&searchBy=" + searchby + "&searchValue=" + searchVal,
dataType: "json",
contentType: "html",
success: function (result) {
if (result.length == 0) {
setData.append('<tr><td colspan="7" style="color: red;">Nie odnaleziono szukanej frazy</td></tr>');
} else {
for (var i in result) {
var Data = "<tr>" +
"<td>" + result[i].AlbumID + "</td>" +
"<td>" + result[i].AlbumName + "</td>" +
"<td>" + result[i].BandName + "</td>" +
"<td>" + result[i].AlbumCover + "</td>" +
"<td>" + result[i].Year + "</td>" +
"<td>" + parseFloat(result[i].Price) + "</td>" +
"<td>" +
"<button id=" + result[i].AlbumID + ' type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-' + result[i].AlbumID + '">' +
"Zobacz </button>" +
'<div class="modal fade" id="exampleModal-' + result[i].AlbumID + '" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-' + result[i].AlbumID + '" aria-hidden="true">' +
'<div class="modal-dialog" role="document">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<h5 class="modal-title" id="exampleModalLabel-' + result[i].AlbumID + '">' + result[i].AlbumName + ", " + result[i].Year + ", " + result[i].BandName + "</h5>" +
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
'<span aria-hidden="true">×</span> </button> </div>' +
'<div id="parent-' + result[i].AlbumID + '" class="modal-body">' +
"</div>" +
'<div class="modal-footer">' +
'<button id="closeModal" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</td>" +
"<td>"+
'<input id="categoryID" class="hidden" type="submit" value="' + result[i].CategoryID + "/>" +
"</td>"+
"</tr>";
setData.append(Data);
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.responseText);
alert("Error!!: " + thrownError);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
return xhr;
}
});
});
});
</script>
And here is my action for searching in DefaultController:
public JsonResult GetSearchingData(int categoryID, string searchBy, string searchValue)
{
var albumsWithCategory = (from album in Album.GetAlbumList()
join category in Category.GetCategoriesList()
on album.CategoryID equals category.CategoryID
where (categoryID == album.CategoryID)
select album).ToList();
List<Album> newAlbumList;
if (searchBy == "AlbumName")
{
newAlbumList = albumsWithCategory.Where(x => x.AlbumName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
else
{
newAlbumList = albumsWithCategory.Where(x => x.BandName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
}
Here is my data model (if it would be useful to find issue):
public class BigViewModel
{
public IEnumerable<Album> Albums { get; set; }
public IEnumerable<Category> Categories { get; set; }
public IEnumerable<Order> Orders { get; set; }
public IEnumerable<Song> Songs { get; set; }
}
Image with error:
enter image description here

I believe that error is due formatting in query parameters. Instead of keyup i would try to use input event and instead of building query url i would use data property.
$("#Search").on("input", function () {
//...
$.ajax({
url: "/Default/GetSearchingData",
type: "get",
dataType: "json",
data: {
categoryID: Number(catId),
searchBy: searchBy,
searchValue: searchVal
},
success: function(result) {
if (result.length > 0)
{
var rows = response.map(item => {
return `
<tr>
<td>${item.AlbumID}</td>
<td>${item.AlbumName}</td>
<td>${item.BandName}</td>
<td>${item.AlbumCover}</td>
<td>...</td>
</tr>
`;
}).join("");
setData.html( `<table>${rows}</table>` );
} else {
setData.html( "<table><tr>Not found</tr></table>" );
}
},
error: function(xhr) { }
});
});

Related

How to add delete button to a column using JS?

I have experience with PHP and HTML, but I am unfamiliar with JS. I have all the code needed, but I can't put it together. I have a table and need to add a delete button that will remove the file on that row. As shown in the picture below, but without the edit button:
When click on the Search button, the table is displayed (here is where I need the delete button):
index.php
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;'/>
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px; display:none">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>
main.js
function Search(){
var crop = $("#crop").val();
var type = $("#type").val();
var year = $("#year").val();
var season = $("#season").val();
var location = $("#location").val();
var subLocation = $("#sublocation").val();
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
$.ajax({
url: "Resources/PHP/Search.php",
dataType: 'text',
data: {
crop: crop,
type: type,
year: year,
location: location,
season: season,
sublocation: subLocation
},
success: function(response) {
var data = JSON.parse(response);
var items = "";
var firstSet = 0;
if (data.length > 0)
{
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
$("#imported-set-wrapper").html(table);
$.each(data,function(index,item)
{
if (index == 0){
firstSet = item.ID;
}
items+= "<tr id='data-set-" + item.ID + "' onclick='SelectDataSet(\"" + item.ID + "\"); return false;' style='cursor:pointer'>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
var rowHeight = 61;
var padding = 10;
var actualHeight = (data.length + 1) * rowHeight + padding;
var maxHeight = 300;
var height = actualHeight < maxHeight ? actualHeight : maxHeight;
$('#imported-set-table').fxdHdrCol({
fixedCols: 0,
width: 1100,
height: height,
colModal: [
//added
{ width: 150, align: 'center' },
//added
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 250, align: 'center' },
{ width: 175, align: 'center' },
{ width: 150, align: 'center' },
],
sort: false
});
if (firstSet > 0){
$("#next").prop("disabled", false);
SelectDataSet(firstSet);
$("#data-set-fs").show();
} else {
alert("No dataset found");
}
}
$("#processing").hide();
},
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
$("#processing").hide();
}
});
}
Useful code from picture 1
"<input id='delete-" + type + "-" + item.ID +"' type='image' class='image-button delete-button' src='Resources/Images/delete.png' alt='Delete' onclick='Delete(" + item.ID +", \"" + type + "\"); return false;' title='Delete'>" +
"<input id='confirmDelete-" + type + "-" + item.ID +"' type='image' class='image-button confirm-delete-button' src='Resources/Images/confirm.png' alt='Confirm' style='display:none' onclick='ConfirmDelete(" + item.ID +", \"" + type + "\"); return false;' title='Confirm'>" +
"<input id='cancelDelete-" + type + "-" + item.ID +"' type='image' class='image-button cancel-delete-button' src='Resources/Images/cancel.png' alt='Cancel' style='display:none' onclick='CancelDelete(" + item.ID +", \"" + type + "\"); return false;' title='Cancel'>" +
function Delete(id, type){
$('#confirmDelete-' + type + '-' + id).show();
$('#cancelDelete-' + type + '-' + id).show();
$('#delete-' + type + '-' + id).hide();
CancelEdit(id);
}
function CancelDelete(id, type){
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
}
function ConfirmDelete(id, type){
$.ajax({
url: 'Resources/PHP/' + type + '.php',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
alert("The " + type + " has been deleted.");
GetList(type);
} else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});
}
Additional info: "//added" are additional lines trying to achieve mentioned goal.
You can add your button like this "<button data-id = " + item.ID + " class='delete'>Delete</button>" where data-id has your item.ID value this will get passed to your backend to perform delete operation.
Then , when delete button get clicked this $(document).on("click", ".delete",.. will get called you can show confirm-box so if user click ok then call your ajax to delete that trs data using selector.closest('tr').remove() where selector refer to the button which has been clicked .
Demo Code :
//dummy datas
var data = [{
"Year": "2016",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "1"
}, {
"Year": "2017",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "2"
}]
function Search() {
//some codes..
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
//other codes...
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
var items = "";
$("#imported-set-wrapper").html(table);
$.each(data, function(index, item) {
if (index == 0) {
firstSet = item.ID;
}
items += "<tr id='data-set-" + item.ID + "' onclick='' style='cursor:pointer'>" +
"<td style='overflow:hidden'>" +
//added button with data-* attribute
"<button data-id = " + item.ID + " class='delete'>Delete</button>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
//soem ot//other codes..
}
//onclick of delete button
$(document).on("click", ".delete", function() {
var id = $(this).data('id'); //get id
var selector = $(this);
console.log(id)
//show confirm box if yes
if (confirm("Are you sure?")) {
//ajax call
/*$.ajax({
url: 'url',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {*/
selector.closest('tr').remove() //remove tr
/* } else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});*/
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;' />
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px;">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>
Where you have:
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
Doesn't this need to be the button? E.g.
<td><button onclick='deleteFunction(item.id)'>Delete</button></td>

data.length is not defined

I want to get the length of data, when i try console.log(data) i got all of data but console.log(data.length) is undefined.
function tampilesai(idsoal){
$.ajax({
url: "soalesai/baca/"+idsoal,
type: "POST",
dataType: "JSON",
success: function(data){
console.log(data); //here <=================
console.log(data.length); //here <=============
var html = "";
for (i = 0; i < data.length; ++i) {
html += "<tr>" +
"<td class='isitbl'>" + data[i].idsoal + "</td>" +
"<td class='isitbl' style='width:20px;'>" + data[i].noesai + "</td>" +
"<td class='isitbl' style='width:200px;'>" + data[i].matakuliah + "</td>" +
"<td>" + data[i].isiesai + "</td>" +
"<td class='isitbl'><button class='btn btn-danger btn-block' id='hapus' data[i]-id='" + data[i].idsoal + "'>" +
"<span class='icon-trash'></span> Hapus</button>" +
"</td>" +
"</tr>";
}
$("tbody#tblesai").html(html);
}
})
i need data.length for loop and fill my table. its data log
{idesai: "90", idsoal: "1", noesai: "1", matakuliah: "1", isiesai: "<p>asdd</p>"}
this image browser
If your data is an Object then you need to use Object.keys(data).length instead to get the length of the data object.
Try the following...
Convert the result data into JSON object. Although the return type was explicitly stated as JSON, but some version of jQuery may not parse it automatically. I ran into such bug with some version 2.x
var data = $.parseJSON(data);
// console.log(data.length) *should return 1
var html = "";
$.each(data, function(c) {
html += "<tr>" +
"<td class='isitbl'>" + c.idsoal + "</td>" +
"<td class='isitbl' style='width:20px;'>" + c.noesai + "</td>" +
"<td class='isitbl' style='width:200px;'>" + c.matakuliah + "</td>" +
"<td>" + c.isiesai + "</td>" +
"<td class='isitbl'><button class='btn btn-danger btn-block' id='hapus' data[i]-id='" + c.idsoal + "'>" +
"<span class='icon-trash'></span> Hapus</button>" +
"</td>" +
"</tr>";
});
$("tbody#tblesai").html(html);
I have not tested this, but I think it will give you an alternative idea.
Finish..
function tampilesai(idsoal){
$.ajax({
url: "soalesai/ambil/"+idsoal,
type: "POST",
dataType: "JSON",
success: function(data){
var html = "";
for(i=0;i<data.length;i++){
html += "<tr>" +
"<td class='isitbl'>" + data[i].idsoal + "</td>" +
"<td class='isitbl' style='width:20px;'>" + data[i].noesai + "</td>" +
"<td class='isitbl' style='width:200px;'>" + data[i].matakuliah + "</td>" +
"<td>" + data[i].isiesai + "</td>" +
"<td class='isitbl'><button class='btn btn-danger btn-block' id='hapus' data-id='" + data[i].idsoal + "'>" +
"<span class='icon-trash'></span> Hapus</button>" +
"</td>" +
"</tr>";
}
$("tbody#tblesai").html(html);
}
})
}
i change my controller
public function ambil($idsoal){
echo json_encode(
$this->pertanyaan_model
->ambilsoal($idsoal)->result());
}
and my model..
public function ambilsoal($idsoal){
$query = $this->db
->where("idsoal",$idsoal)
->get("tblsoalesai");
return $query;
}
and its works, thanks guys try to help me.. love you

Converting the text into a clickable Link

I have a web application, which displays the result parsed from an XML file in the form of table using ajax. It is working good, but the thing is, the data in the XML file is mostly URLs but I am seeing the result in the form of text. I want that text to be made/converted into a clickable link so that it would make my life easier. Is there any code which would make it possible? If yes, please let me know where should I place it. That code is in ASPX page which also has the html code which is responsible for the style of my webpage..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="Scripts/jquery-3.2.1.js"></script>
<script language="javascript" type="text/javascript">
var CheckImage = "<img src='images/check.png' height='25' width='25'>";
var CrossImage = "<img src='images/cross.png' height='25' width='25'>";
var Fail = "<img src='images/fail.png' height='25' width='30'>";
setInterval(url, 100);
setInterval(redirects, 100);
function url()
{
$.ajax(
{
url: "/XMLFile.xml",
type: "GET",
dataType: "xml",
cache: false,
success: function (xml)
{
var tableContent1 = "<table border='1' cellspacing='0' cellpadding='5'>" +
"<tr>" +
"<th>SiteName</th>" +
"<th>URLType</th>" +
"<th>DNSStatus</th>" +
"<th>TargetStatus</th>" +
"<th>TTL</th>" +
"<th>SSL</th>" +
"<th>Force</th>" +
"</tr>";
$(xml).find('ProdURL').each(function ()
{
tableContent1 += "<tr>" +
"<td>" + $(this).attr('ProdHost') + "</td>" +
"<td>" + $(this).attr('URLType') + "</td>" +
"<td>" + ($(this).attr('DNSStatus') == "OK" ? CheckImage : CrossImage) + "</td>" +
"<td>" + ($(this).attr('TargetStatus') == "OK" ? CheckImage : CrossImage) + "</td>" +
"<td>" + $(this).attr('TTL') + "</td>" +
"<td>" + ($(this).attr('SSL') == "OK" ? CheckImage : CrossImage) + "</td>" +
"<td>" + $(this).attr('Force') + "</td>" +
"</tr>";
});
tableContent1 += "</table>";
$("#UpdatePanel").html(tableContent1)
getdata(tableContent1);
}
});
}
function redirects()
{
//this ajax code parses the information from XML file and displays it on the table
$.ajax(
{
//If the name of the XML file is changed, make sure to update that in the url:
url: "/XMLFile.xml",
type: "GET",
dataType: "xml",
contentType:"url",
cache: false,
success: function (xml)
{
var tableContent2 = "<table border='5' cellspacing='1' cellpadding='10'>" +
"<tr>" +
"<th>URL</th>" +
"<th>Target</th>" +
"<th>Status</th>" +
"</tr>";
$(xml).find('Redirect').each(function ()
{
tableContent2 += "<tr>" +
"<td>" + $(this).attr('URL')+ "</td>" +
"<td>" + $(this).attr('Target') + "</td>" +
"<td>" + ($(this).attr('Status') == "Fail" ? Fail : CheckImage && $(this).attr('Status') == "OK" ? CheckImage : CrossImage) + "</td>" +
"</tr>";
});
tableContent2 += "</table>";
$("#UpdatePanel1").html(tableContent2)
getdata(tableContent2);
}
});
}
Here is a more complete example to show you. This is adding a anchor tag with the URL inside your table when you are creating your <td> in the loop.
let tableContent2 = "";
$("div").each(function() {
tableContent2 += "<tr>" +
"<td> <a href='" + $(this).attr('URL') + "'>" + $(this).attr('URL') + "</a></td>" +
"<td>" + $(this).attr('Target') + "</td>" +
"<td>" + $(this).attr('Status') + "</td>" +
"</tr>"
})
$("#UpdatePanel1").html(tableContent2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- this div is just for this example -->
<div URL="https://example.com" Target="I am a target" Status="OK"></div>
<table>
<tbody id="UpdatePanel1">
</tbody>
</table>

Asp.net Same button to edit and Save using Jquery

I have something like that,
When I click on edit, It populate the record of that student back to Text Boxes. I want to use the same 'Save' button to save and edit. I am also saving the student through same button.
I want that when someone click the edit button Save ajax call would not call. I am stuck on that. Currently when i edit the record, same record also inserted. If anyone want to see the code I can edit the question for that .
Thanks
function UpdateStudent(id, name, fname, roll, age, phone, address) {
debugger
$(document).ready(function () {
$("#students").show();
$("#txtName").val(name);
$("#txtFatherName").val(fname);
$("#txtRollNo").val(roll);
$("#txtAge").val(age);
$("#txtPhone").val(phone);
$("#txtAddress").val(address);
if (id) {
$("#btnSave").click(function (e) {
e.preventDefault();
debugger
var Name = $("#txtName").val();
var FatherName = $("#txtFatherName").val();
var RollNo = $("#txtRollNo").val();
var Age = $("#txtAge").val();
var Phone = $("#txtPhone").val();
var Address = $("#txtAddress").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "StudentManagement.aspx/UpdateStudent",
data: "{'ID': '" + id + "','Name':'" + Name + "','FatherName':'" + FatherName + "','RollNo':'" + RollNo + "','Age':'" + Age + "','Phone':'" + Phone + "','Address':'" + Address + "'}",
dataType: "json",
success: function (data) {
debugger
$("#txtName").val("");
$("#txtFatherName").val("");
$("#txtRollNo").val("");
$("#txtAge").val("");
$("#txtPhone").val("");
$("#txtAddress").val("");
$("#students").hide();
var array = data.d;
$("#table").find("tr:gt(0)").remove();
for (var i = 0; i < array.length - 1; i++) {
var row = "<tr>"
+ "<td>" + array[i].ID + "</td>"
+ "<td>" + array[i].Name + "</td>"
+ "<td>" + array[i].FatherName + "</td>"
+ "<td>" + array[i].RollNo + "</td>"
+ "<td>" + array[i].Age + "</td>"
+ "<td>" + array[i].Phone + "</td>"
+ "<td>" + array[i].Address + "</td>"
+ "<td><a href='#' onclick='UpdateStudent(\"" + array[i].ID + "\",\"" + array[i].Name + "\",\"" + array[i].FatherName + "\",\"" + array[i].RollNo + "\",\"" + array[i].Age + "\",\"" + array[i].Phone + "\",\"" + array[i].Address + "\")'>Edit</a></td>"
+ "<td><a href='#' onclick='DeleteStudent( " + array[i].ID + " )'>Delete</a></td>"
+ "</tr>"
$("#table").append(row);
}
},
error: function (response) {
debugger
alert(response);
}
});
return false;
});
}
})
}
And Insert Student code it below, also
function InsetStudent() {
debugger
$(document).ready(function () {
var Name = $("#txtName").val();
var FatherName = $("#txtFatherName").val();
var RollNo = $("#txtRollNo").val();
var Age = $("#txtAge").val();
var Phone = $("#txtPhone").val();
var Address = $("#txtAddress").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "StudentManagement.aspx/CreateStudent",
data: "{'Name':'" + Name + "','FatherName':'" + FatherName + "','RollNo':'" + RollNo + "','Age':'" + Age + "','Phone':'" + Phone + "','Address':'" + Address + "'}",
dataType: "json",
success: function (data) {
debugger
$("#txtName").val("");
$("#txtFatherName").val("");
$("#txtRollNo").val("");
$("#txtAge").val("");
$("#txtPhone").val("");
$("#txtAddress").val("");
$("#students").hide();
var array = data.d;
$("#table").find("tr:gt(0)").remove();
for (var i = 0; i < array.length; i++) {
var row = "<tr>"
+ "<td>" + array[i].ID + "</td>"
+ "<td>" + array[i].Name + "</td>"
+ "<td>" + array[i].FatherName + "</td>"
+ "<td>" + array[i].RollNo + "</td>"
+ "<td>" + array[i].Age + "</td>"
+ "<td>" + array[i].Phone + "</td>"
+ "<td>" + array[i].Address + "</td>"
+ "<td><a href='#' onclick='UpdateStudent(\"" + array[i].ID + "\",\"" + array[i].Name + "\",\"" + array[i].FatherName + "\",\"" + array[i].RollNo + "\",\"" + array[i].Age + "\",\"" + array[i].Phone + "\",\"" + array[i].Address + "\")'>Edit</a></td>"
+ "<td><a href='#' onclick='DeleteStudent( " + array[i].ID + " )'>Delete</a></td>"
+ "</tr>"
$("#table").append(row);
}
},
error: function (response) {
debugger
alert(response);
}
});
return false;
})
}
And insertStudent call on jquery load, like
$("#btnSave").click(function (e) {
e.preventDefault();
InsetStudent();
})
You can do this like:
STEP1:
If you have any required field in your form then use this
$("#btnSave").click(function (e) {
e.preventDefault();
if(Check value of required field not null or empty)
{
UpdateStudent(id, name, fname, roll, age, phone, address);
}
else
{
InsetStudent();
}
});
STEP2:
If you are not using any required field in your form then use hidden field. default value of this Hidden field will be false. When user will click on edit first assign true to hidden field.
$("#btnSave").click(function (e) {
e.preventDefault();
if(Check value of Hidden field true)
{
UpdateStudent(id, name, fname, roll, age, phone, address);
//Here update hidden field value to false after completing the operation
}
else
{
InsetStudent();
}
});
hope this logic will help you.
Remove only btnSave click event
$("#btnSave").click(function (e) {
});
from your function UpdateStudent and call the
function UpdateStudent directly on edit button click event

javascript function saying it doesn't exist when it does

I'm trying to call a JavaScript function and then pass the value of the button clicked to that function but even though the function does exist its saying it doesn't and im not sure why. Basically I need to call the powerOn() function when the power on button is clicked and then return the status messages. All I need to know is why it won't call the function so I can make sure I get the basic response.
Also I'm not entirely sure why sortable returns a console error when im following the documentation on http://github.hubspot.com/sortable/api/options/:
ReferenceError: Sortable is not defined vmstatus:123
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery-1.10.2.js:5375
TypeError: powerOn is not a function
Code:
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#table-repeat-data').remove();
setInterval(update, 1000);
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
$('#table_name').append("<table class='table' id='table-repeat-data' data-sortable><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>");
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + on + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}else{
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + off + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}
}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
function update(){
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = on;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}else{
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = off;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}
}
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
function powerOn() {
console.log('powerOn');
console.log(this.val());
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_vm : $(this).val(),
username : '{{user_name}}',
ip_address: '{{ip}}',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
console.log(json.server_response);
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
Sortable.init();
var dataTable;
dataTable = document.querySelector('#table-repeat-data');
Sortable.initTable(dataTable);
</script>
Try changing the name of your function, or changing the name of your variable of the same name. It's possible that it is getting confused as to which one you actually mean due to scope.
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
function powerOn() {...}
which one is powerOn? They both are. It's possible that your function is later overridden to a string value and then it is no longer valid to try and call it like it was a function.

Categories