Issues with GET Ajax method - php

I started to work with ajax some time ago, but I'm getting a strange problem that I don't have any idea of the reason.
I work with 3 files to make all my pages: a header, a footer and the content files. In header I put my ajax code that is something like this:
$(document).on("click", '.ajax a', function (e) {
e.preventDefault();
var href = $(this).attr("href");
if (href == location.pathname) return; // Prevent from refresh on click the current page link
loadContent(href); // Make the AJAX call
window.history.pushState('', '', href); // Changes the link
});
//MAKE BACK/FORWARD WORKS
window.onpopstate = function(event) {
loadContent(location.pathname);
};
///////////////////////////////////////AJAX ITSELF
function loadContent(url){
$.ajax({
url:url,
type:'GET',
error: function(){
alert("Oops, something went wrong :(");
},
success:
function(data){
$('#content').html(data); // Inject page into the content div
document.title = $("#titulosads").val(); // Changes the page title
}
});
}
After that I open the #content div that will be closed in footer.
And in each page file, I use these codes for include the header.php and the footer.php when is needed:
function includeheader($pagename, $pagedescription)
{
$title = $pagename;
$description = $pagedescription;
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo "<input type='hidden' id='titulosads' value='".$title."' />";
} else {
include 'header.php';
}
}
And for the footer:
function includefooter()
{
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
} else {
include 'footer.php';
}
}
So, basically, this is my pages:
<?php
include_once 'includes/checkajax.php';
includeheader('Contact');
?>
Content of the page here!
<?php
includefooter();
?>
Well, this is my issue: it gets a little strange when I use the GET method of AJAX.
Things get duplicated when you click in other link and back on the first. You can check it on http://feely.com.br
When I change the method to POST or when I activate chrome dev tools that disable the cache, everything works fine.
Oh, there is a lot of errors on console that I don't have idea about what they mean.
A picture of the errors:
Help :(

Well, if you yourself already found out that this is a caching issue, then follow that hint:
Either take care that you mark your requests to not getting cached by the browser by means of http headers you add, or use a unique URL for the requests, that is typically done by simply adding a micro time based request argument to the URL. The preferred method however is to use http headers to tell the browser how to handle a response payload. That is what http headers are for...
PHP offers the header() function for that:
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

I think you was loading a whole pagecontent inside a part of a similar page. So, instead of paste the content in div#content you have to paste it over the whole page. Give it a try.

Related

Don't display a button while file exists on server

I'm trying to display a download button on an HTML page only when a specific file on the web server is deleted. I thought I'd use a CSS display: none; then a PHP script with a while loop that'd look like this :
while (file_exists("/aaa/file.txt")) {
sleep(5);
}
//set display property of the invisibleLink class to block and continue
The thing is I don't know how to do this last step and every thread I've seen about modifying CSS with PHP doesn't work with my use case.
PHP executes before anything is displayed on the screen, so you are probably not going to be able to do that: the code would simply sleep for 5 and then continue with generating the rest of the html before displaying to the user.
What you might want to do instead is mark the button as display: none and then when the page is done loading have a js function that calls a php page that returns whether the file exists or not. Have the js function loop until the php page says the file is gone, then have the js function display the button and stop looping.
<button type="button" id="test_btn" style="display: none;">Download</button>
<script type="text/javascript">
$(document).ready(function () {
checkFile();
function checkFile() {
$.ajax({
url: '/path/to/file_checker.php',
type: 'GET',
success: function (data) {
if (data === "deleted") { // or whatever you want the response to be
$('#test_btn').show();
}
else {
checkFile(); // you can add a setTimeout if you don't want this running too often
}
}
});
}
}
</script>
Then your file checker php can be something similar to what you had:
if (file_exists("/aaa/file.txt")) {
echo "exists";
}
else {
echo "deleted";
}
Just build the button and hide it with a class like this:
<style>
.hidden{ display:none;}
</style>
<?php
if(!file_exists("path") ){ $class = "hidden" }
echo "<input type='button' class='$class' name='stuff'>woo</button>";
?>

Download file after 10 seconds

I have created a download page that has a link to a file, I would like the file to download automatically after 10 seconds but am unsure of how to do this. The link to the file is stored in a cookie and is accessed on the download page and stored in a $file variable.
The link to the file will be similar to this:
https://cloud1.taccess.co.uk/cloud/uploads/eed376ad76d1f74b597aa2e21121f7e6tantami_cloud_file_580a40c1eff3af7484ef592c10bff10047b373cdc5dfd.pptx?AWSAccessKeyId=AKIAJ56YO6753B2RUT2Q&Expires=1477473886&Signature=mF6Zy1Mqo3HM5g%2B4cSePaXF9vM8%3D
This points to the file and includes the required permissions for the file to be downloaded. So in short, I am looking for a way for this link to be opened after 10 seconds so that the file can be downloaded.
Your tag is PHP. So I assume you want to add some delay for download, I think this
will help you
$filename = "your filename";
header("content-type:application/any specific header"); // set the header
// your content
sleep(10) // will add delay for 10 sec
header("Content-Disposition: attachment; filename=$file_name"); // will download your file
in javascript you could do like this
use heroku api to bring the page
<div id="hidden" style="display:none"></div>
<script type="text/javascript">
$(document).ready(function(){
// var text = 'your url';
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'https://login.yahoo.com/', // like yahoo
function (response) {
var res = response;
$('#hidden').append(res);
});
});
after your page is placed inside hidden div then you could do something like this
setTimeout(function(){
$('#hidden').show();// or fade, css display however you'd like.
}, 1000);
});

