Passing PHP Objects to JavaScript

passing PHP objects to javascript

You can convert the PHP object to an array, and then use JSON function to encode it. After that, decode it from JavaScript. Here are some basic steps:

  1. Convert the PHP object to an array.

  2. Using json_encode() to encode that PHP array.

  3. Pass JSON-encoded data to PHP

  4. Decode JSON from JavaScript using JSON.parse or you can use jQuery.parseJSON to do that.

This is an interesting tutorial about passing a JavaScript object to a PHP object. You might find it useful by watching some other featured/related videos.

Hope this helps.

Pass php object to a javascript function

It is because string generated by json_encode contains double quotes and conflict with onclick="..."

Try to wrap it with htmlspecialchars

<a href="javascript:;" onclick="myfuntion(<?php echo htmlspecialchars(json_encode($test)) ?>);">Send object</a>

Converting a php object to javascript array

I have fixed the problem. First I converted the object array to a normal array in PHP:

$customers = $app['database']->selectAll('customers');

$allCustomers = array();

foreach($customers as $key => $val)
{
$allCustomers[] = $val;
}

Then in the javascript part, I used json encode on this variable, and used a for loop to add each 'name' property to a javascript array, and finally passed it to the autocomplete function likewise:

var js_data = <?php echo json_encode($allCustomers) ?>;

var customername = [];

for (var i = 0; i < js_data.length; i++)
{
customername[i] = js_data[i]["name"];
}

autocomplete(document.getElementById("customers"), customername);

Thanks a lot everyone for offering your help.

Passing a PHP Class object to Javascript and accessing its properties in Javascript function

You can implement the JsonSerializable interface to define what properties you want to make visible when you serialise an object; e.g:

<?php 

class User implements \JsonSerializable
{
private $name;

public function __construct(string $name)
{
$this->name = $name;
}

public function jsonSerialize()
{
return [
'name' => $this->name,
];
}
}

echo json_encode(new User('Bob')); // {"name":"Bob"}

This is an idiomatic way to handle object serialisation in PHP in a transparent and implicit manner, and it allows you to define a preferred shape/format for the json respresentation of your object and encapsulate it within its class definition.

It's quite handy when serialising nested object structures, for example, when you were using value objects - here's a (contrived) example:

class Latitude implements \JsonSerializable
{
private $degree;

public function __construct(float $degree)
{
// validation etc.
$this->degree = $degree;
}

public function jsonSerialize(): float
{
return $this->degree;
}
}

class Longitude implements \JsonSerializable
{
private $degree;

public function __construct(float $degree)
{
// validation etc.
$this->degree = $degree;
}

public function jsonSerialize(): float
{
return $this->degree;
}
}

class Coordinate implements \JsonSerializable
{
public function __construct(Latitude $latitude, Longitude $longitude)
{
$this->latitude = $latitude;
$this->longitude = $longitude;
}

public function jsonSerialize(): array
{
return [
'latlng' => [$this->latitude, $this->longitude],
];
}
}

$coordinate = new Coordinate(new Latitude(0), new Longitude(0));

echo json_encode($coordinate); // {"latlng":[0,0]}

Example: https://repl.it/repls/RelievedLightcyanFolders

How to properly pass PHP object as parameter into called javascript function?

Look at the generated source. Identify the error:

onClick="manageFormView(1, {"
1 2
  1. The quote that starts the attribute value
  2. The quote that finishes the attribute value

Use htmlspecialchars to make data safe for inserting into an attribute value in HTML.


Generating JS to insert into HTML which is inserted into PHP makes things relatively hard to manage.

I recommend inserting the data into data-* attributes and using JavaScript to bind a delegated event handler instead of using onclick attributes.

Passing php-objects to javascript

You can only run the PHP code on the server, so each time you want to call a method on it from JavaScript, you will need to make a new HTTP request to the server.

This will require keeping the object in existence across multiple requests. You can do this by storing it in a session variable (you might need to explicitly serialise it first).


An alternative method would be to:

  • reimplement the class using JavaScript
  • extract the data from the PHP object
  • send that data to the client
  • construct a JavaScript object from the data
  • call the methods on that JavaScript object

Obvious, this will only work if the methods do things that you can achieve with client side JS (or you will have to involve more Ajax).

Is there any way to pass PHP object as JavaScript parameter in HTML?

You could try this:

onClick="functionOne({{ json_encode($basl_officer) }})"

Passing PHP objects to javascript using on-click function on an anchor tag

If $content is in JSON format then you got to decode it into array

    $content = json_decode($content,true);

foreach( $content as $obj ){// $obj is the object
$displayString .= "<a href='' onclick='return func($obj['value'])'> View Details </a>";
}
echo $displayString;

value is the key within the object $obj which you want in the javascript



Related Topics



Leave a reply



Submit