How to run a php file without refreshing the web page? - javascript

I have a problem. It is my full honor if anyone helps.
First, let me explain the workflow I want. My CMS is Wordpress. I have a webpage (views.php). In this page, I want to show a download button (id=” download-button”) just to users who has the role subscriber. In default, no one has the role subscriber. So, the button is hidden in default. When a user buys a specific product he gains the role subscriber. Now, suppose a user has opened views.php page as a tab in his browser. In this step, the button is hidden. After that, he opens another tab and buys that specific product and he gains the role subscriber. Now, if he refresh the view.php page, the download button is seen. But, I want the user to see the download button without refreshing the page. In this regard, I wrote button.php file to be called in ajax. However, it does not work.
My codes:
html code (written in view.php which is the place of download button):
<div id="div1"></div>
my javascript code (which is put inside view.php file):
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("button.php");
});
});
</script>
my button.php code:
<?php
if (check_user_role(array('subscriber'))) {
echo ('<button id="download-button">Download</button>');
}
?>
I should note that I have written check_user_role php function in views.php.
It would be my honor if you help.
Thanks in advance.
Milad

As stated by smartdroid in one of the answers above, you can subscribe an event listener function to the window.onfocus event. Try following:
document.addEventListener("DOMContentLoaded", function (event) {
window.onfocus = function () {
$("#div1").load("button.php");
}
});
I highly recomment you to read further into javascript events.
For plain javascript:
https://www.w3schools.com/js/js_events.asp
For jQuery:
https://api.jquery.com/category/events/

Hey you have to use Window setInterval() Method, what this method does it will fire in background at your time interval set.
You can call your ajax code to set/show your button
setInterval(function(){
$("#div1").load("button.php");
}, 3000);
Make sure once you do add this button put return false so it wont execute again and again not to increase load on webpage.

$(document).ready event runs only once after the DOM is loaded. So this event will not fire unless page is reloaded.
If the user is buying a subscription in another browser tab and then returns to the original tab, windows.onfocus event will fire.
So you can use window.onfocus event to check for subscription every time view.php tab becomes active, and then show the button when necessary. So you can use something like the following, in your view.php
$(document).ready(function(){
window.onfocus = function () {
$("#div1").load("button.php");
}
});

Add an iframe to your view.php that doesn't need to contain anyting nor be visible.
<iframe name="download" id="if_download" src="blank.html"></iframe>
Target the download-action to the iframe. With some JS:
function download(href) {
window.frames['download'].location = 'download.php?file=' + href;
return false;
}
You may need to wrap the download-action through a php-file to modify its header
download.php:
$file_name = $_GET['file'];
//validate file exists and *remove any ../ - simple:
if (strpos($file_name, '/') !== false) die('yeah right..');
header("Content-Disposition: attachment;filename=\"$file_name\"");
echo file_get_contents($file_name);
die();

Related

How to load javascript after click in to another url

How can i add this JS into a link:
Im in page1.php;
I need click in some link Link
And when i go to page2.php some code load this JS:
javascript:void(lz_chat_change_state(true,false));
Any help?
It seems to be simple but not for me......
Solved !
If page1 has ?chat i execute the javascript in page2;
Link in page1.php?chat
In page2.php
if (isset($_GET['chat'])) {
include_once("js-externo.php");
}else{
// Fallback behaviour goes here
}
In file js-externo.php i put:
window.onload = function() {
void(lz_chat_change_state(true,false));
}
Do you mean you want to call that function when you click on the link?
If yes
Make javascript file seperate.
Inside the link you put a "onclick" event and call the javascript function as:
<a href="page2.php" onclick = "lz_chat_change_state('true','false')">
If you want things to change after going to page2.php particularly then you need to use sessions. Pass a value from page1 to page2. But looking at your function (which I assume is being used as a toggle) it's not necessary.

How to keep the innerhtml content that is changed with the JS onclick function

this is a simple problem but cant seem to solve it.
I want to be able to change the innerhtml content of a link, once is triggered by an onclick function triggered from separate link that actually takes the user to another page (inside the website not external site), I get the script to work but the desirred innerhtml content to be changed dissapears once the page reloads and goes to the other page the link is pointing to. I actually want to keep the change of the text change even if the page is reloaded and taken elsewhere.
The script looks like something like this:
<script>
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
} //Js script that does the innerHMTL change
</script>
eng // button that triggers the onclick function but takes the user to another page inside the site
<a href="http://example.com" id="testchange" >Hello</a> // text to be changed by JS and want to keep the change even if the page is reloaded and taken elsewhere
So any ideas how i could do that? Thanx
For this to work you need some kind of storage. Let's try localStorage:
You first check if the changes has been made before setting the variable, then handle your event:
<script>
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
}
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
//this will save the state of the change
localStorage.setItem('textSet', true);
}
//this will change the text when the page is loaded if the change has been made before.
ready(function(){
if(localStorage.getItem('textSet')){
document.getElementById("testchange").innerHTML = "Get Started";
}
})
</script>
Either use Cookies or Session/Local storage, sessionStorage option below
Data stored in sessionStorage will lasts as long as the browser window is open, whereas localStorage has no expiration time
eng
<a href="http://example.com" id="testchange" >Hello</a>
<script>
function setFlag() {
sessionStorage.setItem('setFlag', 'true');
}
if (sessionStorage.getItem("setFlag"))
document.getElementById("testchange").innerHTML = "Get Started";
</script>
Note: this code will need to be place after your HTML elements ideally at bottom of the page

