get_file_contents refresh div - php

I loaded a content into a div using php get_file_contents,
now i want to refresh it using ajax but i can't figure how to do it.
Sample code:
<script>
function refreshmydiv(){
...
}
</script>
<div id="mydiv"> <? echo nl2br(htmlspecialchars($myfile)); ?> <div>
Refresh My Div

So, here is one way of doing it. First, the parts:
myrefreshfunction
This function needs to make an AJAX call to refresh.php or another page. Then, it should replace the contents of mydiv with the html that is sent back.
refresh.php
This page needs to return the HTML for the div. It doesn't need to return the whole page, it only needs to return the contents of the div.
In this case, it would just echo get_file_contents and nothing else.
ex.
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Then, the refresh process looks like this:
Your user presses the button to refresh the div.
Your function requests a page.
The page returns ONLY the contents of the div.
Your function replaces the content of the div with the page it just requested.
There are other ways to do this, put this is a very straightforward way to do it.
If you use jQuery, your myrefreshfunction is basically one line of code:
$('mydiv').load('refresh.php');

If you use the Prototype JavaScript framework you can do it this way:
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function refreshmydiv() {
new Ajax.Request('/ajax/getdivcontents.php', {
method: 'post' ,
onSuccess: function(request) {
$('mydiv').update(request.responseText);
}
});
}
</script>
<div id="mydiv"> <? echo nl2br(htmlspecialchars($myfile)); ?> <div>
Refresh My Div
This will make an Ajax call when you click on the "Refresh My Div" link. The getdivcontents.php page will create the HTML you wish to display.

Related

Jquery refresh div

