I have two files home.php and calc.php, the file calc.php has variables parsing from XML URL and this url data keep changing automatically but the problem is i need a specific element in this home.php keep refreshing automatically
as you see in my code there is a div has alink inside it and the link has php variable $amount and this var keep updating,
so i tried to use AJAX like this but it did not work and after 1 s the link disapear So what to do please?
THANKS
var auto_refresh = setInterval(
function () {
$('#low2z3').load('calc.php'});
}, 1000);
<div id="linnnez4" class="linnne res1"><a id="low2z3"><?php echo $amount1;?></a> </div>
<!--in calc.php-->
<?php
$url = 'http://magneticexchange.com/export.xml';
$xml = simplexml_load_file($url);
foreach($xml->item as $item) {
if($item->from == "PRUSD" && $item->to == "NTLRUSD") {
$give = $item->in;
$get = $item->out;
$amount = 10;
$give1 = $amount." ".$item->from;
$get1 = $amount * $get / $give;
$get2 = number_format($get1, 2). " ".$item->to;
$amount1 = $item->amount;
break;
}
}
?>
Related
I have a problem displaying PHP echo from jQuery script. The code is displayed but in plain text. I don't want to load it from PHP. I tried to do everything but it had no effect except the one that displays the code as PHP. By adding instead of replace text, HTML only shows quotation marks.
Is there any solution to this?
var currentBackground = 0;
var currentNaglowek = 0;
var currentTekst = 0;
var backgrounds = [];
backgrounds[0] = 'https://via.placeholder.com/1920x360';
backgrounds[1] = 'https://via.placeholder.com/1920x360';
backgrounds[2] = 'https://via.placeholder.com/1920x360';
var naglowek = [];
naglowek[0] = "<?php echo ($language['carousel_header1']); ?>";
naglowek[1] = "<?php echo ($language['carousel_header2']); ?>";
naglowek[2] = "<?php echo ($language['carousel_header3']); ?>";
var tekst = [];
tekst[0] = "<?php echo ($language['carousel_text1']); ?>";
tekst[1] = "<?php echo ($language['carousel_text2']); ?>";
tekst[2] = "<?php echo ($language['carousel_text3']); ?>";
function changeBackground() {
currentBackground++;
currentNaglowek++;
currentTekst++;
if (currentBackground > 2)
currentBackground = 0;
if (currentNaglowek > 2)
currentNaglowek = 0;
if (currentTekst > 2)
currentTekst = 0;
$('#sliderBox ').fadeOut(1500, function() {
$('#sliderTexts').html('<p>"' + naglowek[currentNaglowek] + '"</p>');
$('#sliderTexts').html('<p>"' + tekst[currentTekst] + '"</p>');
$('#sliderBox ').css({
'background-image': "url('" + backgrounds[currentBackground] + "')"
});
$('#sliderBox ').fadeIn(1500);
});
setTimeout(changeBackground, 7000);
}
$(document).ready(function() {
setTimeout(changeBackground, 7000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sliderBox">
<div class="sliderContent">
<div class="container">
<div class="row">
<div class="col-md-8" id="sliderTexts"></div>
</div>
</div>
</div>
</div>
In order to execute PHP, it needs to be in a file that is registered to be passed through PHP by the webserver. Typically this means giving it a .php file extension (and not a .js file extension).
Since PHP will, by default, claim that anything it outputs is HTML, you also need to override that by being explicit about the content-type:
header("Content-Type: text/javascript");
You might also want to explicitly generate caching headers so the JS isn't rerequested with every page load.
You might also consider breaking the file apart and sticking to a traditional static JavaScript program which gets its data from a JSON endpoint via fetch.
I have created an ACF option in the admin so a user can add cookie notice text via the admin...The javascript script I'm using creates the message within the javascript so I'm wanting to echo the ACF field within the javascript.
At the top of my cookie.js file I have: "<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>"; and I'm echoing it within a var like so: var msg = "<?php echo $cookie_msg; ?>"; so the top of my file looks like this:
"<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>";
(function(){
//Change these values
var msg = "<?php echo $cookie_msg; ?>";
var closeBtnMsg = "OK";
var privacyBtnMsg = "Privacy Policy";
var privacyLink = "https://www.google.com";
//check cookies
if(document.cookie){
var cookieString = document.cookie;
var cookieList = cookieString.split(";");
// if cookie named OKCookie is found, return
for(x = 0; x < cookieList.length; x++){
if (cookieList[x].indexOf("OKCookie") != -1){return};
}
}
What I'm getting when I view the site is: <?php echo $cookie_msg; ?> and not the actual message from ACF...is there a way of actually doing this?
Wordpress giving nice function to pass PHP variable data to js file.
Put this code in your theme functions.php page.
function mytheme_load_scripts() {
wp_enqueue_script('mytheme-script', get_template_directory_uri() . '/js/mytheme-script.js');
wp_localize_script('mytheme-script', 'mytheme_script_vars', array(
'alert' => get_field("cookie_notice",$post_id)
)
);
}
add_action('wp_enqueue_scripts', 'mytheme_load_scripts');
And Create one js folder in your theme root directory. Inside that directory create the js file named mytheme-script.js file, & put the below code over there.
jQuery(document).ready(function($) {
alert( mytheme_script_vars.alert );
});
Now visit any page of your site. Surely you will get an alert with the your desire field value. Make sure you will assign proper value to $post_id. I think this will help you. Codex reference link for more details: WP Localize Script Function
I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys.
Objectives:
Retrieve data from database.
Set the value of an element using javascript/jquery (inside a loop) from the database.
Make the value a link
I have this a_link column from links table with the ff. values:
- www.google.com
- https://www.google.com
- www.stackoverflow.com
And here is my code:
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id = "linkhere"></span>
</div>
<script>
var link = "<?php echo $thelink; ?>";
$("#linkhere").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
<?php
}
?>
Any help would be highly appreciated. Thanks.
#aimme is technically not wrong about using a different database library. Please read "Why shouldn't I use mysql_* functions in PHP?" for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)
I think you're trying to:
display a <div> of class 'row'
with an <a> tag inside that uses the 'a_link' column of the 'links' table as the href and the label.
The href for the tag must always have a scheme (http://).
Just PHP and HTML
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$regexMatches = array();
// removed (what seemed to be) needless groups in regex
$urlFound = preg_match("#((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);
if($urlFound === 1) {
// only add http:// if http:// was not detected
$href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php }
}
?>
This code won't echo a row if a_link doesn't contain either 'http://' or 'www.' in it. so google.com will not be displayed.
Of note, as written, the regex will work on "urls" like 'applewww.google.com'. Don't know if that matters. Adding a '^' to the beginning of the regex may solve the problem (like so:preg_match("#^((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);)
A (better|different) solution could use parse_url($url)
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php
}
?>
However, using parse_url() would mean any old string would be displayed (while the first solution would not display any links that didn't have either http:// or www.) but since your pulling from a table called 'links' it's probably safe to assume everything is a valid path.
That's not how it works, that's not how any of this works
Now let's assume that you really need to use Javascript to process your generated links (which is not).
You first need to separate your Javascript code from your PHP code. You will only use Javascript once you have fetched your data and generated some output.
I guess you just want some kind of working code
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink)) :
$link = $rowlink['a_link'];
?>
<div class="row">
</div>
<?php
endwhile;
?>
<script type="text/javascript">
$(function() {
$('.row a').each(function() {
var urlified = urlify($(this).data('url'));
$(this).attr('href', urlified.url)
.text(urlified.label);
});
});
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var label = (c == 'www.') ? 'http://' +url : url;
return {url: url, label: label};
});
}
</script>
First i want to advice that use PDO or mysqli instead of mysql. as it
is vulnerable to sql injection and its depreciated.
"I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys."
for that i would say Php is a server side language whereas javascript is a client side language. and Ajax is the way to manipulate client side from server vice versa, without refreshing the whole page.
below is just a demonstration that i edited little bit from your code to show the separation of server side and client side code and to just give an idea how it works.I don't know whether the code will work or not. haven't tested. php code (server side) will be executed first but could control the display of it using javascript(client side) functions inside document.ready() or window.load() to apply the affects as soon as possible.Through this we could bring changes to the links that we want before its being shown to the client . For each of the link retrieved and displayed you could use a specific class and jquery .each() function to apply certain fix to the selected link as Lyes BEN mentioned above or all the elements with a specific class could be manipulated as a whole without using .each.
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
echo '<div class = "row">
<span id = "linkhere">
</span>
</div>';
}
?>
<script>
$("#linkhere a").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
You can implement this using php with parse_url function (http://php.net/manual/en/function.parse-url.php) to get different components.
In parse_url, there is 'scheme' key for http or https.
Then to do this with php, just call formatUrl function to make the url
<?php
function formatUrl($url)
{
$urlData = parse_url($url);
if(!isset($urlData['scheme'])) {
$url = 'http://' . $url;
}
return '' . $url . '';
}
?>
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id="linkhere"><?php echo formatUrl($thelink)?></span>
</div>
<?php
}
?>
edit: I'm now wondering how I can access post ID from within plugin (outside of loop). If I try to get the post id, it returns 0.
How does one access a specific page's PHP variables within a plugin JS file?
I originally had the JS in the page template file but have moved it to a plugin. Now I am unsure how to access that page's PHP variables. Maybe move the PHP logic to a plugin function?
content-course.php (JS)
<?php
$user_id = get_current_user_id();
$course_id = $post->ID;
$vimeo_progress = 0;
$vimeo_seconds = 0;
if ( is_user_logged_in() ) {
// Run WP query to retrieve user progress
$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $course_id) );
if ($row) {
$vimeo_seconds = $row->seconds_played;
$vimeo_progress = $row->progress_percent;
}
}
?>
<script>
jQuery(document).ready(function($) {
var progress = <?php echo $vimeo_progress; ?>;
var seconds = <?php echo $vimeo_seconds; ?>;
var userProgress = <?php echo $vimeo_seconds; ?>; //example user data retrieved
var lastUpdateProgress = <?php echo $vimeo_progress; ?>;
var videoUrl;
var courseID = <?php echo $course_id; ?>;
</script>
How would the JS script be able to access the PHP variables if moved to the plugin? Do I need to move the PHP above the script to a plugin function.. because then I am not sure how it would pass the data to the JS.
Wordpress have a classified function for the job
wp_localize_script()
Take a look. It's very easy to do.
http://codex.wordpress.org/Function_Reference/wp_localize_script
I've searched everywhere for a method where a page can reload automatically for every x seconds without actually reloading the page's contents, I have php code(includes some html) which updates my database table whenever a new user joins the page. However this only works once.
PHP CODE
<?php
$userOn5 = "SELECT * FROM `usersOn` WHERE name = '$username'";
$query4 = mysql_query($userOn5) or die (mysql_error());
while ($row = mysql_fetch_array($query4)) {
// Gather all $row values into local variables for easier usage in output
$timenow = $row["time"];
}
$user = "SELECT * FROM `user`";
$query3 = mysql_query($user) or die (mysql_error());
while ($row = mysql_fetch_array($query3)) {
$usernow = $row["name"];
}
$secs = time() - $timenow;
mysql_query("UPDATE user SET name = '$user'");
if ($username == $usernow) {
?>
<div id="container" style="display:none;">
I've attempted using meta tag but that reloads the entire content, I've attempted moving the entire php code to a separate php file and tried loading it inside a div called 'show' in the page:
var auto_refresh = setInterval(
function ()
{
$('#show').load('registeruser.php').fadeIn("slow");
}, 10000); // autorefresh the content of the div after
//every 10000 milliseconds(10sec)
Basically what I'm trying to do is rerun the php code every 10 seconds. Help?
Quite likely your issue is due to browser cache. You can use the following workaround -- that's actually what ajax does when you use cache: false:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t);
$('#container').fadeIn("slow");
}, 10000);
});
UPDATE
Alternatively, you can use the following:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t).find('> div').fadeIn("slow");
}, 10000);
});