How can I send a PHP object using ng-click

Understanding how to pass a PHP variable in ng-click is one thing, but passing a complete PHP object through the ng-click function seems to be a challenge. I have successfully passed a JavaScript object through it, but when it comes to passing a PHP object, I am stuck. Any help on this matter would be greatly appreciated. Below is the script I am working with:

<ul>
   <!-- Retrieving main products -->
                            <? 
                              if(isset($products)):
                                foreach($products as $row):  

                            ?>
                                <li>
                                    <a href="products/<?=$row->sub_c_id?>/<?=$row->pid?>" class="title colr"><?=$row->pname?></a>
                                    <a href="products/<?=$row->sub_c_id?>/<?=$row->pid?>" class="thumb">
                                     <img src="<?php echo base_url(); ?>uploads/<?=$row->product_pic?>" style="width:157px; height:181px;" alt="" />
                                    </a>

                                    <div class="prodbuttons">
                                        <p class="price bold"><?=$row->pprice?></p>
                                        <a class="cart upper" ng-click="addtocart(<?=$row->pid?>,'<?=$this->session->userdata('session_id'); ?>','<?=$row->pname?>',<?=$row->pprice?>,<?=$row->pquantity?>,<?=$row->sub_c_id?>,'<?=$row->product_pic?>','<?=$row->color?>','<?=$row->size?>',1)">Add to Cart</a>
                                        <a ng-click="check(<? json_encode($row) ?>)">email me</a>
                                    </div>
                                </li>
                             <? endforeach; endif; ?>  


                            </ul>

I also tried the following approach, but encountered an error:

<a ng-click="check(<? echo json_encode($row) ?>)">email me</a>

This is the AngularJS script being used:

$scope.addtocart=function(pid,current_session_id,pname,pprice,pquantity,sub_c_id,product_pic,color,size,qty){
             $scope.errors.splice(0, $scope.errors.length); // remove all error messages
             $scope.msgs.splice(0, $scope.msgs.length);
             $http.post('/product/ng_insertincart', { pid : pid, current_session_id : current_session_id, pname : pname, pprice : pprice, pquantity : pquantity,sub_c_id : sub_c_id,product_pic : product_pic,color : color,size : size, qty : qty}
                        ).success(function(data, status, headers, config) {
                            if (data.msg != '')
                            {
                                $scope.msgs.push(data.msg);
                                console.log(data);
                            }
                            else
                            {
                                $scope.msgs.push(data.msg);
                            }
                        }).error(function(data, status) { 
                            $scope.errors.push(status);
                        });
        }
     $scope.check=function(argument) {
         console.log(argument);
     }

Answer №1

Wow, it seems like your client is really pushing you to do some unconventional things. If you have no other choice but to follow their lead, one way to handle this situation is by moving the PHP logic into your Angular controller. Here's an example:

