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!
Related
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');
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.
I've been staring at code too long however when I used a simple script to save a form with:
endif;
header('Location: http:/mysite.com/evo/codesaveindex.php');
?>
at the end the page redirected back to itself just fine, however now I have a longer script here I can't quite figure out where or how to code my redirect:
<?php
session_start();
$directory = 'users/'.$_SESSION['username'].'/';
//here you can even check if user selected 'Delete' option:
if($_POST['Action'] == "DELETE"){
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete))
echo $file_to_delete." deleted.";
else
echo "Error deleting file ".$file_to_delete;
}
if($_POST['Action'] == "SAVE"){
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
}
?>
may be you should use querystring variable while redirecting.
if($_POST['Action'] == "DELETE") {
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete)) {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=1&file='.$file_to_delete);
} else {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=0& file='.$file_to_delete);
}
}
In codesaveindex.php:
if(isset($_GET['deleted'])&& $_GET['deleted']==1) {
echo $file_to_delete." deleted.";
} elseif(isset($_GET['deleted'])&& $_GET['deleted']==0) {
echo "Error deleting file ".$file_to_delete;
}
You can't redirect if the page after html has been outputted.
You need to either use output buffering or redirect using javascript,
or organise it so that the redirect happens before the html is shown.
i have a class written for such thing, should be very easy to use class.route.php
simply do this where you want to redirect: route::redirect('page', http_status);
I am trying to get a parameter from the url with php and write it into a js variable to do some jquery stuff.
my url looks like that
www.example.com/?v=12345
My Code
vnew = "<?php echo $_GET["v"];?>";
if (vnew == null) {
myfunction();
}
else {
$(".myDiv").attr('src','newsrc');
$(".title").html("bla");
};
if the url is like www.example.com shouldn't the value be 'null', so that my function fires?
However if i set it to '12345' the else condition does not fire either.
What is wrong here? Thank you!
Change it like this:
<?php if ($_GET["v"]) { ?>
myfunction();
<php } else { ?>
$(".myDiv").attr('src','newsrc');
$(".title").html("bla");
<?php } ?>
OR
<?php
if ($_GET["v"]) {
echo "myfunction();";
} else {
echo "$(\".myDiv\").attr('src','newsrc'); $(\".title\").html(\"bla\");";
} ?>
to check if your condition is working:
<?php
if ($_GET["v"]) {
echo "myfunction();";
} else {
echo "Hello";
} ?>
It'll never be null, only an empty string. Think about what the JS output is if no value is passed:
vnew = ""; //no PHP output between the quotes, as no value found
In any case you don't need PHP to grab the var, in any case.
var tmp = location.search.match(/v=([^&]+)/), vnew = tmp ? tmp[1] : null;
In this case, the value WILL be null if no value is found.
Try var_dump($_GET["v"]) on the base url. Use that value in your comparison.
i have referred to this two questions call php page under Javascript function and Go to URL after OK button in alert is pressed. i want to redirect to my index.php after an alert box is called. my alert box is in my else statement. below is my code:
processor.php
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
(some imagecreatefromjpeg code here)
else{
echo '<script type="text/javascript">';
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
echo '</script>';
}
it's not displ ying anything(no alert box and not redirecting). when i delet this part echo 'window.location= "index.php"'; it's showing the alert. but still not redirecting to index.php. hope you can help me with this. please dont mark as duplicate as i have made tose posts as reference. thank you so much for your help.
You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
if (window.confirm('Really go to another page?'))
{
alert('message');
window.location = '/some/url';
}
else
{
die();
}
window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location = "index.php";';
echo '</script>';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL
(AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.
Let me suggest that you do this another way..
echo '<script type="text/javascript">\n';
echo 'alert("review your answer");\n';
echo 'document.location.href = "index.php";\n';
echo '</script>\n';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.
Best of luck!
Like that, both of the sentences will be executed even before the page has finished loading.
Here is your error, you are missing a ';'
Change:
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
To:
echo 'alert("review your answer");';
echo 'window.location= "index.php";';
Then a suggestion:
You really should trigger that logic after some event. So, for instance:
document.getElementById("myBtn").onclick=function(){
alert("review your answer");
window.location= "index.php";
};
Another suggestion, use jQuery
Working example in php.
First Alert then Redirect works.... Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.