I've got a certain php code in a div which gets data from mysql.I want this div to refresh every minute without refreshing the entire page.
Currently I'm using this, doesn't work well
<div id="abc">
<?php
?>
</div>
window.setTimeout('location.reload()', 60000);
The ideal way to do this is to use jQuery.ajax to retrieve data from your server, and then use JavaScript/jQuery within your success function to update your page.
You can still use setTimeout or equivalent to periodically issue AJAX requests.
As you want to refresh the div content every minute you need to look at setInterval method and load of jQuery:
window.setInterval(function(){
$('#abc').load('PHPFile.php');
}, 1000);
and your PHP script mentioned in the url part of the load method must be capable to provide the result in HTML format which is going to be placed in the given div (id:abc)
Have the PHP-code on another page (for example; loaddata.php) and have a jQuery timer executing a function which loads the page loaddata.php
Loaddata.php
<?php
echo "Hello World!";
?>
index.php
<div id="data"></div>
<script>
$('#div').load("loaddata.php", function() {
window.setInterval("loadData", 60000);
});
function loadData()
{
$('#div').load("loaddata.php");
}
</script>
Something like this:
function refreshContent() {
$.post(urlHere, { data here...}, success(data) {
//...manipulate DOM here...
}
}
setTimeout(refreshContent, 60000);
Example of jQuery Ajax
file1.php
<?php
echo 'PHP content e.g. from database based on submitted request - '.$_POST['my-value'];
?>
file2.html
<div class="content"></div>
Refresh div
<script>
$(function(){
$(".reload-data").click(function(){
$.post("file1.php", {my-value: "something"}, function(data){
$(".content").html(data);
});
});
});
setTimeout(function(){$(".reload-data").click();}, 60000);
</script>
For these situations I sometimes use jQuery.load()
Example from documentation:
<div id="result"></div>
<script type="text/javascript">
function refreshDiv() {
$('#result').load('ajax/test.html #container', function(){ /* callback code here */ });
}
setInterval(refreshDiv, 10000);
</script>
This does the following:
Checks if the #result element is in the current page
If it is, it makes a request to the ajax/test.html page
Grabs the #container from the response, and dumps it into #result
And it does this every 10 seconds
That's about it. One line of code, although not as efficient as a true ajax request, it does the job.

Can I store the whole content of a required file in a JavaScript variable?

This seems like an odd problem. Maybe it's also the wrong approach. But I have to do this:
there are a few menu items on a page
the content for each page is stored in some .phtml files
when the page loads the default content is displayed (using require)
all other content should be loaded too and should be stored in a JavaScript-array
when a user clicks a link, the content is swapped
The problem is:
AJAX should not be used
all content can't be appended in the beginning, for the good old SEO
All parts are easy, except for: How do I get the content into a JavaScript array. Something like content.push('<?php print require 'page.phtml'; ?>'); won't work of course, because it will return a multi line string, which does not work with JavaScript. All ideas are welcome. Maybe I'm overlooking something very simple.
<script>
<?php
ob_start();
require 'page.phtml';
$contents = ob_get_clean();
echo "var content = ".json_encode($contents);
?>
</script>
if there is no php code in your page.phtml file you can make it even easier
<script>
<?php
echo "var content = ".json_encode(file_get_contents('page.phtml'));
?>
</script>
obviously you can use it in this way too:
echo "content.push(".json_encode($contents).");";
why not function
<?php
function json_require($filepath) {
ob_start();
require($filepath);
return json_encode(ob_get_clean());
}
?>
...
content.push(<?=json_require('page_1.phtml');?>);
content.push(<?=json_require('page_2.phtml');?>);
content.push(<?=json_require('page_3.phtml');?>);
content.push(<?=json_require('page_4.phtml');?>);
you can use hidden divs than using js array, At the end of the your page so they wont effect the seo. Then use these divs id to swap your content.
I hope you are using jQuery if not this can be done even with simple js.
let me elaborate
<script>
function shouldBeCalledAtSomeEvent(page_id)
{
var html = $('#'+page_id+').html();
$('#idOfYourTargetElem').html(html)
}
</script>
<!-- end of your main file -->
<div style="display:none" id="page_1">
include('page_1.phtml');
</div>
<div style="display:none" id="page_2">
include('page_2.phtml');
</div>
<div style="display:none" id="page_3">
include('page_3.phtml');
</div>
If you can't use ajax and you're worried about seo, I recommend you use a modified version of #rupesh answer: store the html in script tags so that they can be accessed by js and not be read by crawlers :
<script type="text/hidden-menu" class="hidden_menu" >
include('page_1.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
include('page_2.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
include('page_3.phtml');
</script>
And then you can easily build your array in js :
var content = [],
contentNodes = document.getElementsByClassName('hidden_menu'),
i=0;
for(;i<contentNodes.length;i++)
content.push(contentNodes[i].innerHTML);
And voila: you have your content array that holds the html sent from php without using ajax and without affecting seo.

php ajax refresh part of page on click

I want to be able to click on a link lower down my PHP page, it send a variable and outputs the result in a <div> tag at the top half of the page.
I've linked to latest jquery, and so far I have this in my <head>:
<script type="text/javascript">
$().ready(function() {
$("#result").load("crimes_result.php");
});
</script>
And in my <body>:
<div id="result"></div>
What I need though, is that the div to be shown and depending on the result of a variable sent by a link the user clicks lower down the page.
like crimes_result.php?id=4334 or crimes_result.php?id=54543
How can I finish my script so it does that?
NOTE: I'm useless in ajax/jquery/javascript
If I understand correctly, simply call .load() from a click event and pass it the href of the link:
HTML:
<a class="loadlink" href="crimes_result.php?id=4334">Click Me<a>
JS:
$(".loadlink").click( function(event) {
event.preventDefault();
$("#result").load($(this).attr("href"));
});
Example: http://jsfiddle.net/jtbowden/ueucL/1/

Refresh single page PHP element using button

I have a single page quote generator, it works by holding the quotes in a 2D array and generating a random number to pull from the matching value in the array using PHP every time that the page is refreshed, I want to change this and make it so that only the element is changed when you press a button, reducing the http requests to the server.
I have tried various "onClick" methods but they never seem to work, I'm assuming that this is something that I should use Javascript (Or any js libraries) for. The function that I want to run when the button is pressed is this:
<?php
$max = max(array_map('count', $arrCSV));
$num = rand(0,$max);
$quote = $arrCSV[0][$num] . "." ;
echo $quote;
?>
Any help is much, much appreciated.
Like, #Dr.Kameleon, this cannot be done with PHP alone.
Using jQuery, you can reload an element like this
$("#yourdiv").load("the/page/from/where/it/should/be/updated.php");
Attach it to the click event of the button
$("button").click(function() {
$("#yourdiv").load("the/page/from/where/it/should/be/updated.php");
});
JQuery's load method could do miracles there.
Here some working example.
Create html page:
<html>
<head>
<title>JS-ajax-PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
// Let's use jQuery library:
$(document).ready(function() {
// get element with id refresh, on click do function...
$('#refresh').click(function(evt){
// get element with id report, load content to element
$('#report').load('/time.php');
evt.preventDefault();
})
});
</script>
</head>
<body>
<button id="refresh">Обновить</button>
<div id="report"> </div>
</body>
</html>
and php file time.php:
<?php
echo date("Y-m-d H:i:s");
Enjoy.

Open a url, in jquery php

when I click on "Click Here" then a page must open inside
<script....>
$('yahoo').html('<a href=desc.php>');
</script>
<div id='yahoo'></div>
<div id='clickhere'>Click here</div>
Thanks
Dave
I think you're looking for AJAX to fetch the page for you. Something like this might work:
<script type="text/javascript">
$(function() {
$('#clickhere').click(function() {
$('#yahoo').load('desc.php');
});
});
</script>
<div id='yahoo'></div>
<div id='clickhere'>Click here</div>
First you need to wrap the script inside $(function() { ... }) to execute your code on page load. This is equivalent to $(document).ready(function() { ... }).
Next you have to bind a click event to the #clickhere element so you can actually do something when the user clicks on it.
When the user clicks on the #clickhere div, load() will fetch the contents of the given url inside the element you call it from. So, this snippet means that when the #clickhere div is clicked, desc.php is loaded inside #yahoo div.
ID selector is #ID, not just ID
Use jQuery AJAX load method to load desc.php page
You should execute your jQuery code after DOMContentLoaded event
Wrap your code in $(document).ready(function() { });, which will insure that the code executes after the DOM is available to your code. Otherwise, $('yahoo') will likely return no matched elements.
Why not try target_self ? I also fixed some code
<script....>
$('yahoo').html('<a href=desc.php target='>self'>Click here</a>');
</script>
<div id='yahoo'></div>
<div id='clickhere'>Click here</div>

Categories