Refresh div which includes sprintf - javascript

I have two php files. The first is named index.php, the second one is named data.php. I tried to get the contents from the file data.php into index.php. Initially it gave me an error using the include_once statement but I now got it to work with:
<?php $str = sprintf(include_once ("/www/index1.php"));
echo $str; ?>
Now, I want this part to refresh every minute without reloading the complete page.
I tried inserting into index.php the following:
<!-- Div refresh function -->
<script type="text/javascript">
var auto_refresh = setInterval(
(function () {
$("#data").load("/www/data.php"); //Load the content into the div
}), 60000);
</script>
<div id="data"><?php $str = sprintf(include_once ("/www/data.php"));
echo $str; ?></div>
I admit, it looks a bit wrong and guess what, it doesn't work. I this is because it tries to load data.php in de script-part and afterwards I try to include the file again in the < div>-statement. I can't get it to work.
I have looked a various examples but can't find any using the sprintf function. I must admit that my knowledge of java, ajax and or json is not great.
Hope someone can help!

Javascript is a front end script. If you want to load something via ajax, you should know its based on js. While js is based on web browser. So make sure you can access that url from browser first.
You can access /www/data.php from php, but if you want to load it in js, make sure it can be visit from web first. How can you visit your index.php?
If you can visit index.php via http://xx.com/index.php, then change $("#data").load("/www/data.php"); to $("#data").load("http://xx.com/data.php");, you will find it works.
Update: Based on your comment, try $("#data").load("data.php");
Also, you can use developer tools to debug it. If js gets error, you will see it.

You're doing something wrong.
What you need to do:
Create file with needful data (for example data.php).
Create file for loading data-file (for example loader.php). If you are using php (I see you are), you can file_get_contents for data.php and then echo it.
On page, where you want to get your data, use something like this:
JS:
function loadData() {
$("#data-container").load("loader.php", function() {
console.log("Load was performed.");
});
}
loadData(); // load first then refreshing every 1 min:
setInterval(loadData, 60000);
HTML:
<div id="data-container"></div>
So, what all of this doing here?
First, script on your page create request to loader.php;
Second, loader.php executes (I hope your server execute php, huh?) and get content of data.php (so in this context data.php can have any file name extention; data.txt, data.log, etc); then it echo that content;
Third, script on your page get echoed (by loader.php) content of data.php and paste it in your #data-container.
These steps repeat again every 1 min.
Note: If data.php in your context is not a programming code (just some data), you can create just data.html and load it directly in jQuery script. It's not need any php-loader files, etc.

Related

AJAX - Refresh DIV in PHP include every second - not working

So I have a DIV that is located in a PHP include file. All I am trying to do is refresh this DIV to show updated content every second (I realize this would be alot, just using 1 second for testing purposes). However, it does not work and I cant figure out why.
I am testing by simply updating the "My Content" text and saving it... nothing changes. Can't figure out what is wrong.
JAVASCRIPT
<script type="text/javascript">
function ajaxCall() {
jQuery.get("<?php echo get_template_directory() . '/inc/order-status-desktop.php' ;?>", function(data) {
jQuery(".ajax-status").html(data);
});
};
// Execute ajax call every 5 seconds
setInterval(function() {
ajaxCall();
},1000);
</script>
HTML in the PHP include file
<div class="ajax-status">
My content
</div>

JSON output on HTML page

