<style>
#number{height: 50px; color: #000; }
</style>
Progress: <div id="number"> </div>
<script type="text/javascript">
var i = 0;
d = 1;
function increment(d) {
if(i<100){
i+=d;
document.getElementById('number').innerHTML = i + '%';
}
else{
document.getElementById('number').innerHTML = 'done' ;
}
}
setInterval('increment(d)', 1000);
</script>
<button type="button" id="button" onclick="d++">Add</button>
<button type="button" onclick="window.location.reload()">Refresh</button>
i'm currently working on a web app with visual studio on asp.net mvc 4. i need to make a partial view that shows a counter that goes from 1 to 100. i added a button that increases by 1 the counter value on every click and another one for refreshing the page. how can i do this using ajax?
AJAX (Asynchronous Javascript and XML) is for making web requests without visible page refreshes. That is not what you should be using this for. You can do this using setTimeout. I have provided a JSFiddle for you to use.
The important bits
In Javascript, you can simulate asynchronous functionality using setTimeout. This function will allow the Javascript to continue executing, and after a given waiting period, will execute the code you provide.
function doSomething() { alert("hello"); }
setTimeout(doSomething, 1000);
This will execute the doSomething() method.
NOTE: You pass the function as a callback. As in doSomething and not doSomething().
Related
I am porting an application to WordPress. It uses a form to select what attributes the customer is looking for in an Adult Family Home via checkboxes and drop-downs. It re-searches the database on each onchange and keyup. Originally I had the application standalone in PHP, but when I migrated it to WordPress I started having issues.
Currently in WP I have the code conditionalized ($DavesWay == 1) to do ajax the normal no-WordPress-way and ($DavesWay == 0) to do it the WordPress-way.
In the non-WordPress-way, the ajax works fine EXCEPT that I get a WP header and menu between the search form and the results-div that Ajax puts the data in. I get no errors from WP or in the JS console. In the WP-way The search form displayed, but nothing happens when I check any of the checkboxes. The JS console displays
POST http://localhost/demo4/wp-admin/admin-ajax.php 400 (Bad Request)
But I don't see any way to tell exactly what it is complaining about. How should I troubleshoot this?
Troubleshooting = Examine the HTML output, lots of echos and exits in PHP code, look at JS console.
function submitPg1(theForm) {
// Used with onChange from "most" form elements, but not on those that change the page
// rather than the select criteria. Such as rowsPerPage, pageNumber etc.
setById("pageNo", "1"); // set inital page
mySubmit();
}
function mySubmit(theForm) { // The actual ajax submit
// DO NOT set page number
jQuery.ajax({ // create an AJAX call...
data: jQuery("#asi_search_form").serialize(), // get the form data
type: jQuery("#asi_search_form").attr("method"), // GET or POST
url: jQuery("#asi_search_form").attr("action"), // the file to call
success: function (response) { // on success..
jQuery("#result").html(response); // update the DIV
}
})
}
function setById(id, value) { // Used to set vales by Id
x = document.getElementById(id).value;
x.value = value;
}
// 1st submit with blank selection
jQuery(document).ready(function () { submitPg1(this.form) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Code fragments: (from the displayed page source)
<div id="asi_container" class="asi_container" >
<noscript><h2>This site requires Javascript and cookies to function. See the Help page for how to enable them.</h2></noscript>
<div id="searchForm">
<form id="asi_search_form" name="asi_search_form" method="post" action="http://localhost/demo4/wp-admin/admin-ajax.php">
<input type="hidden" name="action" value="asi_LTCfetchAll_ajax" style="display: none; visibility: hidden; opacity: 0;">
<table id="greenTable" class="asi_table" title="The Green areas are for site administration, not typical users">
<tbody>
PHP code:
$DavesWay = 0;
if ($DavesWay == 1){ //echo "Daves Way Setup"; // Dave's way, which works but prints the menu twice
if( $operation == "submit"){
require("asi_LTCfetchAll.php"); // for each onchange or onkeyup
}else{
add_filter( 'the_content', 'asi_tc_admin', '12' ); // Initial page refresh # must be >12
}
}else{
// The WordPress way that I could't get to work -- asi_LTCfetch never gets called
function asi_LTCfetchAll_ajax(){
//echo "<br /> Goto to Submit function"; // DEBUG
require($asi_plugin_dir . "/includes" . '/asi_LTCfetchAll.php');
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // non-logged in users
add_filter( "the_content", "asi_tc_admin", "12" ); // Initial page refresh # must be >12
}
Try changing the JavaScript to the way WordPress recommends it in their documentation:
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
I suggest trying following URL: https://codex.wordpress.org/AJAX_in_Plugins
Also you can use the plugin: https://wordpress.org/plugins/ajax-search-lite/
I am new to ASP.NET core.
I am loading a different view under components folder using view component based on a condition.
<div class="container" id="patientLayout">
#await Component.InvokeAsync("PatientView", new {model = Model})
</div>
public async Task<IViewComponentResult> InvokeAsync(PatientTabViewModel model)
{
switch (model.Id)
{
case 3:
PatientMessageViewModel msgModel=GetMessagesViewModel(model.PatientId);
return await Task.FromResult(View("_messages.cshtml", msgModel));
}
}
I have a $(document).ready() function in _Messages.cshtml
<script type="text/javascript">
$(document).ready(function () {
console.log('ready function fired');
}
});
</script>
Issue: This ready function is getting fired for first time only but next time onwards its not getting fired,but breakpoint getting hit at case 3 every time.
Could you please provide some info/solution for this?
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.Reference :$( document ).ready()
I have an issue with observables being fired after content is updated via ajax and javascript is re-initialized via .trigger('contentUpdated'). This all works when the scripts are rendered initially on page load but when they are added via ajax I cannot get the observables to update. For demo purposes I've simplified by logic but basically I have a block that gets loaded via ajax for a product collection like so:
myblock.phtml
<div class="wrapper-id-1">
<!-- this is what gets appended via ajax
<div id="product-item-<?php echo $productId;?>">
<span data-bind="text: someObservable()"></span>
...
</div>
<script type="text/x-magento-init">
{
"#product-item-<?php echo $productId;?>": {
"path/to/component":{
"some":"vars"
}
}
</script>
<!--and ajax append ends here -->
</div>
In the component that gets bound to the element I have:
component.js
...
this.someObservable: ko.observable('default value'),
initialize: function () {
var self = this;
this.anotherComponentModel().value.subscribe(function(data){
self.someObservable(data['value']);
},this);
},
...
the ajax that calls and loads the collection:
ajaxComponent.js
$.ajax({
url: 'route/to/controller?cat=' + categoryId,
success: function (data) {
$('.wrapper-id-' + categoryId).empty().append('<h2>' + categoryTitle + '</h2>' + data).show().trigger('contentUpdated');
}
})
...
I see that the component(component.js) gets initialized when contentUpdated is triggered and it has all of the correct data that is needed. However the observables to not fire and the data is not updated to the DOM. This an issue with scope? Or to I need to re-initialize the observables? I tried doing this via not binding directly to the component ie:
<script type="text/x-magento-init">
{
// components initialized without binding to an element
"*": {
"<js_component3>": ...
}
}
</script>
but it achieves the same result.
What am I missing here.
I'd like to use bootstrap's carousel to dynamically scroll through content (for example, search results). So, I don't know how many pages of content there will be, and I don't want to fetch a subsequent page unless the user clicks on the next button.
I looked at this question: Carousel with dynamic content, but I don't think the answer applies because it appears to suggest loading all content (images in that case) from a DB server side and returns everything as static content.
My best guess is to intercept the click event on the button press, make the ajax call for the next page of search results, dynamically update the page when the ajax call returns, then generate a slide event for the carousel. But none of this is really discussed or documented on the bootstrap pages. Any ideas welcome.
If you (or anyone else) is still looking for a solution on this, I will share the solution I discovered for loading content via AJAX into the Bootstrap Carousel..
The solution turned out to be a little tricky since there is no way to easily determine the current slide of the carousel. With some data attributes I was able to handle the .slid event (as you suggested) and then load content from another url using jQuery $.load()..
$('#myCarousel').carousel({
interval:false // remove interval for manual sliding
});
// when the carousel slides, load the ajax content
$('#myCarousel').on('slid', function (e) {
// get index of currently active item
var idx = $('#myCarousel .item.active').index();
var url = $('.item.active').data('url');
// ajax load from data-url
$('.item').html("wait...");
$('.item').load(url,function(result){
$('#myCarousel').carousel(idx);
});
});
// load first slide
$('[data-slide-number=0]').load($('[data-slide-number=0]').data('url'),function(result){
$('#myCarousel').carousel(0);
});
Demo on Bootply
I combined #Zim's answer with Bootstrap 4. I hope it will help someone.
First, load just the path of the images:
<div id="carousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item" data-url="/image/1.png"></div>
<div class="carousel-item" data-url="/image/2.png"></div>
<div class="carousel-item" data-url="/image/3.png"></div>
</div>
</div>
Then in JavaScript:
$('document').ready(function () {
const loadCarouselImage = function ($el) {
let url = $el.data('url');
$el.html(function () {
let $img = $('<img />', {
'src': url
});
$img.addClass('d-block w-100');
return $img;
});
);
const init = function () {
let $firstCarousel = $('#carousel .carousel-item:first');
loadCarouselImage($firstCarousel);
$firstCarousel.addClass('active');
$('#productsCarousel').carousel({
interval: 5000
});
};
$('#carousel').on('slid.bs.carousel', function () {
loadCarouselImage($('#carousel .carousel-item.active'));
});
init();
});
I have an Ajax call back function which call to a PHP function check the file modified time.
I uses timer to execute it every 50 seconds.
<script type="text/javascript">
setInterval("_checkPopUpUpdate()", 50000); //50 seconds
</script>
function _checkPopUpUpdate()
{
var callback=new Object();
callback.success=this.onExternalSuccess;
callback.failure=this.onExternalFailure;
YAHOO.util.Connect.asyncRequest('GET','/ci/ajaxCustom/ajaxCheckPopupUpdate',callback);
};
The PHP function checks whether the file modified time has different between the first load session time
$announcement_Popup_Path = HTMLROOT . $this->data['attrs']['file_path'];
// Call model function
if($this->data['attrs']['file_path'] !== '' && file_exists($announcement_Popup_Path))
{
//When the announcement content load, it always stores the modified time into session
$this->CI->load->model('custom/checkupdate_model');
$firstloadTime = filemtime($announcement_Popup_Path);
$this->CI->checkupdate_model->store_AnnouncementPopupSession($firstloadTime);
//$this->data['Popup'] = file_get_contents($announcement_Popup_Path);
}
function store_AnnouncementPopupSession ($popupTime)
{
$sessionPopupTime =array("annoucementPopUp"=> $popupTime);
$this->session->setSessionData($sessionPopupTime);
}
function announcement_pop()
{
$file_path='/euf/assets/announcements/pop_up_announcement.html';
$announcement_Popup_Path = HTMLROOT . $file_path;
if(file_exists($announcement_Popup_Path)) {
$currentAnnouncementPopUpTime = filemtime($announcement_Popup_Path);
$oldannouncementPopupTime = $this->session->getSessionData("annoucementPopUp");
if($currentAnnouncementPopUpTime !=$oldannouncementPopupTime) {
//comparing the content and update the time, when they are different, send back update content
$this->store_AnnouncementPopupSession($currentAnnouncementPopUpTime);
//echo $currentAnnouncementPopUpTime;
echo $file_path;
}
else {
echo "no update";
}
}
}
When the file modifed time has changed, it will return to ajax call back and grab the HTML content in my web server to Pop up an annoucement pop up window.
function onExternalSuccess (o){
if(o.responseText!==undefined)
{
var str=o.responseText;
if(str !== 'no update') // Then pop up.
{
L=screen.width-200;
T=screen.height;
popup=window.open(str," ",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=150,width=364,left="+L+",top="+T');
//popup=window.open(str,"",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=100,width=330');
for (i=0;i<200;i++)
{
T=T-1;
popup.moveTo(L,T);
}
}
}
};
It works fine for Firefox and Chrome, however IE7 is a bit bugy, sometime the pop up does not come out.
<html>
<head>
<title>Internal alert</title>
<link rel="stylesheet" type="text/css" href="/euf/assets/css/pop_up_ann.css" media="screen, projection" />
<script type="text/javascript">
var howLong = 50000; //5 minutes, 1 seconds = 1000 milliseconds.
t = null;
function closeMe(){
t = setTimeout("self.close()",howLong);
}
</script>
</head>
<body onLoad="closeMe();self.focus();">
<div id="cs_popup">
<div class="popup_rounded-corner-top">
<div id="popup_ann">
<div id="popup_ann_title">IE7 pop-up EMEA test close </div>
<div id="popup_ann_from"> PLC team - 05/01/2011 at 12:10</div>
<div id="popup_ann_content">
Something has changed in the<em>"Alerts"</em> section of S4S since your last visit.
Make sure you go there as soon as you can to be informed about the current situation.
</div>
</div>
</div>
<div class="popup_rounded-corner-bottom"></div>
</div>
</body>
</html>
The main problem i have here it is self-close function. It close my pop up window and the website as well. Any hints? Also, i am not sure whether my whole pop up annoucement logical structure is correct, is there anyway? thanks
Opening a popup window for an announcement like this could be problematic for people running popup blockers, which typically only allow popups to appear in response to a user-initiated event like clicking on something. A better approach would be to use an inline popup which would also give you the opportunity to display the popup modally (i.e. mask the rest of the page with a semi-transparent div) if you require them to acknowledge your message.
The use of self.close() should not close the original window/tab opened by the user, it should only close things that have been 'open'ed so I'm not sure what's going on there, I suspect you haven't told us everything :) An alternate approach might be to modify your popup function to close the window rather than have the window close itself.
// open popup ... then set timeout to close it
var popupDelay = 50000;
setTimeout(function() {
popup.close();
}, popupDelay);
This may work a little better, not sure. But in the long run, I highly recommend avoiding popups and using something inline instead.