Reload a javascript using jquery - javascript

I have made a PHP file that shows up a session meter for Joomla's frontend using JavaScript. I have also made an other PHP file that shows the user's details and it reloads using jQuery. What I want to do is, when I press jQuery's reload button, JavaScript session meter reload too.
Session Meter PHP:
<?php // NO DIRECT ACCESS
defined('_JEXEC') or die('Restricted access');
$document = & JFactory::getDocument();
$document->addStyleSheet('***/***/session_meter.css');
include('***/***/scripts.php');
$document->addScriptDeclaration($javascript);
$output = array();
$session = & JFactory::getSession();
$expire = $session->getExpire();
$output[] = '<span id="log_res" class="">'.$expire.'</span>';
foreach ($output as $item){echo $item;}
?>
Session Meter javascript (part of it):
<?php // NO DIRECT ACCESS
defined('_JEXEC') or die('Restricted access');
$javascript = ' var timer_start =$time(); '."\n";
$javascript .= 'blah blah blah...
?>
User Profile JQuery script (part of it):
<?php // NO DIRECT ACCESS
defined('_JEXEC') or die('Restricted access'); ?>
<script>
var $JQ_ = jQuery.noConflict();
$JQ_(document).ready(function(){
$JQ_("#refresh_button").click(function(){$JQ_("#r_points").load('index.php #r_points').fadeOut(1000).fadeIn(1000);});
});
</script>
I am trying to do something like this:
$JQ_("#refresh_button").click(function(){
$JQ_("#log_res").load('index.php #log_res').fadeOut(1000).fadeIn(1000);
});
but it only reloads session meter's span and not its JavaScript!
Any idea?

i don't know what can be done with php...but things you can do are:
Save In local storage (the progress)
Put reloading part in iframe so parent doesn't load again
Wrap Js meter part into function and call it at the top/onload event, so when page reloads it gets called too.
Use eval to call javascript that is in string form

Related

Convert WebStorage (JS/JQuery) content into Blade-ready variable

so I'm currently saving local data via WebStorage. Was wondering if there's a way to convert it to a Laravel Blade-ready variable upon page load. Here's what I've done so far.
$(document).ready(function () {
var data = JSON.parse(localStorage.getItem("data"));
// initialize php code
<?php $var = ?> data <?php ; ?>
});
However this doesnt work since it breaks PHP ruling

PHP refreshing using jQuery doesn't work in IE

I wanted to create a function in javascript/jQuery, that uses php script to refresh some data on my website. I'm using it like this:
function aval()
{
...
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d);
setTimeout(aval,200);
}
where #dost refers to some div at the end of my site
Then, my readadmin.php file looks like this:
<?php
$diff=$_GET["diff"];
$name = $_GET["date"];
$dtyg = $_GET["dtyg"];
$plik = fopen("myfile","r");
$tekst = fread($plik,filesize("myfile"));
fclose($plik);
$bookings = explode(";;;;", $tekst);
for ($i=0; $i<(sizeof($bookings)-1); $i++)
$data[$i] = explode(":::",$bookings[$i]);
echo "<script>";
// here I'm echoing some javascript code, that basically changes styles on my page,
//depending on my variables and data from a file
echo "</script>";
?>
Also, on my site (admin.php) I use login, so my site looks like this:
<?php
session_start();
if(!session_is_registered('pass'))
header('location: login.php');
?>
...html code
login.php:
..something not important, forms to get $_POSTs etc..
<?php
if ($_POST["login"] == $login && $_POST["pass"] == $pass)
{
session_register('login');
session_register('pass');
header("location: admin.php");
}
?>
Now, everything works great on Chrome or Firefox, but not on IE. When I change data in my file, IE doesn't react to this, and keep displaying old data. When I put session_start() and session_destroy() at the begining and end of readadmin.php, then data is refreshing properly, but whatever action I do, it logs me out. Nothing strange here, I start a new session every 200ms so I get kicked.
One more thing: when I'm changing data that goes to readadmin.php from site, it displays proper data back, and then immediately changes to old data.
Please help.
You can add timestamp to url so the browser will not cache the file:
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d+"&t="+Date.now());

