Partial page refresh for evary X seconds with Jquery and Ajax? - ajax

1) I have to change images dynamically according to values for every x seconds.
I'm using the following function:
setInterval(function() {
$("#content").load(location.href+" #content>*","");
}, 5000);
It works fine for updating the value, but the images not getting updated into its position.
2) From the 1st question i want to know whether the jquery and css files included in the head tag will load every x seconds or not. if not how to load?
Please give me the suggestion.

If you are returning a whole HTML page and returning it into the body of another page, that is a bad idea.
Think about it, your html structure would be something like
<doc type>
<html>
<head>
</head>
<body>
<div>
<doc type>
<html>
<head>
</head>
<body>
<div>
</div>
</body>
</html>
</div>
</body>
</html>
Ideally you should be retuning just the content that is to be displayed, not everything.
If you are just updating images, there usually is no need to make an XHR call. You can just set the image src and force the browser to update that content that way.

Does this need to be done with Ajax at all? How many images are you going to cycle through? If it is only a few, just keep all of the src's on the page and switch the image src attribute periodically. This requires no page reload. You may also want to preload all the images so there is no flicker when changing to the other image. For example:
$(function () {
var images = ['1.png', '2.png', '3.png'];
$.each(images, function (index, src) {
$("<img />").attr('src', src); //preload
});
var keep = 1;
setInterval(function () {
$("#main_img").attr('src', images[keep]);
keep++;
if (keep >= images.length) { keep = 0; }
}, 5000);
});
Now if you don't want to hard code the image urls in the JS, you can load them initially with a single Ajax request.
I would only recommend using Ajax to do all the work if you are talking about an unpredictable set of images or some massive number of images.

Related

How to inject script code in head?

I have profile user page index.blade.php where I should to shoe Google map.
This template looks like:
#extends('users.index')
#section('content')
<script>Google scripts</script>
#endsection
So, when page is rendered I get outpus as:
<html>
<head></head>
<body>
<script>Google scripts</script>
</body>
</html>
So, when I do HTML validation onlne, I get error, that you can not use scripts in body. It should be in HEAD.
Is there an way to do this in Laravel?
I dont want to load Google script on each pages.
in index page make script in its head to check page URL and if matched requested url then load scripts in page like below
<script>
const RequestedUrl = window.document.URL;
function injectScript ( myScriptURL ) {
let script = document.createElement("script")
script.type = "text/javascript";
script.src = myScriptURL;
document.getElementsByTagName("head")[0].appendChild(script);
}
if(RequestedUrl === 'http://your.URL') { // or RequestedUrl.includes('/cats') for ex.
injectScript(//jquery script URL//);
injectScript(//google script URL//);
}
</script>
if it depended on jquery or any make sure to load it same way before google scripts
learn more

How to refresh only a image of a whole page, when the imagename is variabel?

This is my puzzle i'm struggeling with:
I have a website with a certain amount of images, and i'd like the images to be refreshed each say 20 seconds,
this is the code I wrote so far for that:
<IMG src="imgcam/mostasquare_1.jpg" border="1" name="refresh" id="img1">
<IMG src="imgcam/mriehelbypass_1.jpg" border="1" name="refresh" id="img2">
<SCRIPT language="JavaScript" type="text/javascript">
var t = 35 // Interval in Seconds
images = new Array('../imgcam/mostasquare_1.jpg','../imgcam/mriehelbypass_1.jpg'); //URLs of the Images
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime();
for (i=1;i<image.length;i++){
document.getElementById("img"+i).src = images[i]+tmp;
}
setTimeout("Start()", t*1000)
}
Start();
</SCRIPT>
And solely this works great,
But, here is the catch:
I also would like to force the browser to refresh/download all images when opening the page.
so therefor I appended a querystring with a random number (or time, or version, etc).
so that resulted in:
<img src="mostasquare_1.jpg80123123" alt="image1" />
However,
because I added the random number, the array has got the wrong values
how can I tackle this specific "catch22" problem?
bonus points: i'd also like to show a little text on top of the image(s) (floating with css or so?) which shows when the last refresh of the image took place.
Here you can find an example using jquery: http://codepen.io/anon/pen/waGbQg
You can keep original path inside a data-attribute and update src starting from it in this way:
$this.attr("src", $this.attr("data-original-image") + "?" + d.getTime());

How to Return a View from a Controller to an iFrame

I am new to MVC 3 and have come accross the following scenario:
First let me explain how I have setup my application:
All post backs to the server use jquery ajax which which return a view from the controller that either appended or prepended or replace a targeted div.
The Scenario:
I have come to a point where I would like to upload images but unfortunately because of the jquery ajax posting I cannot get the values for an html in C# Request.Files. I know there are plugins out there to help out with this but I would like to do this myself so I have created an <iframe> which i then use a bit of javascript and post the form targeted to the iframe (old classic way of doing things):
function UploadImg(SACTION) {
alert(SACTION);
validatorform.action = SACTION;
validatorform.target = "fraImage";
validatorform.method = "POST";
validatorform.submit();
}
the SACTION parameter looks like this #Url.Action("UploadFile", "Response"). This all works well as it hits the controllers action method and I can then save the image:
[HttpPost]
public ActionResult UploadFile(string ArticleID)
{
ViewBag.PreviewImage = cFileUploads.UploadFile(ArticleID, Request.Files[0]);
return View("ImagePreview");
}
I would now like to return a view to the iframe (simply to preview the image and then do a couple of other things but this is besides the point)
The View for previewing the Image:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="">
<img alt="" src="#ViewBag.PreviewImage" />
</form>
</body>
</html>
The Problem:
Unfortunately when I return the View (ImagePreview.cshtml) in C# the whole page is refreshed, all I want is for the iFrame to be refreshed. How should I return the view from the controller?
Fiqured out the problem, I had a bit of javascript that was replacing the contents of a div that the iframe was sitting in ... (slap on my forehead). All working perfectly now :)
Will leave this question here just incase ..

