I cant seem to get the following code to work;
function add_js_functions(){
$gpls_woo_rfq_cart =
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');
if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");
if(1 != 0) {
getQuoteIcon[0].style.display = "none";
}
</script>
<?php }
add_action('init','add_js_functions');
The php above the script stores a variable from the quote form on the number of items in the form.
I tried the javascript by itself and its seemed to work but its not working in the functions file.
At the moment im using (1 != 0) to make sure its true and to hide the item so I know the JS works, what will happen afterwards is this will become;
if (<?php $count != 0 ?>) {
//rest of the JS here
}
So that when the page loads, if the form is empty of items then this icon will be hidden (it starts off as inline-block and i dont know how to change this).
I think you want your php to be <?php echo $count != 0 ?>.
Your PHP is executed server-side, and Javascript client side, the two don't communicate by passing variables between the two. In order to get your PHP variable into your Javascript, you need to echo it.
It looks like you are loading the JS too soon and the element you are targeting isn't available yet.
Use add_action('wp_footer') to load the JS in the footer.
function add_js_functions(){
$gpls_woo_rfq_cart =
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');
if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");
if(1 != 0) {
getQuoteIcon[0].style.display = "none";
}
</script>
<?php }
add_action('wp_footer','add_js_functions');
Related
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 posted this earlier but it incorrectly got marked as a duplicate of Can scripts be inserted with innerHTML?, which isn't my problem. I'm not trying to run any JavaScript through using innerHTML, I'm trying to run JavaScript that is located in a PHP file called through Ajax/XmlHttp. I am using innerHTML in that JS, but I'm not writing more JS within that. So it's not a duplicate of that question and I'm trying it again now.
Not sure what's going on here. I'll explain the organization of my files first and then get into the code.
The application- Allows the user to select different attributes (i.e. year or name) and view pictures of matching results from a database.
Files- I have a gallery.php file that has a series of HTML form elements acting as selectors to get filtered results from a database. Whenever a selector is set or changed, the file sends a new request to a get.php file that uses Ajax to refresh the results without loading a new page. All that works great. My next task is to implement a modal section where I can click on an image and view a bigger version which I plan to do with JavaScript and CSS, but my intermediate goal is to just change some text at the bottom of the results from get.php again using JavaScript, just as a first step. But I can't seem to get any JavaScript written in get.php to fire.
Code-
This is gallery.php:
<?php
include_once("./../php/navbar.php");
?>
<html>
<head>
<link href="/css/siteTheme.css" rel="stylesheet">
<style>
.attributes span {
margin-right: 1rem;
}
</style>
<script>
function changeParams() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
}
};
year = document.getElementById("years_select").value;
nameFirst= document.getElementById("nameFirst_select").value;
/* Ton of other getElementById statements here that I'm excluding to keep things shorter */
url = "get.php?year="+year+......;
xmlhttp.open("GET", url, true);
xmlhttp.send();
} /* End function */
</script>
</head>
<body>
<div class="content">
<h1>Gallery</h1>
<form>Details:
<!-- -------------------- Year -------------------- -->
<select onchange="changeParams()" name="years" id="years_select">
<option value="All">Year</option>
<?php
include("/var/www/admin.php");
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = "select year from db group by year order by year desc";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value=" . $row['year'] . ">" . $row['year'] . "</option>";
}
mysqli_close($conn);
?>
</select>
<!-- A bunch of other selectors are created here following the same pattern as above of getting results from a DB -->
<!-- -------------------- Searchbar -------------------- -->
<input type="text" size="50" onkeyup="changeParams()" name="search" id="search" placeholder="Search"></input>
</form>
<div id="test">Choose some filters to see some results!</div>
</form>
</div> <!-- Ends content div -->
</body>
</html>
This is get.php:
<html>
<head>
<style>
/* Bunch of CSS that's not relevant here */
</style>
<script type="text/javascript">
console.log(".....");
var parts = document.querySelectorAll("div.imgContainer");
console.log("Found something:", parts);
parts.addEventListener("click", function(){
document.getElementById("anID").innerHTML = "Test...";
});
</script>
</head>
<body>
<?php
include("/var/www/admin.php");
$year = $_GET['year'];
//Bunch of other variables set here following the same logic, getting data from gallery.php
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
echo '$conn';
}
$sql = 'select * db';
/* ---------- Creating SQL statement ---------- */
$clauses = 0;
if ($year != "All") {
if ($clauses == 0) {
$sql = $sql . ' where year = "' . $year . '" and';
$clauses = $clauses + 1;
} else {
$sql = $sql . ' year = "' . $year . '" and';
}
} /* Bunch of other if statements to get set information and add to sql statement as such */
// Need to chop of the last ' and' from the sql statement
$sql = substr($sql, 0, -4);
$sql = $sql . ' order by year desc';
$result = mysqli_query($conn, $sql);
$num_results = mysqli_num_rows($result);
if ($num_results == 0 or $clauses == 0) {
echo "<p>No matches to your query. Try refining your search terms to get some results.</p>";
} else {
echo "<p>" . $num_results . " results matched your query.</p>";
echo "<div class=results>";
//echo "<div>";
echo '<script type="text/javascript">
function modalFunction() {
document.getElementById("anID").innerHTML = "test";
}
</script>';
while ($row = mysqli_fetch_array($result)) {
$pic = $row['pathToPic'];
$wwwImg = substr($pic, 13);
//echo "<span id=aCard><img src=" . $wwwImg . " height ='250px'>";
//echo "<span class=text>" . $row['fullCardInfo'] . "</span></span>";
echo "<div class=fullContainer><div class='imgContainer'><img class=image src=" . $wwwImg ."></div><p class=text>" . $row['fullInfo'] . "</p></div>";
} // End while of results
echo "</div>";// End results div//</div>";
//echo '<div class="modal"><p id="anID"></p></div>';
} // End else of "if results"
mysqli_close($conn);
?>
<script>
</script>
<div>
<p id="anID">This in a div</p>
</div>
<!--<span>
<p id="anID">This in a span</p>
</span>-->
</body>
</html>
Sorry if that was messy, I chopped out a bunch of stuff that just gets/selects/filters some data. All that works and all variables that are left in there are set in my full code.
But the issue I'm having is writing JavaScript in get.php to change the text in the <p id="anID"> tags. I've tried JS in a few different areas of get.php, from in the <head> tags, to echoing it in <script> tags in the PHP, to pure <script> tags after the PHP statements are done (I think I left them in a few different places).
Problem is that nothing I do works to change the text in the <p> tags I references. Additionally, the console.log statements in the header of get.php don't seem to get called either. They don't fire no matter where I place them in get.php. Console.log works fine in gallery.php so it's not some issue with my browser or anything.
Long term, I will be adding JS query selectors to bring up a bigger image when an image is clicked on, but for now I'm just trying to make ANY JavaScript work in get.php and I'm struggling to do so. I don't see how this is a duplicate of the suggested repeat as I'm not trying to run JavaScript through innerHTML here.
Scratch that, it actually is trying to pass JavaScript through innerHTML as the information from get.php comes from this section of gallery.php:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
console.log("Response: ", this.responseText);
}
So it appears this is a duplicate of the question I linked after all. Apologies. However, there are not great answers to that question, so any tips would be appreciated.
This line:
document.getElementById("test").innerHTML = this.responseText;
Is simply going to add the contents of this.responseText to the element test. I'm sure you understand that much, but what you want to do is completely wrong. The scripts within the output of get.php will NOT be executed at all and you have corrupted your HTML as well by including a second <html><head> and more.
A better approach would be if get.php returned the data from you DB query as a JSON string like so:
$data;
while ($row = mysqli_fetch_array($result)) {
$data[]['pic'] = $row['pathToPic'];
$data[]['wwwImg'] = substr($row['pathToPic'], 13);
}
echo json_encode($data);
exit;
And then back on gallery.php you do something like:
if (this.readyState == 4 && this.status == 200) {
formatResult(this.responseText);
}
// ... snip ...
function confirmJson(str) {
var j = null;
if (str) {
try { j = JSON.parse(str); }
catch (e) { j = null; }
}
return j;
}
function formatResult(str) {
var data = confirmJson(str);
if (! data) {
console.log("result is not JSON");
return;
}
// do stuff with the data
var i, max = data.length;
var h = document.createElement("div");
var img;
for(i=0;i<max;i++) {
img = document.createElement("src");
img.src = data[i].wwwImg;
img.addEventListener("click",function(){ alert("pic:["+ data[i].pic +"]"); },true);
h.appendChild(img);
}
document.getElementById("test").innerHTML = h;
}
What is the easiest way to automate php script to read 1000s of links in a file and produce output?
I have this php code to read links whether they're valid or not. Currently I copy/paste max 500 links in the urls.txt file each time and it produce results, my server do not handle more than that. I need to check 15-20K links.
<?php
$handle = fopen("urls.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$link = trim($line);
$isValid = CheckLinks($link);
if($isValid){
echo "$link". "<br>";
}else{
echo "";
}
}
fclose($handle);
} else {
echo "Could not read urls.txt";
}
function CheckLinks($link) {
$url = $link;
$extpage = file_get_contents($url);
$notValid = strpos($extpage,"This page doesn't exists.");
return !$notValid;
}
?>
What should be added to it to check this amount of links?
Edit: I want it to read 400-500 lines and give output and then next 500 lines and so on.
I'm newbie so forgive me if I ask too much.
You can put the script to sleep after each check:
while (($line = fgets($handle)) !== false) {
$link = trim($line);
$isValid = CheckLinks($link);
if($isValid){
echo "$link<br>";
} else {
echo "";
}
sleep(1); // add this line
}
If 1 second sleep for each iteration is too much, you could use a counter which you increment up to the number of checks you want to perform, then sleep some seconds and reset the counter.
Lastly, if time limit is a problem, you can use set_time_limit(0) to remove the limit altogether.
If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an error:
javascript file (gallery.js)
function goto_anchor(id)
{
var anchor = $("#anchor_" + id);
$('html,body').animate({
scrollTop: anchor.offset().top - 20
}, 1200);
}
php file
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php
$get_cat = 4;
if (isset($get_cat)) { ?>
<script>
$(document).ready(function() {
goto_anchor(4); // this will work PERFECTLY!!!
goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
});
</script><?php
} ?>
I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ??
Thanks
I have such kind of problems before, can not fill
javascriptfunction(<?php echo $phpvirable ?>)
inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;
echo '<script> var get_cat = '.$get_cat.'</script>';
into your php
<?php $get_cat = 4; ?>
surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.
<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?>
// javascript function read predefined javascript virable that confirm work.
// u also avoid using mixed php and javascript statements which looks messy
<script>
$(document).ready(function() {
goto_anchor(get_cat); // this will work then.
});
</script>
First problem
I want to use variable don_settings[don_btn_act] (=checkbox) to define a button action.
IF don_settings[don_btn_act] IS on
THEN -> load checkout
ELSE -> page reload
don_settings[don_btn_act] is definded and it is modified well, so i can turn it on or off. The problem is that I should use it in javascript.
What I have so far:
function reloadpage(){
<?php if(isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on') { ?>
window.location.href = 'index.php?route=dcheckout/checkout';
<?php } else { ?>
window.location.reload();
<?php } ?>
}
It is always executing the window.location.reload() function.
Second problem
in the same way i have the variable don_settings[min_amount]. I use it to define the minimum amount of input.
it is defined in php like the previous varible.
But i should use it in javascript part of tpl file, too.
What I have so far:
function validation(){
if(jQuery('#opton').val() == ''){
alert("<?php echo $drop_empty_msg; ?>");
return false;
}
else if(jQuery('#don_amount').val() == '' || jQuery('#don_amount').val() == '0'){
alert("<?php echo $amount_empty; ?>");
jQuery('#don_amount').focus();
return false;
}
else{
return true;
}
}
i use
|| jQuery('#don_amount').val() <= "<?php $don_settings[min_amount]; ?>"
insteed of
|| jQuery('#don_amount').val() == '0'
but it returns false every time
Sorry, I couldn't understand your problem or your intensions. Try correcting your misspelling, your grammar and please take care of beautiful formatted code!
Nonetheless i have some recommendations for writing maintainable code.
Your problem (#1)
If your browser is always executing the window.location.reload(), the problem does not refer to your javascript. It is your server side code which fails. Your following condition seems to be false:
<?php if(isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on') { ?>
Don't mix your javascript and php up
First of all, compute your necessary values/conditions:
(Preferably into a seperated file)
<?php
$condition = isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on';
?>
Now, you can use it very comfortable and clearly:
function reloadpage() {
var condition = '<?php echo $condition; ?>';
if (condition)
window.location.href = 'index.php?route=dcheckout/checkout';
else
window.location.reload();
}
There are lots of big advantages not to mess up your code.
Also be careful ...
... while injecting code through php to the markup/javascript. Don't offer potential attackers new security holes!