How to read a session variable from a php file in JavaScript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
There have been far too many questions on this subject but I still fail to understand.
Case:
Hyperlinked image
OnClick of image: Check if session exists
If session exist, open link
If session does not exist, show login form
onclick is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
I am unable to capture the session value in the var check. Can you advise?
Using jQuery here is a simple example of how to get a PHP $_SESSION into your JavaScript:
session.php
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>
get_session.html (assumes jQuery has been included)
<script>
$(function() {
$('a').click(function(event){ // use instead of onclick()
event.preventDefault(); // prevents the default click action
// we don't need complex AJAX because we're just getting some data
$.get('session.php', function(sessionData) {
console.log( sessionData ); // session data will be 'foo'
});
});
});
</script>
click
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to json_encode() session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.
Make the request to someone file.php
$( document ).ready(function(){//run when DOM is loaded
$.post("file.php", //make request method POST to file.php
function(data){ //callback of request is data
var arr = jQuery.parseJSON(data); //make json decoding
if(arr.logged == 1) //arr.logged is value needs
#do
})
})
file.php
<?php
session_start(); //start session for my dear friend Jay Blanchard
$_SESSION['logged_id'] = 1; //init value for example
$array = array('logged' => $_SESSION['logged_id']);//creat array for encoding
echo json_encode($array); //make json encoding for call back
?>
your javascript is not a very good solution, as it can be hacked easily. One can simply change the value of check to whatever one likes, and even without a login one would be able to access the link of the picture.
A better implementation would probably be something like:
<img src="img.png" alt="" />
checklogin.php would then verify the $_SESSION variable. If validated, you can use header("Location: something.html"); to redirect to where you want to bring the user. If not logged in, you can instead redirect to the login page: header("Location: login.php");
#Sarah
You have to first call the php file via ajax and set the javascript variable as the result. Since the javascript is a client side scripting language hence it can't read server side PHP script.
Hence on click call javascript function
function someFunc(){
//Fire Ajax request
//Set check variable
//and perform the function you want to ...
}
<?php include "sess.php"; ?>
<script type="text/javascript">
var my_global_link = 'testr.com';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
</script>
<a href="#" onclick="show_login('test')" >test</a>
file1.php
<?php
session_start();
$_SESSION["logged_in"] = 1;
?>
sess.php
I have done this using two files. You may have not included session file I guess. Its working fine for me.

php and JavaScript zip code

What i'm trying to do is when a user enters a zip code in the input type i get the value of the input type store in origin_zipcode than add origin_zipcode inside the $url variable. From there it should run the xml and i should be able to display the city and state but it doesn't do that it im trying to make it work like
https://ship.onemorepallet.com/shipment/start?hsCtaTracking=296d76b9-a6fc-4140-83f9-de066c986716|9001d544-e760-4dae-ac72-36cc2922be55?utm_referrer=http%3A%2F%2Fwww.onemorepallet.com%2F
when you enter in the zip code
$("#origin_zipcode").keyup(function(){
var origin_zipcode = $("#origin_zipcode").val();
<?php
$url = "http://zipcodedistanceapi.redline13.com/rest/gNPseXsQyP3daTlKfRB3D0v0mPVC3jJj6zMlwec54fie8EZowAsaBXaXN5zQpjav/info.xml/origin_zipcode/degree";
$xml = simplexml_load_file($url);
$city = $xml->city;
$state = $xml->state;
?>
$(".labelzip").text(<?php echo $city,$state"; ?>);
});
You can't send a jQuery variable to a PHP script unless you refresh the page using one of a few possible methods. This is because while jQuery is client-side, php is server-side. After PHP has finished loading the page, it can't be used again without a page reload.
You can look at these questions for a possible solutions:
How to pass jQuery variables to PHP variable?
jquery 'variable' to php 'variable'
how to pass a jquery variable to php and then display it

How do I render javascript from another site, inside a PHP application?

What I'm trying to do is read a specific line from a webpage from inside of my PHP application. This is my experimental setup thus far:
<?php
$url = "http://www.some-web-site.com";
$file_contents = file_get_contents($url);
$findme = 'text to be found';
$pos = strpos($file_contents, $findme);
if ($pos == false) {
echo "The string '$findme' was not found in the string";
} else {
echo "The string '$findme' was found in the string";
echo " and exists at position $pos";
}
?>
The "if" statements contain echo operators for now, this will change to database operators later on, the current setup is to test functionality.
Basically the problem is, with using this method any java on the page is returned as script. What I need is the text that the script is supposed to render inside the browser. Is there any way to do this within PHP?
What I'm ultimately trying to achieve is updating stock from within an ecommerce site via reading the stock level from the site's supplier. The supplier does not use RSS feeds for this.
cURL does not have a javascript parser. as such, if the content you are trying to read is placed in the page via Javascript after initial page render, then it will not be accesible via cURL.
The result of the script is supposed executed and return back to your script.
PHP doesn't support any feature about web browser itself.
I suggest you try to learn about "web crawler" and "webbrowsers" which are included in .NET framework ( not PHP )
so that you can use the exec() command in php to call it.
try to find out the example code of web crawler and web browsers on codeproject.com
hope it works.
You can get the entire web page as a file like this:
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data('http://example.com/page.htm');
$my_file = 'file.htm';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $returned_content);
Then I suppose you can use a class such as explained in this link below as a guide to separate the javascript from the html (its in the head tags usually). for linked(imported) .js files you would have to repeat the function for those urls, and also for linked/imported css. You can also grab images if you need to save them as files.
http://www.digeratimarketing.co.uk/2008/12/16/curl-page-scraping-script/

Categories

Resources