With my scripts below, when i start searching Facebook in my table, it appends the fetched Facebook to the table and now i have two Facebook data on the table. When i clear the search input, the table must move to the default state of having all items
Why is my script not doing such?
PS: sorry for my bad english
<script>
$(document).ready(function () {
var typingTimer;
var doneTypingInterval = 100;
$("#myInput").on('keyup', function () {
clearTimeout(typingTimer);
if ($('#myInput').val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
});
//user is "finished typing," do something
function doneTyping() {
var key = $('#myInput').val();
if (key.length >= 1) {
$.ajax({
url: '/customer/search/?myInput='+key,
type: 'GET',
beforeSend: function () {
$("#table").slideUp('fast');
},
success: function (data) {
console.log(data);
$("#table").slideDown('fast');
var table = $("#table tbody");
$.each(data, function(idx, elem){
table.append(
"<tr><td></td> <td>"+elem.name+"</td><td>"+elem.phone+"</td><tr>"
);
});
}
});
}
}
</script>
You added a if (key.length >= 1) condition, so if you clear the search input it won't call the ajax function again. You should just remove this condition.
Related
Struggling to get this to work properly...Making an if/else statement with setInterval that if class is clicked, content refreshes, else content auto refreshes after a specific time period. This is what I have for just auto refreshing atm (which works perfectly):
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
What I've tried to get a "click" function added, but doesn't do anything...:
$('.contentTwoClicked').on('click', function() {
var refreshClicked = true;
if(refreshClicked) {
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
} else {
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
}
});
Where am I going wrong? Or am I way off-base here...? Any guidance/help would be greatly appreciated!
You don't need a conditional statement, but rather a variable to store the set interval in so that it can be cleared and restarted on manual refresh via a calling function:
//variable to store the setInterval
let refreshInterval = '';
//function that calls setInterval
const autoRefresh = () => {
refreshInterval = setInterval(()=> {
refresh();
console.log("auto");
},3000)
}
//run setInterval function on page load;
autoRefresh();
//manual refresh function
const manualRefresh = () => {
//erases the setInterval variable
clearInterval(refreshInterval);
refresh();
//then recalls it to reset the countdown
autoRefresh();
console.log("manual");
}
//for visual purposes
let refreshCount = 0;
//node refresher function
const refresh = () => {
const container = document.getElementById("refresh");
refreshCount ++;
container.textContent= "This div will be refreshed"+ ` Refresh Count: ${refreshCount}`;
}
<button onclick="manualRefresh()">Click to Refresh </button>
<div id="refresh">This div will be refreshed</div>
See it in action: https://codepen.io/PavlosKaralis/pen/rNxzZjj?editors=1111
Edit: Applied to your code I think it would be:
let interval;
var autoRefresh = () => {
interval = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000);
}
$('.contentTwoClicked').on('click', function() {
clearInterval(interval);
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
autoRefresh();
});
autoRefresh();
I have two ajax functions that one is recursively working at loop and other is working when click event invoked. I tested both of the functions that are able to work properly. But when i start recursive function button event is not invoked.
Function that works on click event GET Content from ActionResult (MVC)
function UpdateRequests(url, state, id, cell)
{
$.ajax({
type: "GET",
url: url + id,
success: function (result) {
if (result == "OK")
{
cell.fadeOut("normal", function () {
$(this).html(state);
}).fadeIn();
}
else if(result == "DELETE" || result == "CANCEL")
{
cell.parent().fadeOut("normal", function () {
$(this).remove();
});
}
else
{
$(".modal-body").html(result);
$("#myModal").modal();
}
},
error: function () {
alert("Something went wrong");
}
});
}
Recursive function GET partial view from ActionResult (MVC)
function RefreshRequests()
{
if (isListPage())
{
var id = PageId();
var url = "/Home/List/" + id;
}
else
{
var url = "/Home/Index";
}
$.ajax({
type: "GET",
url: url,
success: function (data) {
$(".ajaxRefresh").html(data);
EditPageHeader();
},
complete: function () {
setTimeout(RefreshRequests, 2000);
}
});
}
Click event
$(".tblRequests").on("click", button, function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
Main
$(document).ready(function () {
EditPageHeader();
RefreshRequests();
ButtonEvent(".btnPrepare", "/Home/Prepare/", "PREPARING");
ButtonEvent(".btnApprove", "/Home/Approve/", "APPROVED");
ButtonEvent(".btnCancel", "/Home/Cancel/", "CANCELED");
RefreshRequests();
});
Assumptions:
The Ajax Calls bring you data that end up as HTML elements in the modal body.
These new elements added above need to respond to the click event (the one that doesn't work correctly right now)
If the above 2 are true, than what is happening is you are binding events to existing elements (if any) and new elements (coming from API response) are not bound to the click event.
The statement
$(".tblRequests").on("click", button, function (e) {
...
})
needs to be executed every time new elements are added to the body. A better approach for this would be to define the event handler as an individual method and then bind it to each new element.
var clickHandler = function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
}
// Then for each new record that you add
$(".tblRequests").on("click", button, clickHandler);
It would be helpful if you can try to explain what exactly you are trying to achieve.
Problem is that the $(this) will hold all elements of the selector. And will also now with one as it will be triggered one time and then never again. Also as can be seen from here, delegate events should be at the closest static element that will contain the dynamic elements.
function ButtonEvent(button, url, state)
{
$("body").on("click", button, function (e) {
e.preventDefault();
var button = e.target;
var id = $(button).data("id");
var currentRow = $(button).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
}
I have an input box (search box) to filter my html table. My query is able to filter the table alright but when i clear the search box it does not bring back the already existing data
For instance if i have
MacBook
Acer
and i search for M
it displays MacBook which is fine
but when i clear the M from the search box, the table still looks like
MacBook
instead of
MacBook
Acer
JS
<script>
$(document).ready(function () {
var typingTimer; //timer identifier
var doneTypingInterval = 100; //time in ms (5 seconds)
$("#query").on('keyup', function () {
clearTimeout(typingTimer);
if ($('#query').val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
});
function doneTyping() {
var key = $('#query').val();
$.ajax({
url: 'search/?query='+key,
type: 'GET',
beforeSend: function () {
// $("#table").slideUp('fast');
},
success: function (data) {
console.log(data);
$("#table").slideDown('fast');
var table = $("#table tbody");
table.html("");
$.each(data, function(idx, elem){
table.append(
//appending rows here
);
});
}
});
}
</script>
This code:
$("#query").on('keyup', function () {
clearTimeout(typingTimer);
if ($('#query').val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
is binded to a keyup event (ok) but will look if $('#query') has a value:
if ($('#query').val()) {
If you empty the input field this condition will be false.
Simply remove the if condition and this will work.
$("#query").on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
After i deleted row the serial number column number are not re-ordered
I have Delete button in each row on click calling Ajax to delete record from data. It's deleting record from data base, after deleted recording I want to display remain data and remove particular row in table but it's changing pagination and refreshing the whole table.
var owner_table = null;
$(document).ready(function () {
owner_table = $('#owners_table').DataTable();
});
function deletehouseowner(oid, rid) {
$.ajax({
dataType: "HTML",
type: "POST",
data: {
"oid": oid
},
url: "houseowner_delete.php",
success: function (msg) {
if (msg === "failure") {
} else {
event.preventDefault();
var table = 'owners_table';
var row = $(this).closest('tr');
var id = row.attr("id");
setTimeout(function () {
var siblings = row.siblings();
owner_table.row($('#row_' + rid)).remove().draw();
siblings.each(function (index) {
$(this).children().first().text(index + 1);
});
}, 100);
}
}
});
}
Screenshot:
SOLUTION
API method draw() accepts optional parameter that controls how the table should be updated.
Pass false to draw() function to preserve current page, see the code below:
owner_table.row($('#row_'+rid)).remove().draw(false);
DEMO
See this jsFiddle for code and demonstration.
I need to archive this task.i have seen this type of tasks in various sites.
$(document).ready(function () {
$.ajax // rest of codes goes here
$("").load // rest of codes goes here
});
I need to show a gif before ready the document(DOM).After the ready the DOM it should disappear automatically.The gif should on the middle of the page.Any idea?
JAVASCRIPT
$(document).ready(function () {
//calculater start
$("#step2_6").click(function () {
$("#calculater").load("cal/cal.html");
});
//calculater end
//menu start
$(".container").load("../../view/html/menu.html", function () {
$(".main_menu.nav a").css("opacity", 0.3);
$("#step1").css("opacity", 1);
//new company start
$("#step1_1").on("click", function () {
//new company start setup opening....
$(".load_window").load("../../view/html/Finalsetup.html", function () {
//company file download
$("#downloadLink").click(function () {
var companyname = $("#company_name").val();
$(this).attr("href", +"../../company_info/" + companyname + "/" + companyname + ".json");
$(this).attr("target", "_new");
});
//create the company through ajax...
$("#CreateCompanyButton").click(function (event) {
event.preventDefault();
//adding step1 and step2 forms
var data = $("#companyData").serialize();
var dataTwo = $("#companyDataStepTwo").serialize();
$.ajax({
type: "POST",
url: "../../controller/business_contact_info.php",
data: data + "&" + dataTwo,
beforeSend: function () {
//loading a gif
$(".loader").html("<img src='../../img/loader.gif' />");
},
success: function (response) {
$(".main_menu.nav a").css("opacity", 1);
//remove gif after loaded
$(".loader").html(" ");
//add your infor window operning...
$(".load_window").load("../../view/html/addYourInfo.html", function () {
$("#addThePeople").click(function () {
//hidden add people window is opening...
$("#addPeopleWindow").show();
//select the excel sheet...
$("#excel").change(function () {
//opening table window...
$("#addPeopleWindow").load("../../view/html/tabledata.html", function () {});
});
});
});
}
});
});
//adding scipt to selectors...
$('.selectpicker').selectpicker();
$(".drag").draggable();
$("#previewButton").on("click", function () {
$("#previewSettingsView").show();
});
$("#previewClose").on("click", function () {
$("#previewSettingsView").hide();
});
$("#step_two").hide();
$("#step_three").hide();
$("#step_four").hide();
$("#step_one_button").click(function () {
$("#step_one").hide();
$(".tell_us").css("opacity", "0.4");
$(".contact_info").css("opacity", "*0.2");
$("#step_two").show();
});
$("#step_two_back").click(function () {
$("#step_two").hide();
$("#step_one").show();
});
});
});
});
});
Just put the code into your script, without enclosing $(document).ready(). It will be executed as soon as the <script> tag is parsed by the browser.