Auto refreshing div with javascript - javascript

Trying to refresh a div every 60 seconds, using the following javascript:
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load').fadeOut('slow').load('index.html #load').fadeIn("slow");
}, 60000);
</script>
Here is the corresponding div:
<div class = "well" id="load">
<center><h3><i class="icon-bar-chart"></i> Mt.Gox</h3></center>
<center><h3>Ƀ1 = <?php echo $usd; ?> USD</h3></center>
<hr>
<center><h3><i class="icon-bar-chart"></i> BTC-e</h3></center>
<center><h3>Ƀ1 = <?php echo $usde; ?> USD</h3></center>
</div>
The div is currently not refreshing at all.
Thanks for any help!

Ok that's because you are using the script incorrectly., You need to use callbacks as below
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load').fadeOut('slow',$(this).load('index.html #load',
function(){
$(this).fadeIn("slow");
})
)
}, 60000);
</script>

Edit: I misunderstood the code a bit so ignore my original comment below!
Try to remove the #load in the url. It's perfectly valid according to the jQuery API, but I think in this case it can cause reduncancy.
That is, make it like this instead:
$('#load').fadeOut('slow').load('index.html').fadeIn("slow");
When you call .load() on an element it will load into that element, if you also specify the same element in the Url to load - I think it can cause a problem.

Please see this link: Origin null is not allowed by Access-Control-Allow-Origin
Also that issue, I think that you shouldn't load html data via file:/// URL. Why don't you load a div in the same file. Forexample:
$('#load').fadeOut('slow').load($('#test').css('display', 'inline')).fadeIn("slow");
and the div tag is like this:
div id="test" style="display:none;"

Related

Second button doesn't produce form in same div as first button

I have a php page with two divs. In the first div, users click a button and it brings up a form in the second div. When they submit the form, both divs refresh. All is great. But I want to add a second button to the first div to bring up a different form in the second div. I haven't been able to get this to work, either the first button stops working or the second one doesn't work. I tried making the second button a div and calling it by its ID and that didn't work. I'm an amateur and don't understand jquery very well (I think this is jquery anyway) and this is just for a project for some friends and I, so any help would be appreciated. I may just not be understanding how this works.
<script>
$(document).ready(function () {
$("button").click(function () {
var handle = "<?php echo $_SESSION['name'] ?>";
$("#infoblock").load("createhandle.html");
});
});
</script>
<div id="div1">
<button id="reservename">Reserve A Name</button>
</div>
<div id="div2"></div>
I found a solution here: https://stackoverflow.com/a/20074373/9157720
It ended up being an issue with syntax and using a pound symbol. This is the code that worked in case anyone else has this problem.
<script>
$(document).ready(function(){
var handle = "<?php echo $_SESSION['name'] ?>";
$("#reservename").click(function(){
$("#infoblock").load( "createhandle.html");
});
$("#uploadpic").click(function(){
$("#infoblock").load("uploadpic.html");
});
});
</script>
<button id="reservename">Reserve A Name</button>
<button id="uploadpic">Upload A Picture</button>
Consider the following.
<script>
$(document).ready(function () {
$("button").click(function () {
var handle = $(this).data("ref");
var target = $(this).data("target");
$(target).load("createhandle.html?handle=" + handle);
});
});
</script>
<div id="div1">
<button data-ref="<?php echo $_SESSION['nameA']; ?>" data-target="#infoblock">Reserve A Name</button>
<button data-ref="<?php echo $_SESSION['nameB']; ?>" data-target="#div2">Reserve B Name</button>
</div>
<div id="div2">
</div>
Your example is sort of ambiguous, so I wasn't sure what you were trying to accomplish. It's best to not mix PHP and HTML if you can. You can have a reference point in the HTML so that when you need to load something, in relationship to that button, you can pass that into a stand alone PHP Script and get the HTML you need back with .load().
Remember that PHP is executed before the HTML is presented to the Client. So the Session data must be present in PHP Memory when the page is initially loaded.
Reference:
https://api.jquery.com/data/
https://api.jquery.com/load/
jQuery $(this) keyword

Append <script> into <div> using jquery