Update text file on button click

I want to make a website where there is a button, and when you click it make it change some text (saying either true/false). The text must change when the user clicks the button, but not just for the one user, for every user that's on the site.
The way I'm trying to do it is I have a text file, and so far all I've got is some text on the page that every 500 milliseconds is refreshing to display whatever is in the text file.
So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)
Thanks,
Fjpackard.
Update
index.php:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<body>
<div id="theDiv"></div>
</body>
<script>
$("document").ready(function(){
$("button").remove();
setInterval(function(){
$("#theDiv").load("file.txt");
},500);
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// mobile code here
}
else {
$("body").prepend("<button>Toggle</button>");
$("#theDiv").css("visibility","none");
$("button").click(function(){
myClick();
});
}
});
function myClick() {
var url = ''; //put the url for the php
value = $.post("", {}).done(
function(data) {
$('#theDiv').html(data);
}
);
}
</script>
script.php:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = 'file.txt';
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
echo 'false'; //this is what we return to the client
}
else
{
file_put_contents($file, 'true');
echo 'true'; //this is what we return to the client
}
exit();
}
?>
Onclick of that button make one Ajax request using jQuery or simple javascript. Which will update that text file.
How to make Ajax request in jQuery:
http://api.jquery.com/jquery.ajax
Iinjoy
You will be reading a file on the server with the name "file.txt".
Let's say you have this code to refresh the page each 500 milliseconds:
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function myClick()
{
//somehow get and change the value
/*var value = ???*/
$('#theDiv').html(value ? 'true' : 'false');
}
$("document").ready(
function()
{
setInterval(
function()
{
$("#theDiv").load("file.txt");
},
500
);
}
);
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">
So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)
script.php:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = 'file.txt';
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
}
else
{
file_put_contents($file, 'true');
}
exit();
}
?>
This is the server side code that updates the file.
index.php
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function myClick()
{
var url = 'script.php'; //put the url for the php
$.post(url, {}); //avoiding using "done", let the timer update instead
}
$("document").ready(
function()
{
setInterval(
function()
{
$("#theDiv").load("file.txt");
},
500
);
}
);
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">
And here we are making an ajax request to execute that code from the event handler of the button.
Note: the code $.post(url, {}) will make the request. In this case we are not using the done continuation (that would be executed when the server sends its response) to avoid a race condition with the timer.
So far you have been reading file.txt. You could take advantage of script.php to provide the current value. That will be done in a GET request instead of a POST.
script.php:
<?php
// disable cache by HTTP
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
// disable cache by IE cache extensions
header('Cache-Control: post-check=0, pre-check=0', false);
// disable cache by Proxies
header("Pragma: no-cache");
$file = 'file.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// POST request
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
}
else
{
file_put_contents($file, 'true');
}
}
else
{
// not POST request, we assume it's GET
echo file_get_contents($file);
}
exit();
?>
index.php:
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function myClick()
{
var url = 'script.php'; //put the url for the php
$.post(url, {});
}
$("document").ready(
function()
{
setInterval(
function()
{
$("#theDiv").load('script.php');
},
500
);
}
);
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">
As you can see, we are now using script.php both to read and to write. This facilitates doing checks on the server. For example: maybe not all users are allowed to update the value or to retrieve it.
Note: There is a race condition on the saver. If two clients makes requests on the server "at the same time" their updates on the file will overlap and the result will look like only one update happened (instead of two).
Observations:
You may want to do additional checks on the server, for example verify the user session. Maybe not everybody is able to update the state.
If you want to do more operation on the same PHP code, you may want to send variables on the POST request. In this case we are not doing that (we just send {}).
Also consider:
Using Web Sockets that provide a more versatile mechanism to push notification to the clients. There are some libraries for this, see the question Is native PHP support for Web Sockets available? where some alternatives are pressented.
Using an storage format (such as ini, json, xml...) that will provide your the ability to store more info in the same file.
Using a database for storage. Databases will solve the race condition on the server, and provide means to store more complex data. The database engine doesn't need to be MySQL... in fact, for this use a document based database may be better idea (most of them often refered as NoSQL, although some of them actually support SQL).

