I want to die. To feel nothing will be better then now. Mathjax is undefined but only if my2 session variables exist:
<?php
if(isset($_SESSION['odpowiedzi']) && isset($_SESSION['gdzieblad']))
{
echo '<script type="text/javascript">window.odpowiedzi = '.json_encode($_SESSION['odpowiedzi']).'; alert(window.odpowiedzi);</script>';
unset($_SESSION['odpowiedzi']);
echo '<script type="text/javascript">var gdzieblad = '.$_SESSION['gdzieblad'].';</script>';
unset($_SESSION['gdzieblad']);
}
?>
<script>
if(typeof gdzieblad !== 'undefined')
{
$('.code').each(function(index,value)
{
var str1 = window.odpowiedzi[index];
var str2 = "$$";
var res = str2.concat(str1);
var res2 = res.concat(str2);
$(this).html(res2);
});
}
</script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax:{inlineMath: [['$','$'], ['\\(','\\)']]}});
var QUEUE = MathJax.Hub.queue;
</script>
<script type="text/javascript" src="js/funkcjesprawdzian2.js"></script>
And in last js in thaat line:
window.UpdateMath = function(TeX){var math = MathJax.Hub.getAllJax(id)[0];QUEUE.Push(["Text",math,TeX]);}
...I have critical JS errorthat MathJax is undefined. What is more when $_SESSION['odpowiedzi'] and $_SESSION['gdzieblad'] is unset, everything is working and I dont get that error. WHAT IS MORE mathjax is generating good math symbols with that error but then I cant continue other js code and I can't use that fucnction from line with error. Please help me.
EDIT:
I know from console that: window.odpowiedzi = ["\frac{1}{1}","\frac{1}{2}","\frac{1}{3}444","\frac{1}{4}"]; alert(window.odpowiedzi); It don't look like a JSON
echo sprintf("'%s'", json_encode($_SESSION['odpowiedzi']));
will print json. Now in javascript you need to parse it to the object. See this answer how to do this.
Don't forget to put " or ' for $_SESSION['gdzieblad'] too.
Related
I have a PHP code, where I need to make some manipulations with JS, and I tried the following
<?php
include './parse.service.php';
echo putContent();
$jsScript = "
<script type='text/javascript'>
const json = require('./transacitions.json');
window.onload = modifyData;
function modifyData() {
document.getElementById('n_transactions').innerHTML = parseInt(document.getElementById('n_transactions').innerHTML, 10) + json.data.length;
document.getElementById('total_received').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML = `${this.totalReceived(convertToFloat(document.getElementById('total_received').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML))} BTC`;
document.getElementById('final_balance').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML = `${this.finalBalance(convertToFloat(document.getElementById('final_balance').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML))} BTC`;
}
function convertToFloat(element) {
var numb = element.match(/[+-]?\d+(\.\d+)?/g);
numb = numb.join(\"\");
return (parseFloat(numb, 10));
}
function totalReceived(quantity) {
json.data.forEach(element => {
if (element.finalSum > 0) {
quantity += element.finalSum;
};
});
return quantity;
};
function finalBalance(quantity) {
json.data.forEach(element => {
quantity += element.finalSum;
});
return quantity;
};
</script>";
echo $jsScript;
?>
And when I echo the created "script", i get the message similar to this Uncaught Error: Call to undefined function totalReceived() how shall I modify the code, in sucha a way that JS will integrate normally in my PHP script.
$ has special meaning inside PHP strings delimited with " characters, so ${this.totalReceived is causing the PHP engine to try to find an execute a function called totalReceived.
There's no apparent reason to use a PHP string here anyway. Just exit PHP mode and just output the code directly.
<?php
include './parse.service.php';
echo putContent();
?>
<script type='text/javascript'>
const json = require('./transacitions.json');
window.onload = modifyData;
// etc etc
</script>
Better yet. Move the JS to a separate file and include it with <script src>.
Is there a way via some lines of JavaScript to assign the value of a custom meta field in a Wordpress post/page to a JavaScript variable?
In other words, I've got a custom meta field in all my Wordpress posts and pages named "customamznsearch". I'd like to assign the value of that field to a JavaScript variable with the same name... or different name if need be.
Also, an added bonus would be to also define a static value for the variable if no data is available from that meta field.
This is the code that will be utilizing the "customamznsearch" variable.
<script type="text/javascript">
amzn_assoc_placement = "adunit0";
amzn_assoc_tracking_id = "livcouintheci-20";
amzn_assoc_ad_mode = "search";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_textlinks = "";
amzn_assoc_linkid = "0c1ce8995df23ae16ec99d3bb32502ec";
amzn_assoc_default_category = "SportingGoods";
amzn_assoc_default_search_phrase = customamznsearch;
</script>
<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>
This code will be displayed in an Enhanced Text Widget in the footer of my page. The Enhanced Text widget should be fully capable of supporting Text, HTML, CSS, JavaScript, Flash, Shortcodes, and PHP.
After much research, the following snippet of code was what ended up working (please note that I decided to change the variable to 'amazonadserach'):
var amazonadsearch = "<?php global $post;
$amazonadsearch = get_post_meta($post->ID, 'amazonadsearch', true);
echo $amazonadsearch; ?>";
You can just output javascript code from php like this:
<script>
var customamznsearch = "<?php echo addcslashes($customamznsearch, '"'); ?>";
</script>
Or if you mean to get it from the <meta> tags, then:
function getMeta(metaName) {
var metas = document.getElementsByTagName('meta');
for (i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == metaName) {
return metas[i].getAttribute("content");
}
}
return "";
}
var twitterTitle = getMeta("twitter:title");
Having some strange issue that I've been looking at for a couple of days now, and even with Googling can't solve.
I have this piece of JS that is called when a button is pressed. I cab tell this function really is called because the alert("1") pops up. I also know for sure the rarray is populated.
<script type="text/javascript">
function process_match() {
var rarray = new Array();
$x = $("input[name=pair]:checked").val();
$left = $x.charAt(0);
$rite = $x.charAt($x.length-1);
$car1a = document.getElementById("car"+$left+"_"+$rite+"_1").value;
$car1b = document.getElementById("car"+$rite+"_"+$left+"_1").value;
.....
$hsb = document.getElementById("hs"+$rite+"_"+$left).value;
rarray[0] = $left;
rarray[1] = $rite;
rarray[2] = $car1a;
rarray[3] = $car1b;
.....
rarray[15] = $hsb;
alert("1");
$.post("./updpoule.php",
{'results': rarray},
function(data) {
alert("2");
}
);
}
</script>
Then, I have the following php file :
<?php
$f = fopen("/tmp/q", "w");
$array = $_POST['results'];
fwrite($f,"AAA");
fwrite($f, $array[0]);
fwrite($f, $array[1]);
fclose($f);
?>
I have seen this code all over as solutions to similar problems, but I can't get it to work.
If I run the code, the alert("1") pops up. After that nothing happens. No file /tmp/q is being created. BUT, if I debug the page, and set a breakpoint where the $.post is, and then step through, a file /tmp/q IS created, just not with the right content..
Any suggestions are more than welcome.
Thanks,
Hans
Try to return something from your php script.
For example, add this to the end of the file:
echo 'OK';
?>
And, in you JS:
$.post("./updpoule.php", {'results': rarray}, function(data) {
if (data === 'OK') {
alert('ok');
} else {
console.log(data);
alert('error');
}
});
If you'll get popup with error, check the console on the data you've got from php.
Just like the title above: how to concatenate two strings in JQuery?
This is my code so far:
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= "#" .$_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if (serviceName != "") {
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
As you can see in my above code, in variable name serviceID, I am concatenating hashtag and my GET value and I try to put it on ALERT and the result is correct, but when I assign it to .addClass it’s not working.
Any alternatives and solution is much appreciated.
I guess you meant that the PHP code should be evaluated before arriving to the client, therefore your code syntax is correct, but check out the following looks cleaner and also not polluting the global JavaScript scope (that's what the var ... is for):
var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;
but, since your code syntax is correct, you should verify that you actually have an element with serviceId as the id when your are executing it
if (($(serviceId)||[]).length) {
alert('your element with the id:'+serviceClass+' exists');
}
else {
alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
i hope this one solve the issue:
<script>
$(document).ready(function(){
serviceName = '<? echo "./".$_GET["services"].".php";?>';
serviceID = '<? echo "#" .$_GET["services"]; ?>';
serviceClass ='<? echo $_GET["services"]; ?>';
console.log(serviceID);
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
</script>
also check the console in your browser (firebug or chrome developer tools) to see the output ,fit your criteria
Try as but not sure, My change is append "#" Id in jquery
<script>
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= $_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$("#"+serviceID).addClass("it");
}
});
</script>
Stuck on a jquery/javascript function that is attempting to .load a set PHP script but passing get variable parameters. As an aside this is set to happen automatically after 5 seconds. New to posting here but have read a lot of posts and can't seem to find exactly what I am doing wrong.
This function works:
function LoadMyPhpScript()
{
$('#MyDiv').load('hello.php');
}
setTimeout(LoadMyPhpScript,5000);
This function does not work:
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'hello.php';
strURL = strURL + cPhpParamString;
$('#MyDiv2').load(strURL);
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
Here's the hello.php
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Note: this is just a mock-up, would use regex to validate gets, etc in production.
RESOLVED
Here is what I ended up with, thank you!
function LoadMyPhpScript1(cPhpParamString)
{
$('#MyDiv1').load('hello.php'+cPhpParamString);
}
setTimeout(function() { LoadMyPhpScript1('?MyVar1=0&MyVar2=1'); },5000);
When you do this:
LoadMyPhpScript2('?MyVar1=0&MyVar2=1')
You are executing the function and passing the result to setTimeout
Try this:
setTimeout(function() { LoadMyPhpScript2('?MyVar1=0&MyVar2=1'); },5000);
However, sending the url querystring like that is an odd way of doing it. Something like this might be better:
function LoadMyPhpScript2(myVar1, myVar2)
{
var strURL = 'hello.php';
$('#MyDiv2').load(strURL, { myVar1: myVar1, myVar2: myVar2 });
}
setTimeout(function() { LoadMyPhpScript2(0, 1); },5000);
Better try this way:
File help3.html:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'help3.php';
strURL = strURL + cPhpParamString;
$.ajax({
url: strURL
}).done(function(data) { // data what is sent back by the php page
$('#MyDiv').html(data); // display data
});
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
</script>
</head>
<body>
<div id="MyDiv">
</div>
</body>
</html>
File help3.php:
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Test on my localhost, and both files on the same folder.