This is wordpress plugin code The following code works, but no text comes into the modal window. Error is this enter image description here
<?php
$phpvariabletext = get_post_meta( $post_id, '_billing_satis_sozlesme', true );
// $phpvariabletext large text along with html codes
?>
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
var content = '<?php echo $phpvariabletext; ?>';
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
You can use PHP variable in JQuery/Javascript easily check below steps
1) Stored PHP variable value in HTML input tag as type hidden
<input type="hidden" value="<?php echo $phpvariabletext;?>" id="phpvariable">
2) After assign variable value in HTML input tag. You can get value in JQuery/Javascript.
<script type="text/javascript">
var content = $('#phpvariable').val();
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
Creating extra DOM elements solely to transport a value is needless extra markup.
I always pass php data to javascript as json_encode() output (without manually quoting) because it will automatically double-quote your string and escape any of the double-quotes in the actual data.
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
let newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(<?= json_encode(get_post_meta($post_id, '_billing_satis_sozlesme', true)); ?>);
}
</script>
The above technique outputs the php value using php "short tags".
P.s. you could also consider removing the inline js function call and use an event listener in your js to keep all of the behaviors/events in one place.
Good morning everyone,
I am reading a textfile from our server which changes its content every 10 seconds. I am displaying it using this code:
<div id="textfile">
<?php
$file = $_SERVER['DOCUMENT_ROOT'] . "/resources/file.txt";
$content = file_get_contents($file);
echo $content;
?>
</div>
I am using jquery in updating the content and displaying it.
setInterval(function() {
$('#textfile').load(document.URL + " #textfile");
}, 10000);
However if it is updated, it creates another < div >.
Previously it looks like this..
<div>Content</div>
But after it refreshes, it looks like this..
<div>
<div> Content </div>
</div>
Can anyone tell me what is wrong with this code and please help me so that it won't create another < div > after it refreshes..
You can load the text file directly, and reload it every 10 seconds.
<div id="textfile"></div>
<script src="path/to/the/jquery/lib.js"></script>
<script>
$(function() {
setInterval(function() {
$('#textfile').load('path/to/the/text/file.txt');
}, 10000);
});
</script>
I am having a problem with jQuery where by it is not loading inside a requested div.
Setup:
On index.php I have 4 Morris charts on 4 tabs all working fine.
On each tab there is a list. Each item in the list is a link
Upon clicking the link the div within the tab reloads with new data
via post:
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-'+companyId+' .clickthrough5').val(),
ref_date_from5: $('#company5-'+companyId+' .ref_date_from5').val(),
ref_date_to5: $('#company5-'+companyId+' .ref_date_to5').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
The new div contains a back button to take you back to a replica of the 1st graph but on a different page (donut1.php), for my personal ease:
$(document).ready(function () {
$('.backref2').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut1.php', {
clickthrough6: $('#company6-'+companyId+' .clickthrough6').val(),
ref_date_from6: $('#company6-'+companyId+' .ref_date_from6').val(),
ref_date_to6: $('#company6-'+companyId+' .ref_date_to6').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
All this code works fine up until landing on donut1.php.
At this point I proceeded to pull out chunks of my hair for several hours looking through Inspect Element in Chrome to identify the issue.
1 bald person later I realised the jQuery was not loading although it is correctly requested in a script tag.
I confirmed this by placing the following on both donut1.php and donut5.php:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
donut5.php displays the output fine while donut1.php does not.
I then tried to load an external source and a different version using the Google snippets found here but this still did not work.
Some points to note:
I currently have jquery loading in my header and footer as part of trying to work this out.
As the 2 pages donut1.php and donut5.php do not include header or footer I have manually included them both in there. Same exact way in both files. donut5.php works donut1.php does not.
Order is index.php > donut5.php > donut1.php and then you continue to cycle between donut5 and donut 1 - or you would if the post on click was working in donut1.php.
Any help would be greatly appreciated!
EDIT: donut1.php:
<?php
include("../../../includes/config.php");
$selected = $_POST['clickthrough6'];
$date_from = $_POST['ref_date_from6'];
$date_to = $_POST['ref_date_to6'];
?>
<script src="../../../js/jquery-1.11.0.js"></script>
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
<div id="tabs2">
<div id="tabs-1" class="donut5">
<h4>Top 5 Referrers - Quotes <br /><small>Total number of Quotes between <?php echo date("d/m/Y", $date_from); ?> to <?php echo date("d/m/Y", $date_to); ?></small></h4>
<div class="statgrid">
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
<?php $quotes_q="SELECT
c.case_id,
co.name AS company_name,
co.company_id AS company_id,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = " .$RegisteredUser['panel_id']. " AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from. " AND
c.insert_date < ".$date_to. "
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result=$mysqli->query($quotes_q); ?>
<div class="col-2-6">
<div id="morris-donut-chart6"></div>
</div>
</div>
<div class="statgrid">
<?php while ($row=$result->fetch_array()) { ?>
<div class="col-4-6">
<div id="company7-<?php echo $row['company_id'];?>">
<input type="hidden" class="ref_date_from7" value="<?php echo $date_from; ?>" />
<input type="hidden" class="ref_date_to7" value="<?php echo $date_to; ?>" />
<input type="hidden" class="clickthrough7" value="<?php echo $row['company_id'] ?>" />
<a><div id="<?php echo $row['company_id'];?>" class="click7 col-5-6"><?php echo $row['company_name']; ?></div></a>
<div class="col-1-6"><?php echo $row['quote_count']; ?></div>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
$quotes_q = "SELECT
c.case_id,
co.name AS company_name,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = ".$RegisteredUser['panel_id']." AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from." AND
c.insert_date < ".$date_to."
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result = $mysqli->query($quotes_q);
?>
<script>
var donut_data6 = [
<?php while ($row = $result->fetch_array()) { ?>
{
label: '<?php echo substr($row['company_name'],0,15); ?>',
value: '<?php echo $row['quote_count']; ?>'
},
<?php } ?>
];
var donut6 = {
element: 'morris-donut-chart6',
data: donut_data6,
resize: false
}
donut6 = Morris.Donut(donut6)
</script>
EDIT2:
Not too sure if this makes a different but in Network tab I have 2 listings for jquery the initial one loaded from the header which loads 304 Not Modified and the 2nd one which loads on calling donut5.php which loads as 200 OK. Seems that after this I cannot request jquery again perhaps?
EDIT3: in donut1.php I have removed everything except for the jquery script request and the Hello World inside the div I am trying to retrieve. Network tab still shows that jquery is not loading. The strange thing is I have this exact setup, minus the charts, working on the same page (different div classes of course), and this does load jquery fine.
EDIT4: Substituted jQuery for JS as a test and not even basic stand alone JS will work, added in:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Nothing :( - Looping in JS world
EDIT5: Suppose <script> is a HTML tag so looping in them too.
EDIT6: When adding console.logo(data) to the function in list item 4 above I get back the following (obviously I have excluded a lot for testing:
<script src="../../../js/jquery-1.11.0.js"></script>
<script src="../../../js/jquery-ui.js"></script>
<!--
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
-->
<div id="tabs2">
<div id="tabs-1" class="donut5">
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
</div>
</div>
EDIT7:
Placing code here to confirm if I have correctly inplemented KevinB's suggestion.
var
contentSelector = '.donut5',
$content = $(contentSelector),
contentNode = $content.get(0);
var documentHtml = function (html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi, '</div>');
// Return
return $.trim(result);
};
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-' + companyId + ' .clickthrough5').val(),
ref_date_from5: $('#company5-' + companyId + ' .ref_date_from5').val(),
ref_date_to5: $('#company5-' + companyId + ' .ref_date_to5').val()
},
function (data) {
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.donut5'),
$dataContent = $dataBody.find(contentSelector),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ($scripts.length) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html() || $data.html();
$scripts.each(function () {
var $script = $(this),
scriptText = $script.text(),
scriptNode = document.createElement('script');
if ($script.attr('src')) {
if (!$script[0].async) {
scriptNode.async = false;
}
scriptNode.src = $script.attr('src');
}
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
console.log(data);
});
});
});
EDIT8:
After trying the code above in EDIT7 the .donut5 in no longer being pulled from donut5.php to index.php which was originally working. I can see that jquery doesn't duplicate anymore on Network tab when clicking the link for donut5.php (even though the call to it is still there). Currently either I assume I have not mapped a div correctly above as I did remove part of the class find code for :first as I felt it was not required or somehow I have managed to make things worse!
When you pass an htmlstring to .html, one of two things happen. It either gets inserted using .innerHTML, or it gets inserted using .empty().append(htmlString). Which one is chosen is based on the complexity of the htmlstring passed in.
If it's relatively simple, .innerHTML will be used and scripts will execute in the way you expected.
However, if it is more complex, the elements are first parsed and appended to a docFragment before being appended to the document. This middle step is what causes your problem because the javascript will be executed before the elements are part of document.
The only way to fix this issue is to forcibly delay the execution of the javascript by either coding the javascript in such a way that it's execution is in a callback that later gets called, or by removing the javascript from the htmlstring before appending it and then executing it after.
Below is an example of the former:
(function divTestLooper () {
if (!$("#divTest1").length) {
// the element didn't exist, lets wait a little longer...
return setTimeout(divTestLooper, 10);
}
$("#divTest1").text("Hello, world!");
})();
Here is an example of the latter:
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L60-L70
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L123-L135
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L158-L167
Of course, the best solution is likely to avoid this problem entirely by not including javascript in your partials.
I have the following javascript:
<script type="text/javascript">
function changeBet(parseFloat(bet)) {
var moneyline = parseFloat(<?php echo json_encode($win) ?>);
var gain = parseFloat(bet * moneyline);
document.getElementById("PotentialGain").value = gain;
}
</script>
The php variable $win is successfully var_dump'ed as a float. When the variable gain = bet, PotentialGain displays the user input from BetAmount as expected. Here is my echo'ed php code:
echo '<tr>';
echo '<td>type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" ></td></tr><tr><td>Potential Gain:<input type="text" name="PotentialGain[]" id="PotentialGain" ></td></tr><tr><td><input type="Submit" name="send" value="Submit"></td>';
echo '</tr>';
However, I want gain(which is inputted as the PotentialGain value) to be the user input bet * the var moneyline.
The result is NaN. Is there a var that I am not parsing correctly to display the correct numerical value of gain?
Thanks for any help.
You can't put a function call where a parameter name is expected.
function changeBet(bet) {
bet = parseFloat(bet);
// rest of code
}
The problem is the incorrect syntax in this line:
function changeBet(parseFloat(bet)) {
you need to pass a parameter to the function, like this:
function changeBet(bet) {
Then, when you call the function, you can evaluate whatever argument you want to send through parseFloat:
changeBet(parseFloat(strBet));
Here is the final javascript that I used:
<html>
<script type="text/javascript">
function changeBet(bet) {
var moneyline = <?php echo $win ?>;
var gain = (bet * moneyline).toFixed(2);
document.getElementById("PotentialGain").value = gain;
}
</script>
</html>
My final notes are: 1. To remember to place the javascript function after the code with your php caclculations. 2. Thanks to everyone who clarified parseFloat is not necessary if you know the var is a int (or double in my case). 3. Thanks to everyone who clarified parseFloat did not belong in the function parameter.
Hopefully this helps others out!
<?php
echo '
<script type="text/javascript">
$(function() {
var refresh = setInterval(function() {
$("#content").html("'.rand().'");
}, 3000);
});
</script>
<div id="content"></div>
';
?>
This will update the div "content" with a random number after 3 seconds, however it only updates once. Why does it not continually generate a new number every three seconds, and how can I make it do precisely that?
Thank you in advance for any assistance rendered.
Ha. PHP is run on the SERVER side. JS is on the client.
you need to generate the rand on the JS side not he php side...
js code:
<script type="text/javascript">
$(function() {
var refresh = setInterval(function() {
var randomnumber = Math.floor(Math.random()*11);
//where 11 dictates that the random number will fall between 0-10
$("#content").html(randomnumber);
}, 3000);
});
</script>
<div id="content"></div>