How to manipulate the ajax response text

I've an ajax code like this:
var req = new XMLHttpRequest();
req.open('GET', 'http://www.example.org/', false);
req.send(null);
if(req.status == 200)
var response = http_attendance.responseText;
document.getElementById('divAttendance').innerHTML = response;
When I get result on the page, FF browser shows the DOM elements on 'divAttendance'. If I want to put put some jquery effect on the result, I can't be able to do it.
DOM elements is clearly viewed using firebug. But, when I generate the source code of that page then there is no repsonse text on 'divAttendance'. It is blank like thisL:
<html>
....
..
<div id="divAttendance"></div>
..
..
</html>
How to manipulate or put some effect on that result ???
Well, if you are using jQuery then you should be using jquery ajax anyways
http://api.jquery.com/jQuery.ajax/
Regardless, if you are populating your div with AJAX response then it will not show up using "View Source" rather you will have to use a tool like firebug.
Your div initially should look like following
<div id="divAttendance" style="display:none"></div>
and your javascript should have the following
.....
document.getElementById('divAttendance').innerHTML = response;
$("#divAttendance").show("slow");
For such operations jQuery load is easy and usefull function, have a look at
http://api.jquery.com/load/
Your specific example can be rewritten as
<html>
....
IMPORT JQUERY.JS
<script language="javascript">
$('#divAttendance').load('http://www.example.org/', function() {
$("#divAttendance").show("slow");
});
</script>
..
<div id="divAttendance" style="display:none"></div>
..
..
</html>

Running a function in a jQuery implicit context

My html document looks like this:
<html>
<head> .. load jquery and other stuff </head>
<body>
<div id="cool_container">
<div class="cool">.. no script friendly markup ..</div>
</div>
<a id="cool_link">Link</a>
<script>
function installStuff(){
$('.cool').coolPlugin();
$('#cool_link').click(function(){
$('#cool_container').load('/anothercooldiv.html');
});
}
$(document).load(function(){ installStuff(); });
</script>
</body>
</html>
Of course, /anothercooldiv.html gives another <div class="cool"> .. etc ...</div> fragment.
So what's the best way to turn the fresh cool div into a coolPlugin without breaking everything (and writing some nasty hacks) ?
It'd would be great to be able to either:
Call installStuff with a default jQuery context '#cool_container', so I could call something like:
$.doThisInContext(function(){installStuff();}, $('#cool_container');
In the load callback.
Or, have an equivalent of 'live' (that would solve the problem of links if cool contains links), but on an element existence, that I could use like that in my function installStuff:
$('.cool').exists(function(what){ what.coolPlugin() };
Then the coolPlugin would be installed on all cool elements now and in the future.
I'd suggest the .livequery() plugin for this still:
$(function() {
$('.cool').livequery(function() {
$(this).coolPlugin();
});
$('#cool_link').click(function(){
$('#cool_container').load('/anothercooldiv.html');
});
});
The important bit:
$('.cool').livequery(function() {
$(this).coolPlugin();
});
Will run for every current and future .cool element as they're added, running the plugin on each.
Applying the plugin to the newly ajax loaded content shouldn't be too tricky:
$('#cool_container').load('/anothercooldiv.html', function() {
$(this).coolPlugin();
});

Resources