Add Redirect URL link to JS Function

How can I add redirect URL link to JS function (example form action to : session.php) in below code.
I've tried with another way code, but it still can't function.
$(document).ready(function() {
$("#submit_butt").click(function() {
var conf = {
frequency: 5000,
spread: 5,
duration: 600
};
/* do your AJAX call and processing here...
....
....
*/
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Invalid username or password!</p>');
// clear the fields to discourage brute forcing :)
$("#password").val("");
document.forms['login_form'].elements['username'].focus();
});
});
You can try this
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
https://developer.mozilla.org/en-US/docs/DOM/window.location
Ref: How to redirect to another webpage in JavaScript/jQuery?
you can use this..
window.location.href = "http://www.google.com";
you can try
<script>
function name(){
window.location ='abc.php';
}
</script>
you can by breaking into php code inside your javascript
$(document).ready(function()
{
<?php
someFunction();
?>
});
but only if your javascript is in a php file so it can be processed by php. So if your linking to a .js file that needs to be changed to .php

PHP publishing JavaScript

I have a PHP script that publishes customised JavaScript based on the parameter, with header type as text/javascript. This PHP URL is included in the src of a <script> tag. However, there seem to be an issue, because the script seems to be nonfunctional. As in, I have an alert inside the script, which should be executed immediately after inclusion, but it's not happening. Where am I going wrong?
Server Side PHP
<?php
//Exploding the path after the file widget to get user details
$expl = explode("/",$_SERVER['PATH_INFO']);
$c=count($expl);
//Handling the cases as widget/a widget//a etc
switch($c) {
case 2:
if(empty($expl[0]) && !(empty($expl[1]))) pumpValid();
else pumpInvalid();
break;
case 3:
if(empty($expl[2]) && !(empty($expl[1])) && empty($expl[0])) pumpValid();
else pumpInvalid();
break;
default:
pumpInvalid();
break;
}
function pumpValid() {
global $expl;
//Checking for a matching account in the urllist
include('embedUrl/urllist.php');
if(isset($customerList[$expl[1]])) {
header("Content-Type: text/javascript");
//Setting the host path for fetching the JS files later. As in stage or vidteq.com
echo "alert('h');";
echo 'var _serverHostUrl="http://'.$_SERVER["SERVER_NAME"].eregi_replace('widget.*','',$_SERVER["REQUEST_URI"]).'";';
}
else
pumpInvalid();
}
function pumpInvalid() {
//Should redirect to error/home page
echo "Are You Nuts";
}
?>
function init() {
alert('hi');
addJSinHead('jquery-1.3.2.min.js');
addJSinHead('OpenLayers.js');
addJSinHead('json2.js');
addJSinHead('dom-drag.js');
addJSinHead('globals.js');
}
function addJSinHead(fileName) {
var head=document.getElementsByTagName('head');
var new=document.createElement('scrpit');
new.src=_serverHostUrl+'/js'+fileName;
new.type='text/javascript';
head.appendChild(new);
}
init();
Inclusion in client side HTML
<script src='http://rak/cvs/widget/cis/' type='text/javascript'></script>
Is the alert that should be executed inside of a function block? If so then you first need to execute the actual function.
Also try copying and pasting the javascript src url directly into the browser's url bar.
If the above didn't help, some code to analyze would be useful.
You can check with Firebug to see if the output of the script is what you expect and that the headers are being sent as you expect.
You'll need to provide some code for further help.
EDIT:
I don't see anywhere that you output a header in php:
header('Content-Type: text/javascript');
EDIT2:
It looks like you're calling the pumpValid function before it's defined.

Categories