Click Button on Website with scheduled script

I have a website with external like buttons (from likebtn.com) on it. To encourage users to use them I have a script that randomly gives likes to random posts. However I have the problem that this could only be done via the REST API from likebtn.com if the post already has min 1 Like from a button click. It is not possible for me to send an API request to achieve this (as told by likebtn.com support).
My question now is:
Is it possible (with javascript) to run a cron that opens the url with the post and clicks the like button once?
Any help or tips are appreciated!
I am not sure if I understand your question correctly but you could do something like this.
Run this code from a cronjob on set intervals. It simulates the click of the like button on page load.
http://jsfiddle.net/m3gN2/1/
<?php ?>
<button id="virtualLike">Like Me!</button>
<script>
var likeBtn = document.getElementById('virtualLike'); // get a reference to your element
likeBrn.onclick = clickHandler; // assign its click function a function reference
function clickHandler() {
alert("Button is clicked");
}
document.getElementById('virtualLike').click();
</script>
<?php ?>
Let me know if it was what you wanted and if it works for you.

PHP and window.close in JavaScript

I have a problem. I have a page that when you click a button, a popup with a form is shown. So, I complete some data and I submit. What I want to do is, to submit the form, close the form and refresh the parent page. I don't want to do it with AJAX.
The problem is that in my parent page I have to refresh content with the input information of the form.
So when I refresh, sometimes the data is shown and sometimes not. Do you know why this could happen?
I just use onsubmit="refreshParent()" in my form. The info is stored always in my database, so I think the problem may be that sometimes the refresh catches the new info and sometimes not.
function refreshParent() {
window.opener.location.reload();
window.close();
}
I use this to reload the page that opened a popup window:
<script language="JavaScript">
<!--
function reloadParentPage() {
window.opener.location.href = window.opener.location.href;
if (window.opener.progressWindow) {
window.opener.progressWindow.close()
}
window.close();
}
//-->
</script>
By the way, the code above is called by a link or button in the popup page.
You have a race condition between the script doing the insert and the script reloading the parent.
The solution is to call refreshParent on the page after the submit - that way you know the data is in the database. You don't even have to do it on document ready - return a stub page that just defines and calls refreshParent in the head tag.
In PHP when you run post script, at the end, include this code :
echo '<html><script language="javascript">
parent.location.href="http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].'"; // or any other url
</script></html>';
This will output a javascript that will reload the windows.

Global Javascript link handler

Here's what I have:
A web application that runs in a single HTML page (call it myapp.req), with content coming and going via AJAX
The application can be entered externally with a link such as myapp.req?id=123, and the application opens a tab with the item at id 123
The content on the page is mostly user's content, and many times has inner-application links to myapp.req?id=123
The problem is that clicking a link to myapp.req?id=123 reloads the browser, and removes any content or state that the user had loaded
What I want is to be able to catch link clicks whose destination is myapp.req?id=123, and instead of reloading the page, just open the tab for item 123, leaving anything else currently loaded alone. If the link is for an external website, though, obviously just let the browser leave.
So my question really: Can I have a global link handler that checks if I want to handle the link click, and if so, run some Javascript and don't leave?
I understand I could find all <a>s and add listeners, but my hope is that the solution would only require setting up the listener once, and not adding link handlers every time new content is loaded on the page. Since content can be loaded many different ways, it would be cumbersome to add code to all those places.
Does that make sense?
jQuery's live is what you need:
$('a').live("click", function () {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
Any link will now have this click handler whether it's been added after this is called or not.
Sure you can. Add a clickhandler on the body. So you catch all clicks. Then you have to check if the target of the event or one of its parent is a link with your specific href. In this case stop the event and open the tab.
updated to use .live instead of .click
If you use jQuery, you can add a "live" click event handler to every a href at once:
<body>
click here
<br/>
whatever
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$('a').live('click',function() {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
</script>
This should extract the id from the href's query string and let you do whatever you want with it.

Categories