I have a table that is being populated dynamically, and a reload script that refreshes it ever 60 seconds.
<script type="text/javascript" language="javascript">
window.setInterval(function () {
$('#divGrid').load('Home/Index #divGrid>table');
}, 60000);
</script>
I also have a Javascript that calls a partial view on table row click:
<script type="text/javascript" language="javascript">
function showOpenTrData() {
$('#OpenTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetails/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
function showClosedTrData() {
$('#ClosedTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetailsClosed/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
I had it at first without an onclick function but then upon reload it would stop working so I changed it to onclick function, however first time after reload I have to double click the row and after that for the period of 60 seconds till next reload its all fine, after it reloads I have to double click the first time again. Its driving me up the wall.
Please help!
HTML
<table class="table" id="OpenTickets" style="overflow-y:scroll;width:70%;float:left; margin-top:-25px; display:block;">
<tbody>
#foreach (var item in Model.ticketModel.OrderByDescending(x => x.ticket.ID).Where(x => x.ticket.StatusID == 1))
{
<tr onclick="showOpenTrData()">
<td class="columnID" id="ticketID">
#Html.DisplayFor(modelItem => item.ticket.ID)
</td>
<td class="columnSummary">
#Html.DisplayFor(modelItem => item.ticket.Summary)
</td>
<td class="columnAssignee" id="ajaxTest">
#if (item.ticket.Assigned_to_UserID == null || item.ticket.Assigned_to_UserID == 0)
{
#Html.Label("Unasigned")
}
else
{
#Html.DisplayFor(modelItem => item.assignedUser.First_name)
<text> </text>
#Html.DisplayFor(modelItem => item.assignedUser.Last_name)
}
</td>
<td style="font-size:11px; width:10%" class="columnUpdated">
#if ((item.ticket.updated_at == null))
{
#Html.DisplayFor(modelItem => item.ticket.Created_at)
}
else
{
#Html.DisplayFor(modelItem => item.ticket.updated_at)
}
</td>
</tr>
}
</tbody>
</table>
i got it - if anyone else struggles here is the breakdown.
.load method renders any javascript useless as its not part of the same instance any more, hovever on click is a solution but how do you get the object reference?
you pass this in the on click function.
onclick="showTableData(this)"
then you can use the passed event to acquire data from it
cheers
The basic problem here is that you are mixing onclick=... with jQuery bindings .click(...). It is possible to use both on the same page but it becomes confusing and is harder to maintain: Pick one.
The easiest thing (based on your current code) is to kill the jQuery bindings. Try this:
<script type="text/javascript" language="javascript">
function showOpenTrData(ptr) {
$.ajax({
url: 'Home/TicketDetails/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
function showClosedTrData(ptr) {
$.ajax({
url: 'Home/TicketDetailsClosed/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
</script>
Each time the showOpenTrData or showClosedTrData was running, it was adding another jquery bind. If you open your console and check the networks tab you'll see that the ajax functions are then being run multiple times with one click (after the second click).
If you want to just use jQuery, then use this:
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#OpenTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetails/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
$('#ClosedTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetailsClosed/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
Also, delete the onclick=... section in the html or you'll get javascript errors because it is looking for a function that doesn't exist.
EDIT:
I added in the ticketId you needed.
Related
I'm trying to delete a table row, my button works and my product deletes from the database, however it doesn't delete on the page until a refresh and I always get "It Failed" even tho it worked... What am I doing so wrong? seems like the "success" isn't being called.
$(".deleteProduct").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "/eventlineitem/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
Here is my html
<tr class="item{{$item->id}}">
<td class="align-center" scope="row">{{$item->product->id}}</td>
<td class="align-center">{{$item->quantity}}</td>
<td>{{$item->product->name}}</td>
<td class="align-center">{{$item->warehouse_id}}</td>
<td class="align-center">{{$item->product->location}}</td>
<td><div class="switch">
<label><input type="checkbox"><span class="lever switch-col-green"></span></label>
</div></td>
<td><i class="material-icons deleteProduct" data-id="{{ $item->id }}" data-token="{{ csrf_token() }}">delete</i></td>
</tr>
Change your success function like this
success: function ()
{
$(".item"+id).remove();
console.log("it Work");
}
I don't know how you expected the html to know you deleted the row?
I think you should create a variable before the Ajax call
var target = $(this).parents("tr");
And then in the ajax.success call
target.remove()
success: function() {
$(this).parent().parent().remove();
console.log("it Work");
}
By the way, if console.log is being fired here then you know success worked.
Can you try with the below code:
$(".deleteProduct").click(function(){
var _selector = $(this);
var id = _selector.data("id");
var token = _selector.data("token");
$.ajax({
url: "/eventlineitem/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token
},
success: function (){
console.log("it Work");
_selector.parents('tr.item' + id).remove();
}
});
});
Let me know if its work for you.
I a have a Bootstrap Typeahead function, what I want to customize a little bit. If the user clicks on any of the items in the result dropdown list, the user would be redirected to one subpage. The typeahead function is working great, the dropdown list is populated without any error, this is one example what is return from the php file:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
The idea is, that the "name" attribute is displayed to the user and after click, it's redirects to the "url" attribute.
The problem is that right now after I click on ANY of the items I get this error (Firefox Firebug console output):
TypeError: ui is undefined
This is my jQuery function and before that the .js imports:
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/bootstrap/js/ie10-viewport-bug-workaround.js"></script>
<script src="/bootstrap/js/bootstrap3-typeahead.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
</script>
</body>
Can someone help me please, what's the problem here?
Thank you very much!
updater function was the solution:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
updater: function (item) {
window.location.href = item.url
},
});
});
});
I wonder why its not working, here is the code
View
<input type="button" value="Delete" onclick="deletefunction(#item.PhotoId)"/>
Controller
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return null;
}
JQUERY/AJAX
<script type="text/javascript">
$(document).ready(function () {
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
};
});
</script>
im new to jquery and ajax, im trying to delete the photo without refreshing the page, am i in the correct path?
I would suggest to attach click event to your button instead of writing javascript in markup. Consider the below markup:
<input type="button" class="delete" value="Delete" data-picid="#item.photoId"/>
Now attach a click event to .delete as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
//access message from server as result.message and display proper message to user
alert: ("Success")
},
error: {
alert: ("Error")
}
});
});
Your Controller then:
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return Json(new{ message=false},JsonRequestBehavior.AllowGet);//return false in message variable
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return Json(new{ message=false},JsonRequestBehavior.AllowGet); //return true if everything is fine
}
Once photo is deleted based on the success or failure your can do it as below in success of ajax, but before that store a reference to yourbutton` as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
var $this=$(this);
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
if(result.message)
{
$this.closest('yourrootparentselector').remove();
//here yourrootparentselector will be the element which holds all
//your photo and delete button too
}
},
error: {
alert: ("Error")
}
});
});
UPDATE
Based on your given mark up you I suggest to add one more root parent for your each image and delete button as below:
<div style="margin-top: 17px;">
<div id="links">
#foreach (var item in Model.Content)
{
<div class="rootparent"> <!--rootparent here, you can give any classname-->
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
</div>
Now you can write this in success
$this.closest('.rootparent').remove()
Try this.
<script type="text/javascript">
$(document).ready(function () {
});
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
}
</script>
Am trying to open an id on a new window, this is my code:
<script type="text/javascript">
$(document).ready(function () {
$('.myButton').click(function () {
$.ajax({
type: "GET",
url: $(this).parent().data("url"),
data: { callNumber: $(this).parent().data("callno") },
success: function (data) {
$("#CallDetail").html(data);
},
});
});
});
</script>
When i click .myButton class it opens the id:
<div id="CallDetail"></div>
thats located on the home page.
What i need is to open on a new window, i have tried doing this via the link :
<div data-callno='#parts.Call_Num' data-url="#Url.Action("GetCallInfo", "CallHandling" , new {target = "_blank"})">
<div class="myButton toolbarIcon">
<div class="toolbarIconText">View</div>
</div>
But no luck, at the moment it just opens in the same page i am doing this, the problem is am getting data called in the JavaScript so its trickier then i imagined. any ideas?
You can use jQuery's .find to search the returned HTML for a selector:
$(document).ready(function () {
$('.myButton').click(function () {
$.ajax({
type: "GET",
url: $(this).parent().data("url"),
data: { callNumber: $(this).parent().data("callno") },
success: function (data) {
$(data).find('#CallDetail');
},
});
});
});
i am appending a div using ajax and alnog with that div a function (it's a time ago function) the function needs to be called as soon as the div is appended I've tried all possible solutions but none works
my function (located in processor.php page)
<script>
$(document).ready(function () {
$('.post_the_stat').click(function(event) {event.preventDefault();
$.ajax({
type: "POST",
url: "addition_life_text.php",
data: 'final_text='+ fin_text +'&priv='+ priv + '&post_time='+post_time ,
success: function(data) {
$(".main_container").prepend(data);
}
})
})
})
</script>
the function
<script>
function ago()
{
//codeblock
}
</script>
my question:how do i call the function ago as soon as the ajax was success is appended.ive tried window.onLoad etc...
<script>
$(document).ready(function () {
$('.post_the_stat').click(function(event) {event.preventDefault();
$.ajax({
type: "POST",
url: "addition_life_text.php",
data: 'final_text='+ fin_text +'&priv='+ priv + '&post_time='+post_time ,
success: function(data) {
$(".main_container").prepend(data);
ago();
}
})
})
})
</script>
Please try above. Hopefully this will work
Try this
success: function(data) {
$(".main_container").prepend(data).go();
}
})