I have the following div that has a number generated by jQuery:
HTML:
<td id="Total" class="total">
</td>
jQuery:
var sum = 0;
$(".item-price").each(function() {
var NewQuoteTotal = $(this).html().replace('£', '')
sum += parseInt(NewQuoteTotal);
})
console.log(sum)
$(".total").text('£' + sum)
I need to get the generated number from that element so that I can use it in PHP to be displayed elsewhere.
I've meddled with DOM (Which I don't know):
$dom = new domDocument;
$html = file_get_contents("FILELOCATION"); //I don't use FILELOCATION, that's just a placeholder for StackOverflow.
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$thePrice = $dom->getElementById("Total");
if(!$thePrice) {
die("Element Not Found!");
}
echo "Element is there!";
$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//td[id="Total"]');
echo $divContent;
And tried to use jQuery to $.post() a variable containing the number but I've had no success.
$.post('/path/to/my/php/script.php', {total: $('#Total').text()}, function(){
//what to do with the returned data from the server
});
And in script.php (as indicated above):
$total = isset($_POST['total']) ?: false;
if($total !== false):
//you can use $total now
endif;
I can't believe I didn't think of it earlier, but I just made the variable in PHP rather than jQuery...
Thanks for all the help!
Related
What I want:
A list of links show events - a click on such a link shall show further details in a special DIV on the same page.
Idea:
I read from the database all events:
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
This gives me all available events in the DB that are not yet processed.
I assgin all found events identified by their UUID into a PHP array for further processing
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i",
$eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
Having that 2-dimensional array "eventInfo" I build the list
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
Last but not least I create a DIV to store the desired eventBody-Information:
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
To populate now the DIV when a link is clicked I tried this:
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
I wanted to pass the php-Array with JSON to make it available inside the function.
With the click-effect I wanted to load from this php-array the related array-element ['eventBody'] with the UUID given by the link-click.
Somehow I am stuck. I am able to pass the UUDI key to the javascript area and can write it into the DIV but I cannot identify a php-element by the given UUID and put the content into the DIV.
Any hint is appreciated, thank you.
As requested here is the code in total:
<?php
// Including jQuery
echo '<script src="http://code.jquery.com/jquery-1.11.3.min.js">/script>';
// Querying the Neo4J DB
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
// Parsing result and build the 2-dimensional array $eventInfo
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i", $eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
// Displaying list of events with UUID as forwarded parameter (-> JS)
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
// Creating a DIV Container to hold $eventInfo[eventUUID][eventBody]
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
// JavaScript Part
echo <<<EOT
<script type="text/javascript">
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
</script>
EOT;
?>
2nd EDIT:
I have stripped down everything to this functioncode, which is at the end of the php-file and no longer wrapped in the php-tags. So its like standard html. This way I avoid the uncaught syntax error.
<script type='text/javascript'>
$(document).ready(function (){
var passedArray = '<?php echo json_encode(array($test_array)); ?>';
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
console.log(p);
console.log(passedArray[p]['eventBody']);
$('#info').text(passedArray[p]);
});
});
</script>
Outcome:
I can console.log the array, which shows as a test:
[[{"UUID":"60762d3eb9949596701a2dfb700cd2c9","eventBody":"Hallo"},{"UUID":"620c16ced5097bf60f718abca7d979f8","eventBody":"Ciao"}]]
I see also that when I click a link that the UUID key is passed to the Javascript-Script:
60762d3eb9949596701a2dfb700cd2c9
But when I want to assign the related eventBody-element I receive this error:
Uncaught TypeError: passedArray[p] is undefined
As I have the array and the key I assume it must be a syntax error in this line:
console.log(passedArray[p]['eventBody']);
So two questions left:
How would I access one element of the given array?
How can I then populate the DIV with the element ['UUID']['eventBody']? Not sure if this is the way to go: $('#info').html().passedArray[p];
Resolution (with Uwe's help):
function findme(p) {
var passedArray = '<?php echo json_encode($test_array); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
thanks to your support here (Kudos to Uwe) here is the solution:
As we use jQuery we need to include this in the head:
echo '<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>';
The Javascript-Function (written in HTML, not in PHP tags):
function findme(p) {
var passedArray = '<?php echo json_encode($eventInfo); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
I was not able to find a way to write the whole code within PHP tags, as the double echo (Start and inside the array handover) and the additional PHP?-tags always generates syntax errors - thus the JS function is written as HTML-code outside the PHP code.
In the PHP the UUID of the array is passed onClick to the JS function - looks like
echo ' Find the element by UUID Brackets -- '.$UUID.'';
Please pay attention to the escaped quotation marks - important to avoid an error in JS that allows no identifiers starting with a number.
The DIV is marked by
echo '<p id="result"></p>';
For testing I made an array like this:
$eventInfo= array();
$eventInfo[] = array('UUID' => '60762d3', 'eventBody' => 'Text 1');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 2');
$eventInfo[] = array('UUID' => '6076299', 'eventBody' => 'Text 3');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 4');
I try to load an HTML page from a remote server into a PHP script, which should manipulate the HTML with the DOMDocument class. But I have seen, that the DOMDocument class removes some parts of the Javascript, which comes with the HTML page. There are some things like:
<script type="text/javascript">
//...
function printJSPage() {
var printwin=window.open('','haha','top=100,left=100,width=800,height=600');
printwin.document.writeln(' <table border="0" cellspacing="5" cellpadding="0" width="100%">');
printwin.document.writeln(' <tr>');
printwin.document.writeln(' <td align="left" valign="bottom">');
//...
printwin.document.writeln('</td>');
//...
}
</script>
But the DOMDocument changes i.e. the line
printwin.document.writeln('</td>');
to
printwin.document.writeln(' ');
and also a lot of others things (i.e. the last script tag is no longer there. As the result I get a complete destroyed page, which I cannot send further.
So I think, DOMDocument has problems with the HTML tags within the Javascript code and tries to correct the code, to produce a well-formed document. Can I prevent the Javascript parsing within DOMDocument?
The PHP code fragment is:
$stdin = file_get_contents('php://stdin');
$dom = new \DOMDocument();
#$dom->loadHTML($stdin);
return $dom->saveHTML(); // will produce wrong HTML
//return $stdin; // will produce correct HTML
I have stored both HTML versions and have compared both with Meld.
I also have tested
#$dom->loadXML($stdin);
return $dom->saveHTML();
but I don't get any things back from the object.
Here's a hack that might be helpful. The idea is to replace the script contents with a string that's guaranteed to be valid HTML and unique then replace it back.
It replaces all contents inside script tags with the MD5 of those contents and then replaces them back.
$scriptContainer = [];
$str = preg_replace_callback ("#<script([^>]*)>(.*?)</script>#s", function ($matches) use (&$scriptContainer) {
$scriptContainer[md5($matches[2])] = $matches[2];
return "<script".$matches[1].">".md5($matches[2])."</script>";
}, $str);
$dom = new \DOMDocument();
#$dom->loadHTML($str);
$final = strtr($dom->saveHTML(), $scriptContainer);
Here strtr is just convenient due to the way the array is formatted, using str_replace(array_keys($scriptContainer), $scriptContainer, $dom->saveHTML()) would also work.
I find it very suprising that PHP does not properly parse HTML content. It seems to instead be parsing XML content (wrongly so as well because CDATA content is parsed instead of being treated literally). However it is what it is and if you want a real document parser then you should probably look into a Node.js solution with jsdom
If you have a <script> within a <script>, the following (not so smart) solution will handle that. There is still a problem: if the <script> tags are not balanced, the solution will not work. This could occur, if your Javascript uses String.fromCharCode to print the String </script>.
$scriptContainer = array();
function getPosition($tag) {
return $tag[0][1];
}
function getContent($tag) {
return $tag[0][0];
}
function isStart($tag) {
$x = getContent($tag);
return ($x[0].$x[1] === "<s");
}
function isEnd($tag) {
$x = getContent($tag);
return ($x[0].$x[1] === "</");
}
function mask($str, $scripts) {
global $scriptContainer;
$res = "";
$start = null;
$stop = null;
$idx = 0;
$count = 0;
foreach ($scripts as $tag) {
if (isStart($tag)) {
$count++;
$start = ($start === null) ? $tag : $start;
}
if (isEnd($tag)) {
$count--;
$stop = ($count == 0) ? $tag : $stop;
}
if ($start !== null && $stop !== null) {
$res .= substr($str, $idx, getPosition($start) - $idx);
$res .= getContent($start);
$code = substr($str, getPosition($start) + strlen(getContent($start)), getPosition($stop) - getPosition($start) - strlen(getContent($start)));
$hash = md5($code);
$res .= $hash;
$res .= getContent($stop);
$scriptContainer[$hash] = $code;
$idx = getPosition($stop) + strlen(getContent($stop));
$start = null;
$stop = null;
}
}
$res .= substr($str, $idx);
return $res;
}
preg_match_all("#\<script[^\>]*\>|\<\/script\>#s", $html, $scripts, PREG_OFFSET_CAPTURE|PREG_SET_ORDER);
$html = mask($html, $scripts);
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
libxml_use_internal_errors(false);
// handle some things within DOM
echo strtr($dom->saveHTML(), $scriptContainer);
If you replace the "script" String within the preg_match_all with "style" you can also mask the CSS styles, which can contain tag names too (i.e. within comments).
i have been scrolling for a solution for ages now and i cant seem to make it work.
i am trying to make some sort of library where u can hover on an icon while hovering it displays that image into image tag. as you can see from the image below my php statement returned 2 images at the left. and while hovering i want the hovered image to display in the big img tag. but hovering is not working.
Here is my javascript
<script type="text/javascript">
//imageview
$(document).ready(function loading(){
var getimg = document.getElementById("icoimg").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
});
</script>
And here is my php mysqli while loop
$count = 1;
if($count <= 6){
while($row = mysqli_fetch_array( $query )) {
$imgcase = $row['Showcase_Image'];
$itemname = $row['Product_Name'];
$itemid = $row['Product_ID'];
echo "<div class='imgico' id='imgico'><img id='icoimg' name='icoimg' src=$imgcase onmouseover='loading();' /></div></br>";
$count++;
}
}
and this is the big img preview
<div class="imgprev" id="imgprev" width="460" height="300"><img id="selectedimg" width="460" height="300" /></div>
I have tried numerous tricks i tried inventing my own code. I searched all over the net but no luck. What i am thinking is MAYBE because the generated id's inside the tags have the same ID that maybe my img hover is useless. Maybe i need to find a way to get each generated id tags a unique id and call and then call that tag's id which should be "unique" in javascript and then apply the function? if so how?
Any lifesaver that can help me? Thx in advance!
Php and Javascript only..no CSS plz(unless its the only hope...lol)
EDIT: I did a "Hardcoding" and it worked but even tho its hardcoded i dont want it to work like this.I want to display max 5 images which is why i have a count function before my while loop in my php code. but if i cant find a better way i think im just going to stick with this unprofessional hardscript lol
if($count <= 6){
while($row = mysqli_fetch_array( $query )) {
$imgcase = $row['Showcase_Image'];
$itemname = $row['Product_Name'];
$itemid = $row['Product_ID'];
echo "<div class='imgico' id='imgico'><img id=$count name='icoimg' src=$imgcase onmouseover='loading$count();' /></div></br>";
$count++;
function loading1(){
var getimg = document.getElementById("1").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading2(){
var getimg = document.getElementById("2").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading3(){
var getimg = document.getElementById("3").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading4(){
var getimg = document.getElementById("4").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading5(){
var getimg = document.getElementById("5").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
echo "<div class='imgico'><img name='icoimg' src=$imgcase onmouseover='loading(this);' /></div></br>";
You can't use the id as the selector to get the img, because it is supposed to be unique.
Instead, in your javascript, you can pass a reference to the element that called the loading() function :
echo "<div class='imgico'><img name='icoimg' src=$imgcase onmouseover='loading(this);' /></div></br>";
<script type="text/javascript">
//imageview
$(document).ready(function loading(elm){
var getimg = elm.getAttribute("src");
document.getElementById("selectedimg").src = getimg;
});
</script>
Well my page works now.
The answer i received from Galcha was the first thing i ever used so it didnt really help. after some thinking i decided to replace $(document).ready(function loading(elm) with function loading(elm) . So my script looks like this now
function loading(elm){
var getimg = elm.getAttribute("src");
document.getElementById("selectedimg").src = getimg;
}
Now after using this the hover works perfect. BUT it does not auto display the first image on page load. So i modified my while statement a bit and now it looks like this.
$count = 1;
if($count <= 6){
while($row = mysqli_fetch_array( $query )) {
$imgcase = $row['Showcase_Image'];
$itemname = $row['Product_Name'];
$itemid = $row['Product_ID'];
echo "<div class='imgico'><img name='icoimg' src=$imgcase onmouseover='loading(this);' /></div></br>";
if($count <= 1){
$imgfirst = $imgcase;
}
$count++;
}
}
Now my page works perfectly. Incase you ask why i have a count <1 statement in my while loop?
Because if i just echo the $imgcase in the selectedimg src code i will get the last image src autodisplayed. And i wanted the first one. Thats why i made a count <=1 to get the first link and give the first link a seperate variable and echo's $imgfirst in the selectedimg src.
My code is a bit scrappy but...it works i guess lol.
I am trying to work out how to get thye last part of a url on click of a button dynamically from a pre populated csv file.
For example on click of <a href="mysite.com/" >button</a>
would grab a code from a CSV file (or something better) and the link would be mysite.com/code1.
However each code from the CSV will only be used once and be removed after
So first click = mysite.com/code1
Second click = mysite.com/code2
and so on getting code1 and code2 from the CSV file and never to be gotten again.
I can use either JavaScript or PHP, either is good, I'm just not sure on the syntax.
Like this:
<?php
$first = true;
$links = "";
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if (!$first) $links.=",";
$first=false;
//$line is an array of the csv elements
$links.='"'.$line.'"';
}
fclose($file);
?>
Plain JS
<script>
var links = [<?php echo $links ?>];
cnt = 0;
window.onload=function() {
document.getElementById("csvLink").onclick=function() {
window.open(this.href+links[cnt],"_blank"); // otherwise you need cookies
return false;
cnt++;
}
}
</script>
jQuery using Ajax:
<script>
var links = [<?php echo $links ?>];
cnt = 0;
$(function() {
$("#csvLink").on("click",function(e) {
e.preventDefault();
$("#someContainer").load(this.href+links[cnt]);
cnt++;
});
});
</script>
I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});