Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using objects in Ajax calls PHP files

Tags:

oop

ajax

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.

like image 406
ajsie Avatar asked Feb 07 '10 05:02

ajsie


2 Answers

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!

like image 68
Xeoncross Avatar answered Oct 24 '22 06:10

Xeoncross


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.

like image 3
AlexV Avatar answered Oct 24 '22 05:10

AlexV