Page1.php (Not Full code)
<?php
class A {
function Session() {
session_start(); // assume session started here
}
?>
<button onclick="play('MyVideo.mp4',event)">MyVideo1</button
<script type="text/javascript">
function play(video,e) {
var videoFile = 'folder1/product.php?v=' + video;
$('#divVideo video source').attr('src', videoFile);
$("#divVideo video")[0].load();
}
</script>
<?php
}
?>
product.php (this page is not a class)
In product.php I am having some code, but if(isset($_SESSION)){ condition failed ,so got to understand that session getting failed.
How do I make session pass in product.php? I cannot use $this in this product.php page.
To pass data to your products.php file you would need to use ajax, then you can pass the variable from the session via ajax to your file.
At first we need to capture the session variable in hidden input
<input type="hidden" value="<?php $_SESSION['variable_name']?>" class="sessionName" >
now the js file
<script>
$(document).ready(function() {
var name = $('.sessionName').val();
$.ajax({
url : 'products.php', // url to your file could be different
type : 'post',
data : {
sessName: name )
},
success : function(data) {
console.log(data);// check console long for output and errors
}
});
});
</script>
in your products.php file
if (isset($_POST['sessName']) ){
$session_name = $_POST['sessName']
//output to console.log in case the variable is set
echo 'Session Variable : '.$session_name;
}else{
//output to console.log when variable is not set
echo 'Session Variable is not Set'; // if not
}
Hope this help.
Related
I'm new into php and I am trying to call code from another file.
I try to use ajax to so, because later I would like to add parameters. But unfortunattely for me nothing appen when I click on my button.
I have a button in my file admin.php that is written like this:
<button onclick="clickMe()"> Click </button>
And in the same file I have my ajax code in script balise:
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: test() {
alert('ok');
}
error : test(){
alert("error");
}
});
}
</script>
And here is the code that I'm trying to call in my ajax, the function test in the file delete.php:
<?php
function test() {
echo "Hello the World! ";
}
?>
I wondering if I maybe need to put the code in delete.php in a function ?
Do you think I need to post the entirety of my admin.php file, even thought a lot of the code is not related to the question ?
EDIT: I forgot to mention; i have require delete file in my admin one:
require 'delete.php';
I don't know jQuery, but I think your code should look something like this:
<?php
// delete.php
// make somthing
return 'Helo Word';
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: response => {
alert(reponse);
},
error: error => {
alert(error);
}
});
}
</script>
let's assume that your js code is working(i'm bad with JQuery). The JS code and the PHP code are living in different worlds but can connect by HTTP requests(XML-AJAX) and some others.
You can do a request to a PHP page like my-domain.com/the-page.php?get_param_1=value(GET method), and you can pass the same params(and a little more) by POST method. GET and POST params are looking like :
param_name=param_value¶m_name=param_value¶m_name=param_value
You can't call directly PHP function(like var_dump('123);), but you can do this request with JS my-domain.com/the-page.php?call_func=myFunc123&printIt=HelloMate
to php page
<?php
function myFunc123($printText) { echo $printText; }
if (array_key_exists('call_func', $_GET)) {
$param_callFunc = $_GET['call_func'];
if ($param_callFunc == 'myFunc123') { myFunc123($_GET['printIt']); }
}
?>
Yes, you can pass any existing function name and call it, but it's not safe in future usage. Above, i use "page" word because you should do a request, not php file read or access.
Here is how I finally did it :
I gived an id to my button:
<button id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Delete</button>
I give in deletedata the parameter this.id, it's a way to give the id of the button as parameter, then I use Ajax to call delete:
<script type="text/javascript">
// Function
function deletedata(id){
$.ajax({
// Action
url: 'admin',
// Method
type: 'POST',
data: {
// Get value
id: id,
action: "delete"
},
success:function(response){
}
});
};
</script>
Here is the tricky thing, I didn't use a fonction as I thought I needed. Instead I did this :
if (isset($_POST["action"])) {
echo "Hello the World! ";
// Choose a function depends on value of $_POST["action"]
if($_POST["action"] == "delete"){
mysqli_query($conn, "DELETE FROM bdd_sites WHERE id = " . $_POST['id'].";");
}
header('Location: '.$_SERVER['REQUEST_URI']);
}
?>
I have a communication problem between home.php page and user.php page.
on Homepage there is link for Log out
<span class="log_out"> <a id="logOut">Log Out</a></span>
When a user click this page ajax call will be started
Here is my ajax call
<script>
$( document ).ready(function() {
$( "#logOut" ).click(function() {
$.ajax({
url: 'class/user.php',
data: "logout=1",
success: function(data) {
$('body').append(data);
}
});
});
});
in user.php I have this
<?php
if(isset($_GET['logout'])){
echo "alert";
$_SESSION['user'] = 0;
}
?>
When I click logout, alert is being appended in body, but session variable was not changed at all.
I dont know what's going on here.
You need to add session_start(); to the top of your user.php file and also debug with the echo after a session is set, otherwise you'll get the warning you're getting at the moment.
if(isset($_GET['logout'])){
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user'] = 0;
Print_r ($_SESSION);
}
I found solution thanks for helping guys, I just need to add session validation on my if else clause, although I have this validation on top of the page, when I added it inside the function, problem fixed
I've got a simple jQuery function and at a certain point (let's say on a button click) I'd like to start a PHP session.
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//here I'd need a way to trigger the session.
});
});
I would assume starting a session from PHP can be done as easily as changing a PHP variable. For example - the PHP can be something like:
<?php
$testVar = null;
if(isset($testVar)){
session_start()
$_SESSION['sessionStarted'] = $testVar;
}
?>
Is there a way for such as session to be started?
<?php
session_start();
if(isset($_GET['login'])) {
if(isset($_SESSION['sessionStarted'])) {
echo 'session is already set';
} else {
$_SESSION['sessionStarted'] = $testVar;
}
}
?>
and client-side:
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//code to redirect to index.php?login=true or make some ajax GET call, doesnt matter
});
});
then you can add like php checks, if session exists, do not echo loginPopupButton and so on :)
The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it
I have a javascript file pet.js. I want to pass a value of variable in test.php. But i can't.
my pet.js is like
$('#pmWorkOrderDetailsPage').live('pageshow', function(event) {
var id = getUrlVars()["id"];
$.get("test.php", { test1: id } );
$.getJSON('pmworkorderdetails.php?id='+id, displaypmWODetails);
});
function displaypmWODetails(data) {
..............code..........
}
My test.php is like
<?php
$ms = $_GET["test1"];
echo $ms;
?>
But it is not working. I tried with Ajax and post method.
It will be best if I can store the variable value on the session in test.php.
Thanks in advance for any help.
1 do not use getUrlVars() it can make site vulnerable to xss
$('#pmWorkOrderDetailsPage').live('click', function(event) {
var id;// get id
$.get("test.php?id="+id,function(data){
var result=$.parseJSON(data);
alert(result["content"])
});
})
test.php
<?php
$id=$_GET['id'];
$data=array();
$data=array("content"=>$id);
echo json_encode($data);
?>