I want to display a JSON object on a html page. When I enter
productArray[0][0].xyz
into the Firefox console then I get a value back.
Question:
How can I display the value which is stored in this variable on a HTML page?
I have tried this (didn't work):
<div id="test">
<script>
window.onload = function()
{
var out = productArray[0][0].xyz;
document.getElementById("test").innerHTML = out;
}
</script>
Since it's working in console in browser, I guess it's a timing problem. You're probably trying to use the value in the json before the json data is loaded and ready to use.
Assuming you're running an xhttp request or ajax call or something you'll have to run the code AFTER data is loaded. Which often means running it inside successmethod.
Maybe this post and answer helps you locate the problem? NB: This uses Ajax, so feel free to update your post with some more information so we can help you with your solution / technologies.
Ajax success function
Assuming that missing div close tag is a typo most probably the productArray is not populated by the time your code executes. Can you post a more detailed snippet ?
var out = "your value";//productArray[0][0].xyz commented to show you running code uncomment it when you use this in you code. ;
document.getElementById("test").innerHTML = out;
<div id='test'></div>
You actually forgot to close the DIV tag.

Javascript not working when echo'd by php

I have the problem when i echo this:
echo "Logged in! <script> alert('hello'); </script>";
The message "Logged in!" appears, but not the alert. How can i fix it so i get the alert? I can't use header(); because i already echod things out!
I also tried multiple thing like:
echo "Test message <script> window.location.href = 'index.php';"
Same thing again, Test message was echo'd, but the script wasn't run.
I hope someone can help me!
Edit:
NOTE: All of this code is in a xml file that i get that response of and put that in a div. So the script is in a message that i get with responseXML and output the data in a div.
Question i have in 1 sentence: How can you run a javascript function in a ajax call without jquery?
I'm guessing you call this script through ajax after the page is already loaded. In this case it's not surprising the script isn't running because the browser runs the scripts as it reads them and isn't on standby for another script tag to appear.
If this is the case, you can solve this by adding some event listener or even better, call a desired function in the end of the ajax response.
Your PHP looks fine, but you might need to change the way that you collect the JavaScript.
Consider this example:
http://jsfiddle.net/0vcewvkc/1/
If you are collecting JavaScript only, you can wrap the response in a jQuery tag ($()), and then append it to your document.
$("#go").click(function() { // call the function here
// your ajax code would go here, but either way you will end up with a string of JavaScript
var response = '<script>alert("hi");</' + 'script>';
// use jQuery to append this script to your document's body, like so:
$(response).appendTo(document.body)
});
Update
To do this without jQuery, the end of your AJAX call would have this code:
var response = 'alert("hi");'; // note that we have removed the <script> tag
var s = document.createElement("script");
s.innerHTML = response;
document.getElementsByTagName('body')[0].appendChild(s);
try the following this should work
<?php
echo 'Logged in ';
?>
<script> alert("hello")</script>;
<?php
// the rest of your php code
?>

Php includes and js scripts position

I bought a theme where pages were all HTML with JS scripts loaded at the bottom. I modified the theme and now have PHP files with the following (quite standard, with php includes to load the required content) :
index.php
header.php
menu.php
footer.php
content1.php
content2.php
content3.php
...
All the scripts are still loaded at the end, in footer.php.
My problem lies in the fact that in each content pages I need specific scripts, for exemple content1.php needs script1.js, content2.php needs script2.js...
Here is where I have trouble understanding the proper way of doing it :
I could load all scripts (script1.js, script2,js and script3.js) in the footer therefore whichever content is loaded, the required script will be loaded anyway. But I end up loading scripts that are not being used.
For example, I have a script that generates and displays a table from a json array (which is generated using php and a mysql query). This table is only displayed in content1.php.
I don't want to load this script in the footer as it will then be executed each time a page is displayed even if we don't need it. And I can't include it in content1.php as it requires other scripts (jQuery) which is loaded in the footer, ie. after the php include itself.
Does that make sense ?
Use PHP conditionals (either an if/else or switch, which might be better) to check the URL value and load the appropriate scripts for the page in header.php. Very rough example below.
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'content1') !== FALSE) {
echo '<script src="script1.js"></script>';
}
elseif (strpos($url,'content2') !== FALSE) {
echo '<script src="script2.js"></script>';
}
Why not load the ones you need more often in the header file i.e. jquery and call the optional files at the bottom of the page where they needed, there by removing all calls from the footer
You may be better off combining the files and including the new file in the footer. One file would result in fewer requests, but keep an eye on the file size.
Done a small thing few years ago as follows:
<?php
if(getPageJsname()!='') {
?>
<script type="text/javascript" src="jquery-code-<?php echo getPageJsname(); ?>.js"></script>
<?php
}
?>
function getPageJsname() {
return $scriptname = trim($_SERVER['SCRIPT_NAME'], "/");
}
After this you can rename all the javascript files as follows:
for page content1.php js name will be jquery-code-content1.js
and vice-versa
See if this help with something
Take this out of the footer:
<script></script>
</body>
</html>
And put it in each page accordingly.
in content1.php create a var
$script='script1.js';
the same in content2.php
$script='script2.js';
and content3.php
$script='script3.js';
finally in footer.php
echo '<script src="'.$script.'"></script>';
Well, easiest and obvious solution would be to load jQuery before content blocks start. While it is recommended and good to include scripts at the bottom, it's not that of a cornerstone. It is also recommended to combine and compress your JS, so you can generate one compressed JS for all your pages.
But you can also try to load scripts via AJAX after document is rendered. There is http://api.jquery.com/jQuery.getScript/
And you know what content is loaded by that point.
$(document).ready(function() {
if ($("#content1").length > 0) { ... }
});
You can also try to wrap your code in function to postpone it's execution untill jQuery is also loaded.

Javascript Document.write Issue

I'm trying to get the lines of code below to help me write "<?php include('like.php'); ?>" on a page only when the visitor isn't using a a mobile device but it doesn't seem to be working. Any ideas on how to get it to work?
<script type="text/javascript">
<!--
if (screen.width > 699 {
document.write("<?php include('like.php'); ?>")
}
//-->
</script>
By the time JavaScript is writing to the document, it's too late - PHP has already sent everything to the browser. Your next best approach would be to make an AJAX call to fetch the content and append it to the DOM.
Assuming you're willing to use a JavaScript framework like jQuery, it's quite simple:
if (screen.width > 699) {
$.ajax({
url : '/like.php',
dataType : 'html',
success : function(data) {
$('#myContainer').html(data);
}
});
}
http://api.jquery.com/jQuery.ajax/
As others have mentioned, you can not have JavaScript include a piece of PHP-code and have it executed. As PHP is run server-side, before the page is served to the client, injecting the code like you suggest would just write <?php include('like.php'); ?> as plain text to the document.
You could however load the content of like.php through Ajax and inject it into the DOM, if a certain criteria is met.
With a library like jQuery, it is quite easy, as it provide a method .load() that let you load content into the DOM like that. You could do it something like this:
// Wait for the DOM to be ready
$(function () {
// Check the width of the screen
if (screen.width > 699) {
// Load the content and add the HTML to an element
$('#id-of-element-to-add-content-to').load('like.php');
}
});
In the above example, the content of like.php will be loaded into the HTML-element with id id-of-element-to-add-content-to, but you could use any selector you like, that match your need. If you want to replace the entire body of the page, your could do $('body').load('like.php'); instead.
More about the available jQuery selectors: http://api.jquery.com/category/selectors/
javascript executes on the browser and php executes on the server so, you need to add an if condition and then include
you could test the user agent server side and append that line if not from a mobile device

Categories

Resources