Using objects in Ajax calls PHP files - php

I have instantiated a class in my index.php file. But then I use jQuery Ajax to call some PHP files, but they can't use my object that I created in the index.php file.
How can I make it work? Because I donĀ“t want to create new objects, because the one I created holds all the property values I want to use.

Use the session to save the object for the next page load.
// Create a new object
$object = new stdClass();
$object->value = 'something';
$object->other_value = 'something else';
// Start the session
session_start();
// Save the object in the user's session
$_SESSION['object'] = $object;
Then in the next page that loads from AJAX
// Start the session saved from last time
session_start();
// Get the object out
$object = $_SESSION['object'];
// Prints "something"
print $object->value;
By using the PHP sessions you can save data across many pages for a certain user. For example, maybe each user has a shopping cart object that contains a list of items they want to buy. Since you are storing that data in THAT USERS session only - each user can have their own shopping cart object that is saved on each page!

Another option if you dont want to use sessions is to serialize your object and send it through a $_POST value in your AJAX call. Not the most elegant way to do it, but a good alternative if you don't want to use sessions.
See Object Serialization in the documentation for more informations.

mm, you should store in session, $_SESSION["someobj"] = $myobj;, and ensure that when you call the Ajax PHP file this includes the class necessary files which defines the class of $myobj and any contained object in it.
Could you be more specific? I can try.
This is how I create an object then assign it to a session variable:
include(whateverfilethathastheclassorincludeit.php)
$theObject = new TheObjectClass();
//do something with the object or not
$_SESSION['myobject'] = $theObject;
This is how I access the object's members in my Ajax call PHP file:
include(whateverfilethathastheclassorincludeit.php)
$theObject = $_SESSION['myobject'];
//do something with the object

If you don't want to move your object that is in your index.php, have your ajax make a request to index.php but add some extra parameters (post/get) that let your index.php know to process it as an ajax request and not return your normal web page html output.

You have not provided code, but what I guess is that you need to make your instantiated object global for other scripts to see it, example:
$myobject = new myobject();
Now I want to use this object elsewhere, probably under some function or class, or any place where it is not getting recognized, so I will make this global with the global keyword and it will be available there as well:
global $myobject;
Once you have the object, you can put it into the session and then utilize it in the Ajax script file.

As others have suggested, $_SESSION is the standard way to do it, in fact, that was one of the reasons, that sessions where invented to solve. Other options, i.e. serializing the object rely on the client side to hold the object and then return it untampered. Depending on the data in the object, it is not a good solution, as a) the object may include information that should not be available on the client side for security reasons and b) you will have to verify the object after receiving it.
That said, and if you still want to use the object on the client side, then JSON is an option for serializing object data, see JSON functions in PHP.

Based on most of the answers here, referring to storing the object in $_SESSION, is it more efficient to store only the individual properties that need to be accessed in AJAX as opposed to the whole object, or does it not matter?
E.g.
$_SESSION['object'] = $object;
vs
$_SESSION['property1'] = $object->property1;
$_SESSION['property2'] = $object->property2;
I know the OP is asking about accessing the entire object, but I guess my question pertains to if it's just a matter of only accessing certain properties of an object, and not needing to access methods of a class to alter the object once it's in AJAX.

Related

Passing complex objects via PHP

