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.
Related
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;
}
}
?>
I have the following code which returns the result I require inside of a tab. But because the JavaScript is in the same file it shows a blank tab when there is no data to show. I remove the JavaScript and the tab disappears. How can I run the JavaScript only if data is present so the tab will disappear? Or can I call it from another file?
<?php echo $block->escapeHtml($block->getProduct()->getData($this->getCode()));
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
Since you have to hide the tab if escapeHtml() returns empty value. So you can create a condition block to add the script if escapeHtml() returns a non-empty value.
<?php $EH = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if ($EH) {
echo $EH;
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
<?php } ?>
My knowledge on PHP is not the best, so I will just describe it like that.
Just save the data in a variable
If the data exists (e.g. is not empty)
Print data and JavaScript code
If it does not exist, do nothing
Here is some pseudo-code:
<?php
data = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if (data exists) {
echo data;
echo /* Your JavaScript Code*/;
}
?>
Use a if statement that within the php tags that check value id present then you can render the the java script tags as well as the value.
<?php
$val = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
$script = '<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>';
if($val != "" || $val !=null)
{
echo $val;
echo $script;
}
?>
I have having big issues with the execution order of my code.
HTML sample:
<div id="toast-container" class="toast-top-right"><div id="toast-type" class="toast" aria-live="assertive" style=""><div id="snackbar">message</div></div></div>
.
.<!--Somewhere more down the line-->
.
.
<div class="col_half col_last">
<label for="job-ctc-frm-heard-about">How did you find out about us?</label>
<input type="text" id="job-ctc-frm-heard-about" name="job-ctc-frm-heard-about" value="<?php echo $discovered;?>" class="sm-form-control" />
</div>
Javascript function:
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
PHP sample:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$message = 'Let the games begin';
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
......
?>
Now heres my problem. My php uses a function Toast. My function Toast accesses the HTML div toast-container to set a message. The other div uses the php variable $discovered to remember the entered value on a failed form submit. If i position the JS anywhere before the DOM then var cont will be null so it has to be below.
However if I position the code order as PHP -> HTML -> JS then the function is undefined in PHP so it has to be after JS. But if i position it as HTML -> JS -> PHP then the variable $discovered won't be displayed in the HTML. The orders are conflicting with one another. Is there any work around for this?
The simplest would be to just move the relevant parts to where you need them. You need $discovered to be available throughout your file (when PHP is executed server-side) and you need it to echo the script specifically after your Toast-declaration:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST") {
$message = 'Let the games begin';
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
// ...
}
?>
<!-- HTML referencing $discovered here -->
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST") {
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
}
?>
If you want to control these things from client-side, you can json_encode your PHP objects, meaning they will be sent in plain-text as if you had hard-coded them into the file. As #FZs mentions, PHP runs on the server and "prepares" the file by executing all <?php ... ?> blocks. When the result reaches the browser, it contains the resulting text and not PHP (browsers don't understand PHP).
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
}
?>