var controller = function()
{
<?php 
    // Convert product objects to array then encode as json
    $items = array();
    foreach($products as $product) {
        $item = array(
            'pid' => $product->pid,
            'pprice' => $product->pprice,
            ...
        $items[] = $item;
     }
     $productsJson = json_encode($items);
?>
$scope.products = angular.fromJson('<?php echo $productsJson; ?>');

By doing this, you'll have a more structured products array in your controller that you can conveniently use with ng-repeat in your templates. Additionally, consider performing the conversion of $products to a JSON string in your main PHP code before passing it to the template. There are also serializers available that can aid in converting PHP objects into arrays: http://symfony.com/doc/current/components/serializer.html

Answer №2

To ensure that the object is passed correctly as JSON and handled properly in your AngularJS function, be sure to wrap it in single quotes when calling the scope function. Here's an example:

<a ng-click="check('<? echo json_encode($row) ?>')">email me</a>

Then, in your function:

$scope.check = function(obj) {
obj = angular.fromJson(obj);
// perform actions here
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve information from XML Google Maps

I am currently facing an issue with my code that retrieves data from Google Maps in XML format. The problem I'm encountering is that it only displays the last set of data. How can I resolve this issue? You can find my code on jsFiddle function getli ...

Comparing DOM Creation in PHP and JavaScript

My website currently does not have any ajax requests, and here is a simplified version of my code: class all_posts { public function index($id){ $statement = $db->prepare("SELECT * FROM mytable WHERE id = :id"); $statement->exe ...

What is the best way for me to show comments beneath all of my posts?

Currently, I am facing an issue with my application where I need to retrieve comments from posts. I am unsure of the best approach to tackle this problem. The existing system only displays posts that have comments, but it shows only a single comment inste ...

Why is it that in Angular, the child controller shares the same scope as the parent?

I have set up a testing environment on Plunker, here is the link to the full example: View the complete example on Plunker Below is the child controller code snippet that is functional: child.directive('child', function(){ return{ r ...

Activate inline javascript within LESS styling

I am interested in incorporating inline JavaScript into my less files, but I received the following notification: Inline JavaScript is not enabled. Have you configured it in your settings? What steps can I take to enable this feature? ...

Using Vuejs to display errors with alerts

Is there a way to display errors using alerts in bootstrap when working with vuejs? This is an example of the code: <div v-if="this.getError"> <div v-for="(_errors, key) in this.getError"> <p>{{key.repla ...

The property fails to reflect changes in state

I am currently developing an application that requires fetching data asynchronously and preserving the state in the parent component while also passing the data reference to children components. I encountered an issue where the props do not update when the ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

How to Retrieve a File Using Angular 2

Currently, I am trying to download a file in pdf format using Angular 2. For this purpose, I have incorporated FileSaver.js to facilitate the saving of the file as a pdf. (response) => { var mediaType = 'application/pdf'; let pdfConte ...

"NodeJS Express: The intricacies of managing overlapping routers

While constructing a NodeJS express API, I have encountered a peculiar bug. It seems that some of the endpoints are overlapping, causing them to become unreachable as the request never completes and ends up timing out. For example: const load_dirs = (dirs ...

Detecting the existence of a scrollbar within the document object model using JavaScript - a guide

Could someone provide a JavaScript syntax for detecting the presence of a scrollbar in the DOM by measuring the body height and window height? ...

Uncertain about the distinction between reducers and dispatchers when it comes to handling actions

I'm feeling a bit confused regarding reducers and dispatchers. While both receive actions as parameters, it doesn't necessarily mean that the actions I use in my dispatchers are the same as those used in my reducers, correct? For example, if I h ...

Having trouble with WebRTC video streaming on Firefox?

I have implemented one-way broadcasting in my Dot Net MVC website for video streaming using the example found at https://github.com/muaz-khan/WebRTC-Experiment/blob/master/webrtc-broadcasting/index.html. While it works perfectly in Google Chrome, unfortuna ...

The script remains static and does not alter the "href" or "div" content based on the current URL

I am having an issue with my NavMenu on my website. It is a table with images that link to product pages, and I want to change the links and names based on the language of the site. However, the script I wrote for this is not working properly. I have tried ...

Modifying HTML elements in real-time using AngularJS

Looking for a way to display all posts from the database using AngularJS? You're in luck! I'm currently implementing an 'edit-post' directive to provide users with the ability to edit each post they see. Here's a snippet of the lin ...

Discover the worth within the outcome obtained from the AJAX request

I have an action that returns a tuple containing a boolean value and a string. How can I retrieve the first boolean value from the result, which could be either true or false? This is the action: public Tuple<bool, string> Check This is the AJAX c ...

Retrieve data from Last.fm API by utilizing both Node.js and Angular framework

I am currently working on implementing the node-lastfmapi track.search method into my project. I have successfully retrieved the results, but I am facing challenges in integrating them into the front end using Angular. My backend is powered by mongoDB and ...

Passing a DOM element from Selenium to JQuery and retrieving the results in C#

I recently encountered some challenges with using JQuery to search for information and send it back to Selenium C# in my project. After some trial and error, I was able to figure it out and wanted to share my findings. Specifically, I focused on: How ca ...

Using Selenium in Python to close a modal window

After struggling for a while to close a modal, I attempted running a JS script. Surprisingly, it worked when executed in the browser console but failed with selenium. The script I used was: driver.execute_script("document.getElementById('btnChiudi&ap ...

How to eliminate the comma from the final element in a JavaScript Vue.js array?

I'm looking to remove the comma from the last element in Vue, but I'm unsure how to do so since the index of the last element is unknown. <td v-if="category.sub_category.length > 0"> <template v-for=&q ...