I've been researching a bit but I cannot find any way of doing this...
I need to pass an instance of a complex PHP class (formed by properties, functions, arrays, etc.) between different pages. The variable of the object is called $Model; I've been trying to use the GET method and "serialize" / "unserialize", but I cannot retrieve the object in the new page...
I'm trying to pass the object as follows:
echo 'Pass Model Object';
Then, I'm trying to retrieve it like this:
if(isset($_GET['modelobject'])) //$_GET when used in a link!
{
$ModelObjPost = unserialize($_GET['modelobject']); //$_GET when used in a link!
echo "POST: Model Object retrieved<br>";
var_dump($ModelObjPost);
}
There could be some kind of problem with certain characters in the serialization (I'm not sure, though), as the link that should send the object sometimes gets printed as (and it is also recognized as a URL):
r";s:3:"new";b:0;}i:2;(... MORE STUFF ...)s:9:"dbModelId";s:1:"1";}">Pass Model Object
Should I try a completely different approach, or this method should work, but there is just something I'm doing wrong?
Thanks in advance for your time!
Warning: I would discourage serializing a class and placing the result in an end-user readable location. This probably reveals far more about your application than you should be disclosing publicly.
Let's clear up some terminology right up front. I assume you know this, but just to be clear... A class is both the code that defines the behavior you want for an object and data (properties). An instance is when you use the new keyword on a class to create a usable object using that class definition.
By the very nature of how PHP works (typically), all instances are unloaded and deleted after a page loads. It cannot survive in memory to be used on a second page.
Typically you would create a file that contains the class definition you're trying to pass between pages, and create a new instance of the class on each page.
If you're trying to keep state between pages, you should look at using sessions. If you choose to use sessions, and want to keep an instance of your class inside your session, keep in mind what I said above - it will be deleted and recreated between the pages. You will need to make sure your class is set up to reload everything it needs to operate. PHP provides for a "magic" method to do this: __wakeup() in this method, you will need to restore the object back to the same state it was in on the previous page load.
Other ways to pass data between pages (or page loads) would be arrays for HTTP GET or POST.
$data = array( 1,2,3,4, 'a' => 'abcd' );
$query = http_build_query(array('aParam' => $data));
$url = 'somepage.php?data=' . $query;
Forms may be created to pass arrays of data by utilizing array notation in the form field names
<form action="somepage.php" method="post">
<input name="option[a][]" value="option a,0">
<input name="option[a][]" value="option a,1">
<input name="option[b][]" value="option b,0" />
<input name="option[b][]" value="option b,1" />
<input name="option[]" value="option 0" />
</form>
Access this data like this:
<?php
echo $option['a'][0];
echo $option['a'][1];
echo $option['b'][0];
// etc
Your two best options in this case would be to either:
Use a $_SESSION variable. You could save the object as $_SESSION['Model'] and access that on each page that you need to use it. Be sure to call session_start(); on each of those pages to resume the session.
Use urlencode(serialize($Model)) in the URL and use urldecode() on the next page to make sure that you don't have encoding issues in the URL. json_encode() and json_decode() would also be a good option for object to string serialization.

Maintain php object state

My php code creates a "School" object which is (among other functions) able to return several forms which are being ,on submit, handled by php.
Thru one of these forms i'm able to add a "SchoolClass" object to a array in the "School" object but it seems that the "School" object is recreated at some point after i add the "SchoolClass" object. This re-creation makes the array of "SchoolClass" disappear.
The functions that returns the forms are static, but the functions where "SchoolClass" objects are added to the array are not static; ("School::ShowStudentForm() and School->RegisterSchoolClass($class)")
Both the class definition and the php-script which handles the form after submit is in the same file(index.php). I had the idea that keeping both the class code and the form handling code in the same file would do the trick, but it did not make a change.
Question 1: how do i maintain the "School" object for as long as i need it?
Question 2: is it ok to create a class with only static methods and write the data directly to a file or database to avoid the whole problem or just skip the whole object approach and just use "normal" functions?
Yes, this problem is probably encounterd before and therefore also answered before but i have not been able to find a answer which i understand.
OK....i figured it out.
I can use the $_SESSION variable to store it.
Now i do like this in the start of the page:
$school = null;
if(!isset($_SESSION["school"]))
{
$school = new School;
$_SESSION["school"] = $school;
echo "New school <br>";
} else {
$school = $_SESSION["school"];
}

retrieving contents of a class object in php

i am trying to get the contents of another class object into php code.
a class object contains
$Raiwind = new gridcell();
$Raiwind->place="raiwind";
$Raiwind->latitude="31.4279";
$Raiwind->spatial[] = array(
array('lda','31.4104',3),
array('ali','31.3998',3),
array('multan','31.4675',10));
$Raiwind->temporal[]=array(
array('lda',00.04),
array('ali',00.06),
array('multan',00.26),
array('dha',00.33));
$Raiwind->taxi=array(array(8899, 15.56));
now in another web page i am trying to get the taxi array contents matched with $raiwind.
how to code that.
Store the object in session.
I give you a link if you don't know how to do this.
Exemple:
//start session
session_start();
$obj = new Object(...);
//do something
$_SESSION['object']= $obj;
Now your have your object in session, and you can use it everywere in your application.
You can also serialise the object for pass it in GET or POST.
Same problem

Ajax, JavaScript, PHP/HTML and variables

Ok... so I have a game I'm developing and I'm running into a scope problem I think...
It starts in my js file fired by a click on the card the player wants to play:
It starts in my js file:
function playCard(playerId, card){
$.post("support_files/Blades_functions.php", {
method:'playCardFromHand',
playerID:playerId,
cardName:card
},function(data){
var attr = new Array();
attr = data.split("/");
alert(data);
$("#playerAttackPower").html(attr[0]);
$("#playerDefensePower").html(attr[1]);
$("#playerHealth").html(attr[2]);
$("#playerAttackMod").html(attr[3]);
$("#playerChargeCounters").html(attr[4]);
$("#playerSpecialAttackCounters").html(attr[5]);
});
}
Then into my php file
function playCardFromHand(){
$weapons = new WeaponCards(); // this is basically a class with variables(card objects) (my answer to php not having enums really)
$player = $theGame->gamePlayers[$_POST['playerID']]; // this is the variable ($theGame) that I declare in my main php file with all the markup on it. I'm including my functions file in my main file so the variable should be visible... I've tried using "global" keyword as well and that didn't do anything different...
$cardName = $_POST['cardName'];
$card = $weapons->$cardName;
$card->applyCard($player);
echo $player->getAttack()."/".$player->getDefense()."/".$player->getLife()."/".$player->getAttackMultiplier()."/".$player->getChargeCounters()."/".$player->getSpecAttackCounters();
}
So my problem is that the $player variable is null so nothing is displayed. Basically, as you can see in the callback on the js function, I'm just parsing out the string and updating the player's stats on the main php page. So is this a scope thing? Is there some way to make PHP persist that $theGame variable, which is an object itself, so that I can access/modify it in my functions file?
Any ideas would be most helpful... I've tried using the global keyword, as I said... tried making the variables in the $theGame object public, tried making them private and using getters and setters... I've had a separate problem with that actually, can't seem to get my functions to work on my objects in general, have just been making my variables public and accessing them directly instead of using the getters and setters. Anyway. Please help! I'm so frustrated!!! lol
Thanks,
Jon
Make sure that you declare your PHP variable as global, otherwise you have to get the POST variable inside of your function.

Storing objects in PHP session

The PHP documentation says "You can't use references in session variables as there is no feasible way to restore a reference to another variable."
Does this mean I can't have things like:
session_start();
$user = new User;
$user->name = 'blah';
$_SESSION['user'] = $user;
I have tried to store a simple string and a User object in session, the string always persists between pages to pages, or after page refresh. However the User variable is lost in $_SESSION(becomes empty).
any idea?
Edit:
I have confirmed that session_id is the same in all of these pages/subpages,before & after page refresh.
Edit:
Strangely, after I tried serialize and unserialize approach below, the serialized user object(or string) in session still still disappears!
Edit:
finally I figured out what the bug was, looks like somehow $_SESSION['user'] gets overwritten by some mysterious force, if I use any variable other than 'user', then everything's fine. PHP(at least 5.3 which is the version I'm using) does serialize and unserialize automatically when you put object in the $_SESSION.
session_start();
$user = new User();
$user->name = 'blah'
$_SESSION['myuser'] = $user;
You need to use the magic __sleep and __wakeup methods for PHP 5 Objects.
For example in the following code block:
$obj = new Object();
$_SESSION['obj'] = serialize($obj);
$obj = unserialize($_SESSION['obj']);
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
Your code example isn't using references as the documentation was referring to. This is what php means by references:
$var =& $GLOBALS["var"];
As to putting objects into the session, PHP can store objects in $_SESSION. See http://example.preinheimer.com/sessobj.php.
What you are seeing is a bug in the order of calls to __sleep and __destruct (__destruct is being called before __sleep) and the session module fails to serialize the object at shutdown. This bug was opened on Sep 1, 2009.
For safe serialization and unserialization encode and decode with base64_encode() and base64_decode() respectively. Below I pass a serialized Object to a session and unserialize it on the other page to regain the variable to an object state.
Page 1
<?php
require $_SERVER['DOCUMENT_ROOT'] .'/classes/RegistrationClass.php';
$registrationData= new RegistrationClass();
$registrationData->setUserRegData();
$reg_serlizer = base64_encode(serialize($registrationData)); //serilize the object to create a string representation
$_SESSION['regSession'] = $reg_serlizer;
?>
Page 2
<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'] .'/classes/RegistrationClass.php';
$reg_unserilizeObj =
unserialize((base64_decode($_SESSION['regSession'])));
$reg_unserilizeObj->firstName;
?>
This article describes issues that may be faced by not doing so.
issuses with php serialization/unserialization
You were right saying you can not store references in sessions variables
assigning an object in PHP 5 and above is doing just that assigning the reference not the obj
That its why you would need to serialize the object (implementing also __sleep in the Class) and assigning the string to a session variable
and deserializing it later (implementing also __wake in the Class) from the session variable later on.
That's the expected behavior. Storing a reference to an object would only work if the memory location for the object didn't change. In a stateless protocol like HTTP, application state is not persisted between requests. The next request may be handled on another thread, process, or another server.
Given the inherent stateless nature of a web application, holding a pointer to a memory location is useless. Therefore the object's state must be broken down into a storage format, saved or transmitted, and then reconstituted when needed. This process is known as Serialization.
You can choose to serialize the entire object into session (which maybe dangerous depending on the depth of your object graph, since your object may hold references to other objects and those would need to be serialized as well), or if the object can be reconstituted by querying the database on the next request you may just stash an ID in the session.
[EDIT]
JPot pointed out that objects are automatically serialized to $_SESSION, so explicit serialization isn't necessary. I'll leave the answer for posterity, but obviously it doesn't help your problem.

Categories