I'm trying to append a <script> tag into my <div>. Whenever I try to do this, the script just doesn't loads. But it works if I hard coded it under the tag.
But if I try to append an <img> tag, it works!
Here's a partial code to give you some ideas.
$(document).ready(function() {
var tag = '<script src="xxx.js"></script>'; // file to grab images
var tag2 = '<img src="some image link"></img>';
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
On HTML
<div id="test"></div> <!-- Not Working! -->
<div id="test2"></div> <!-- This Works! -->
<div id="test"><script src="xxx.js file to grab images"></script></div> <!-- This Works too! -->
Edit with more info below:
I've actually looked for solutions over the net and most of the answer are almost the same as the ones given here. In my case, it is slightly different from the others. That's because the tag variable is actually a must from database.
<?
$result = mysql_query("SELECT code FROM users_loc WHERE method='script'") or die(mysql_error());
$row = mysql_fetch_array($result);
?>
and on javascript side:
$(document).ready(function() {
var tag = <? echo $row['code'] ?>;
var tag2 = <? echo $row2['code'] ?>;
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
On my site, users will input their external image source into my database, and I will grab the source and display it on my site. But the problem arise when a user put in a <script> tag which works if it were hard coded into the <div>
I kept having this error message on my console "A call to document.write() from an asynchronously-loaded external script was ignored."
I hope this answers the confusions. Thanks.
Edit: I think this is the problem with append: Does Jquery append() behave asynchronously?
It all because about the parsing problem. The problem showing up after found </script> this code. It's assume we want to close the script tag but we won't. In order to avoid that, put \ before / like so to escape special character :
$(document).ready(function() {
var tag = '<script src="xxx.js"><\/script>'; // file to grab images
var tag2 = '<img src="some image link"></img>';
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
DEMO
Try inspect the element in chrome to see the code.
Try it:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'xxx.js';
$('#test').append(script);
If it matters where in the source order the script tag is injected, Mario Araque's solution is for you. If it does not matter, R3tep's solution does the job nicely.

modifying main view from inside partial view

I have a main view that let's say has the following:
<div id='test'>Some Text</div>
<div id='placeholder'></div>
then using ajax I'm replacing the contents of 'placeholder' with a partial view that looks like this:
<div id='ajaxContent'>
// new content
</div>
<script>
$(document).ready(function() {
console.log($('#test').text());
$('#test').css('color','red');
});
</script>
so in my script I'm trying to change the color of the text in div 'test' to red, but I keep getting 'undefined' in the console. How do I access the test div in the main view from the partial view coming into the main view through ajax?
If they're ending up on the same page, shouldn't the html elements be able to see each other?
Your JavaScript fragment is simply removed by jQuery on html(...) call. A similar issue can be found here: jQuery .load() / .ajax() not executing javascript in returned HTML after appended
Thus, you have to insert partial data in this manner (assuming you have your partial respone in result variable):
$(result).find('#ajaxContent').appendTo('#placeholder');
$(result).find('script').appendTo('#placeholder');
Also, as #RolandBertolom said before, you don't need ready() in your partial response in JavaScript.
You actually do not need to use $(document).ready. It's just useless. But it shouldn't break anything. As well as you can access any element on the page from script inserted anywhere in the same document. So problem is somewhere out your question's scope.
Try:
run $('#test').text() from console.
replace $('#test').text() with $('body') or something else in your script.
...
Be deductive when you debugging! ;-)
you should not be using $(document).ready again because you document will already loaded with main page so again using it wont help.
try like this:
suppose this is your test.php:
<script>
jQuery(document).ready(function() {
$.ajax({
type:'post',
url:'submit.php',
success:function(data) {
$('#placeholder').append(data);
}
});
});
</script>
<div id='test'>Some Text</div>
<div id='placeholder'></div>
//this is your submit.php the content to replace
<?php
echo "<div id='ajaxContent'>
</div>
<script>
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
</script>";
?>
NOTE: what i exactly mean here is use:
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
in script.

External POST form through iframe

I'm trying to get a page which includes a POST form to load inside an iframe for users to be able to confirm an action such as deleting a listing. I have successfully got the JS and the form page to load inside the iframe, but when I click an action inside the form, it's not updating the listing. Instead, it just refreshes the page.
The form is working fine because if I try to access the content-url manually in the browser and update the form, it works fine.
How can I get the iframe content to refresh instead of the parent page and load the response inside the iframe itself? What I am doing wrong exactly?
Any help is appreciated!!
Here's my code:
HTML:
<button class="myclass" content-url="<?php bloginfo('siteurl') ?>/?a_action=delete_auction&pid=<?php the_ID(); ?>">Delete Me</button>
<div class="popup"><iframe id="mynewiframeid" name="myframename" src=""></iframe></div>
JS:
$(document).ready(function() {
$(document).click(function(e) {
if ($(".popup").is(":visible")) {
$(".popup").fadeOut("fast")
}
});
$(".myclass").click(function() {
if (!$(".popup").is(":visible")) {
$('#mynewiframeid').attr('src',$(this).attr('content-url'));
$(".popup").fadeIn("slow");
}
return false;
});
$(".popup").click(function(e) {
e.stopPropagation()
})
});
Form:
<div class="popup_content">
<h3> You are about to delete <b><?php echo $title; ?></b>!</h3>
<?php
if(isset($_POST['yes_confirm']))
{
$s = "update ".$wpdb->prefix."posts set post_status='trash' where id='$pid'";
$wpdb->query($s);
echo '<div class="deleted_item_ok">';
printf(__('Your item has been deleted successfully!'));
echo '</div>';
}
else
{
?>
<form method="post">
<div class="are_you_sure_delete">
<?php
_e('Are you sure you want to delete this item?');
?>
</div>
<button class="button-small button-w-green" type="submit" id="submits" name="yes_confirm">Yes, Delete</button>
<button class="button-small button-w-red" type="submit" id="submits" name="no_confirm">No!</button>
</form>
<?php } ?>
</div>
You are trying to replace html in the class "popup" with following js code..
HTML => <div class="popup"><iframe id="iframeid" src=""></iframe></div>
JS => $('.popup').html(response);
This replaces the iframe element in the HTML above with the response..! Therefore after response comes, no iframes inside the page..
If you do want to use an iframe, I don't think you have to deal with AJAX. Instead just change the src of iframe. You may use following js code..
$(document).ready(function() {
$(document).click(function(e) {
if ($(".popup").is(":visible")) {
$(".popup").fadeOut("fast")
}
});
$(".myclass").click(function() {
if (!$(".popup").is(":visible")) {
$('#iframeid').attr('src',$(this).attr('content-url'));
$(".popup").fadeIn("slow");
}
return false;
});
$(".popup").click(function(e) {
e.stopPropagation()
})
});
Fiddle (with fake src urls)
First of all, correct the following errors and then see if it works:
in your you are missing semicolon after the closing parenthesis
you close the php tags and right after you continue with url and then you add another closing php tags
What you are looking for is this inside your content-url:
<?php bloginfo('siteurl') . '/?a_action=delete_auction&pid=' . $the_ID; ?>
What is the_ID()? I dont see that function. And if exists it has to return the value that you will store in variable $the_ID. You also have to call that function before button tag to get that variable.
In your JS you need to wrap everything in $(document).ready(function() {}
It seems you are trying to do GET request and not POST request since you are not sending any data in the body but in the url
Missing semicolon at the end of first .click function
I didn't even look at all other .click functions cause there's some repetitions going on and more weird stuff

How to use .load() for refresh div in same page?

I am trying to make an on-line user content which refresh it self and calls every time php function.
I used
<div class="onlineFriends">
<?php
$members = find_online_friends($_SESSION['id']);
foreach($members as $member):?>
<div class="user" href=<?php echo ($member['f_id']); ?> rel="popup_name" >
<img src=<?php
$avatars = find_avatar($member['f_id']);
foreach($avatars as $avatar)
echo ($avatar['src']) ?>
/>
</div>
<?php endforeach; ?>
</div>
<script>
$(function(){
var refreshId = setInterval(function() {
$('.onlineFriends ').load("# .onlineFriends ").fadeOut("slow", function () {
$(this).fadeIn("slow");
});
}, 50000);
});
</script>
This works good. But .load() function I think loads first all entire page and then calls .onlineFriends. I can see it with firebug on console. it returns all page source code as GET answer. My question is it will make slow down ? Because I will use this method 5 times for other div contents and each time each functions will load full page.
Also I tried to create separate .php file but I have in php code some dependences and I cant run this function in another file.
Any request to your page will result to it's full code. You can specify in php to send back only wanted part of page when specific GET or POST data is present and use $.get() or $.post() to get them.
Because I will use this method 5 times
On the same page? Then it's better to replace them from the one of $.get() and $.post() data during callback function.
Create other page friends.php
and in page index use cod java/ajax and use jquery-min
<script src="js/jquery-1.10.1.min.js"></script>
$(document).ready(function() {
$("#center").load("friends.php?var=<?php echo $member['f_id']; ?>");
var refreshId = setInterval(function() {
$("#center").load('friends.php?var=<?php echo $member['f_id']; ?>');}, 9000);
$.ajaxSetup({ cache: false });
your div html use
<div class="center"></div>
your friends.php use
<?php include"your bd here" $jab = $_GET['var'];
'select bd'
echo $resultyourneed['f_id'] ?>

Categories