I'm navigating through the site by doing this
$('.account-nav a').on('click', function (e) {
e.preventDefault(e);
var url = this.href;
console.log(url);
$('.account-nav a> .account-tab-current').removeClass('account-tab-current');
$(this).children('.account-tab').addClass('account-tab-current');
$('#user-page-content').remove();
$('#user-page-container').load(url + ' #user-page-content').hide().fadeIn('fast');
var url = $(this).attr('href');
if (url != window.location){
window.history.pushState({path: url}, '', url);
}
Problem is, one of the pages contains a script that doesn't get loaded. that page. I also pass in a php variable. It looks something like this:
<div id ='user-page-container>
<div id ='user-page-content>
//content with $variable
<script>
var myVariable =
'<?php
if (isset($variable)) {
echo $variable;
}
//some jquery animation stuff here
?>';
</script>
</div>
</div>
Nothing inside the script get loaded when the html is loaded through jquery.
Related
So basically i got this code from online which allows you to load body content via ajax/php.
Site i got the code from:
https://www.webdesignerdepot.com/2014/02/how-to-supercharge-your-sites-speed-with-ajax-and-jquery/
If you look at that site(specifically the ajax/php demo, not the first jquery demo) you'll see that ajax loads load.php, then it loads different html files. Ive edited it to load different php files, however the loaded content displays the html code in my php file but not the php code(session name variable).
Here's the custom.js(ajax) file:
$(function() {
$('.left-sidebar a').click(function() {
var $linkClicked = $(this).attr('href');
document.location.hash = $linkClicked;
var $pageRoot = $linkClicked.replace('#', '');
if (!$(this).hasClass("current")) {
$(".left-sidebar a").removeClass("current");
$(this).addClass("current");
$.ajax({
type: "POST",
url: "load.php",
data: 'page='+$pageRoot,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#main-content').html(msg);
$('#main-content section').hide().fadeIn();
}
}
});
}
else {
event.preventDefault();
}
});
var hash = window.location.hash;
hash = hash.replace(/^#/, '');
switch (hash) {
case 'steal' :
$("#" + hash + "-link").trigger("click");
break;
case 'extort' :
$("#" + hash + "-link").trigger("click");
break;
case 'kill' :
$("#" + hash + "-link").trigger("click");
break;
case 'welcome' :
$("#" + hash + "-link").trigger("click");
break;
case 'profile' :
$("#" + hash + "-link").trigger("click");
break;
}
});
here's the load.php file:
<?php
if(!$_POST['page'])
die("0");
$page = $_POST['page'];
// echo $page; // rob, steal, extort, kill, welcome, profile
if(file_exists('pages/'.$page.'.php'))
echo file_get_contents('pages/'.$page.'.php');
else
echo 'There is no such page!';
?>
Here's the welcome.php file:
<?php
if (session_status() === PHP_SESSION_NONE || session_status() !== PHP_SESSION_ACTIVE )
session_start();
print_r($_SESSION);
if (!isset($_SESSION['name'])) {
die(json_encode(array(
"error",
"You must be logged in to view report data."
)));
}
?>
<section id="welcome">
<h2>Welcome Content</h2>
<p class="block">Welcome back, <?=$_SESSION['name']?></p>
</section>
And this is all i see when welcome.php is loaded:
Welcome Content
Welcome back,
After looking at years old post on here a lot of people mentioned needing to have session_start(); at top of file, i tried this and it said "ignoring session start cause a session has already been started".
So i found this on another post where someone else having a similar issue(unfortunately there was no answer for me there[nor for that poster])
<?php
if (session_status() === PHP_SESSION_NONE || session_status() !== PHP_SESSION_ACTIVE )
session_start();
print_r($_SESSION);
if (!isset($_SESSION['name'])) {
die(json_encode(array(
"error",
"You must be logged in to view report data."
)));
}
?>
I put the above code at the very top of welcome.php and when i load welcome.php without ajax i see this:
Array ( [loggedin] => 1 [name] => -Phil (Just-Us) [id] => 1 [role] => Admin )
Welcome Content
Welcome back, -Phil (Just-Us)
But when i load welcome.php via ajax i only see this:
Welcome Content
Welcome back,
UPDATE: So i added the below code to my home.php file of which houses the body content div and said div houses all the dynamically loaded content. And doing this works fine, i see my session name being displayed just fine. So does replacing load.php with welcome.php in the ajax code. So something is going wrong when ajax loads the load.php file and then load.php echo's another php files contents(leaving behind needed php content).
<script>
$(document).ready(
function() {
setInterval(
function() {
$("#main-content").load('pages/welcome.php');
}
, 10000 // 1000ms = 1 second. Lowest i'd go to is 0.05s which is 50ms. (even though the lowest it can go is 4ms apparently. not advised tho)
);
$.ajaxSetup({ cache: false });
}
);
</script>
Why is it that when i use the below code it opens the php file in a new tab rather than loading it into the specified div?
// Create event listener for all link clicks
document.querySelectorAll('page-links').forEach(link => {
link.addEventListener('click', (e) => {
// Retrieve href and store in targetUrl variable
let targetUrl = e.target.href;
// Output value of targetUrl to console
// console.log('A link with target URL ' + targetUrl + 'was clicked');
$("#main-content").load(targetUr);
});
});
I want to send base_url from Controller Book to book.js
This is my function in book.js
function loadPage(page, pageElement) {
// Create an image element
var img = $('<img />');
img.mousedown(function(e) {
e.preventDefault();
});
img.load(function() {
// Set the size
$(this).css({width: '100%', height: '100%'});
// Add the image to the page after loaded
$(this).appendTo(pageElement);
// Remove the loader indicator
pageElement.find('.loader').remove();
});
// MY PROBLEM is here !!! Load the page
// img.attr('src', '../../_library/book/samples/magazine/pages/' + page + '.jpg');
img.attr('src', '<?php echo base_url($source) ?>' + page + '.jpg');
loadRegions(page, pageElement);
}
You cannot use php commands in js files. But instead you can define a variable between script tags in the php file. For example:
example.php
<script>
const EXAMPLE_VAR = '<?php echo base_url($source);?>'
</script>
And you can use it in js file like this:
img.attr('src', EXAMPLE_VAR + page + '.jpg');
I have image url in js variable /w/s/wsh10-black_main.jpg.
Question: How can I get media cache url in js, like: https://mydomain.test/media/catalog/product/cache/c687aa7517cf01e65c009f6943c2b1e9/?
As result I want get full url, like https://mydomain.test/media/catalog/product/cache/c687aa7517cf01e65c009f6943c2b1e9/w/s/wsh10-black_main.jpg
You need to get base url in order to have the complete url you want. You can do this by defining a function that returns base url so,
<?php $baseUrl = $this->getBaseUrl() ; ?>
<script type="text/javascript">
function getBaseUrl() { return '<?php echo $baseUrl; ?>'; }
</script>
then use it in JavaScript:
var urrl = 'http://'+getBaseUrl()+'/w/s/wsh10-black_main.jpg';
You can also refer to this link
https://magento.stackexchange.com/questions/60111/get-base-url-in-js-magento
Hope it helps!
I am new and just doing practices i just did:
var i= [["j.php?i=1"]]; and it sent value to php and prints but when i want some input from user it does nothing. For example:
file j.js
var input = "hello";
var send= [["j.php?i="+input]];
and in j.php
<?php
$e=$_GET['i'];
echo $e;
?>
Any idea or i am totally wrong? I am trying to have some variation. And i really did with window.location.href. But I just want to know how to do in this way var send= [[]]. Thanks
Edit:
your question is not very clear, maybe try this:
var input = "hello";
var url = "/j.php?i=" + input;
var send = [[url]];
But, it's not clear to me what you want to do with your send variable...
Original
You have to send the data to the server either using a a tag (GET method), a form (POST method) or an Ajax request (any Http verb):
<!-- Here you give a unique id to your link -->
<a id="link" href="">your link</a>
<script>
var i = "Hello";
// wait for page to be loaded
document.addEventListener("DOMContentLoaded", function(event) {
// change the href attribute of the link with the id equal to 'link'
// with whatever data contained in the i variable
// this is done after the page is loaded
document.getElementById("link").href = "/j.php?i=" + i;
});
</script>
Then, when you just click the link, it will send the variable named i containgin the value Hello to your php page.
You could also do it in this way:
<a id="link2">your link</a>
<script>
var i = "HELLO";
// wait for page to be loaded
document.addEventListener("DOMContentLoaded", function(event) {
// here we are telling javascript to change the url
// in the browser when the user clicks the link
document.getElementById('link2').onclick = function() {
window.location = '/j.php?i=' + i
}
});
</script>
I have a simple AJAX based site that I have an equally simple geolocation function that redirects a user to a new page when they click a button.
This is the part of my geolocation function that redirects users which, as you will see, redirects people to a page called weather.php;
function showPosition(position) {
window.location='weather.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
The problem is that it redirects the page using a "traditional" page load and thus renders the AJAX page loading I have implemented obsolete.
Is it possible to modify this function and make it AJAX friendly?
This is the full redirect code;
<button onclick="getLocation()">My Location</button>
<script>
var x = document.getElementById("message");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
window.location='weather.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
<script>
Here is how you can do it.
I give you a simple example of a website where the pages are loaded with Ajax. The page is put in the url.
Not like this: weather.php?lat=50.452
But like this: index.php#50.452
The point is: when you change anything right of the #, the page is not reloaded.
And still, there is a system where the url remembers the page
It's not a complete answer to your question, but I hope it gives you the inspiration you need
pages.php
<?php
switch(isset($_GET['p']) ? $_GET['p'] : '') {
default:
$content = 'This is the HOME page ...';
break;
case 'calendar':
$content = 'calendar stuff ...';
break;
case 'contact':
$content = 'contact stuff ...';
break;
}
echo $content;
?>
index.php
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
// load page according to the url.
// We read the url, to the right hand side of the # (hash symbol)
var hash = window.location.hash;
var page = hash.substr(1); // this removes the first character (the #)
loadPage(page);
// triggered by the navigation.
function loadPage(page) {
getAjaxPage(page);
}
// this returns the content of a page
function getAjaxPage(page) {
switch (page) {
default: // = HOME page
var url = '';
case 'calendar':
case 'contact':
var url = page;
}
$.ajax({
url: 'pages.php',
data: {
p: url
},
success: function(data) {
$('#content').html(data);
}
})
}
</script>
<style>
#content {
margin: 15px;
}
</style>
</head>
<body>
<div id="nav">
Home |
Calendar |
Contact |
</div>
<div id="content"></div>
</body>
</html>
Your job ... You should not redirect the client.
It's (something like) a Google Maps thing, right?
What are your intentions there?
Why can't you load weather.php with Ajax? I bet you can.