How to pass an object as function's parameter without getting Unexpected identifier error?

passing object as argument in c++
c++ passing objects by reference
objects as function arguments pass by value pass by reference in c++
passing object as argument in java
object as function argument in c++ tutorialspoint
pass by reference c++
passing class pointer to function c++
friend function in c++

I tried to passed the object as parameter in function getReqDetail but it returned Uncaught SyntaxError: Unexpected identifier. But when i passed a simple value(integer,boolean,string) as parameter such as data[i].id, it worked. So how do i passed the object as parameter

the data/object is from ajax function jquery

function agetAllRequests(){
    $.ajax({
        type: 'GET',
        url: `http://localhost:8080/api/requests`,
        headers: {
            "Content-Type": "application/json", "Accept": "application/json"
        },
        dataType:"json",
        success: function (data) {
            console.log("yes. data: " + data);
            if (data) {
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        if(data[i]) {                            
                            console.log(data[i]);  
                            txt += `
                                    <tr class="hov" onclick="getReqDetails(${data[i]})">
                                           <td>${data[i].id}</td> 
                                           <td>${data[i].status}</td> 
                                           <td>${data[i].user.email}</td> 
                                           <td>${data[i].message}</td> 
                                           <td>${new Date(data[i].createdAt).toLocaleString()}</td>
                                    </tr>`;
                        }
                    }
                    if(txt){
                        $("#requestList").html(txt);
                    }
                }
            }
        },
        error: function (error) {
            console.log('errorCode: ' + error.status + ' . Message: ' + error.responseText);
        }
    });
}
function getReqDetails(data){
    console.log(data);
    return data;
}

EDIT : note: function getReqDetails is outside of ajax function

the error

The reason for the error is that `onclick="getReqDetails(${data[i]})` will resolve to a string. Because data[i] is not a string it is converted to one, ie. "[object Object]". This makes the onclick attribute look like this:

onclick="getReqDetails([object Object])"

But that code is not valid JavaScript, hence the error.

In order to pass the object to the function, you should really not use the onclick attribute, which must have a string value. Instead bind a click handler, as follows:

    success: function (data) {
        console.log("yes. data: " + data);
        if (!data || !data.length) return;
        $("#requestList").empty(); // Clear whatever content there was before
        for (var i = 0; i < len; i++) {
            var item = data[i]; // Use a local variable to avoid repetition
            if(!item) continue;                            
            console.log(item);
            // Use jQuery methods to add the content and bind a click handler
            $("#requestList").append(
                $("<tr>").addClass("hov").append(
                    $("<td>").text(item.id),
                    $("<td>").text(item.status),
                    $("<td>").text(item.user.email),
                    $("<td>").text(item.message.id),
                    $("<td>").text(new Date(item.createdAt).toLocaleString())
                ).click(getReqDetails.bind(null, item)); // <-- click handler for TR
            );
        }
    },

How to pass and return object from a function in C++?, An object can be passed to a function just like we pass structure to a function. Here in class A we have a function disp() in which we are passing the object of class  How to pass objects to functions in C++ Program? Pass by Value. This creates a shallow local copy of the object in the function scope. Things you modify here won't be reflected in the object Pass by Reference. Pass by const Reference.

Template literals allows population of variables ( ${myVar} ) at runtime but the result will be always a string so the evaluation of your template will result in getReqDetails([object Object]).

What you can do is render a serializable value from your object or store a reference to the index then process it in the called function getReqDetails().

Try to pass a simple value to your string function:

var data = [{id: 1},{id: 2}, {id: 3},];
if (data) {
    var len = data.length;
    var txt = ``;
       if (len > 0) {
         for (var i = 0; i < len; i++) {
            if(data[i]) {                           
            txt += `
            <tr class="hov" onclick="getReqDetails(${data[i].id})">
                  <td>...<td>
            </tr>`;}
}
if(txt){
           $("#requestList").html(txt);
}
}
function getReqDetails(reqId){
     console.log(reqId)
     return reqId;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="requestList" />

Pass and return Object from a function in C++, Inside the function, the integer value of the argument object is added to that on which the 'add' function is called. In this method, we can pass objects as an  Passing an Object as argument . To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable ‘a’ and a function ‘add’ which takes an object as argument. The function is called by one object and takes another as an argument.

Passing and Returning Objects in C++, There are four ways of passing objects to functions. Let's assume you have a class X and want to pass it to a function fun, then − Pass by value  I want to use an object as function argument. When I define an object outside fucntion and then pass it as an argument, it works fine: var obj = { a: 0 } function foo(obj){ console.log(this.obj.a); } foo() //0 But when I pass an object directly, it doesen't work:

How to pass objects to functions in C++?, You can pass by value, by reference or by pointer. Your example is passing by value. Reference. void show(abc& S) { cout<<S.display(); }. Moreover, any changes made to the copy of the object inside the function are not reflected in the actual object. On the other hand, in pass by reference, only a reference to that object (not the entire object) is passed to the function. Thus, the changes made to the object within the function are also reflected in the actual object.

How to pass object to function in c++?, JS Function Objects. • Functions are first-class objects. • Functions are copied by reference. • Passing a  When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that’s sort of a hybrid between pass-by-value and pass-by-reference.

JavaScript Function Objects, I have a Matlab variable of object type, i.e. an instance of a class but I can't properly pass the variable to a function because the function  Pass object to a function An object can be passed to a function just like we pass structure to a function. Here in class A we have a function disp () in which we are passing the object of class A. Similarly we can pass the object of another class to a function of different class.

Comments
  • Attach the listener properly with addEventListener instead of using an inline attribute (which is as bad as eval)
  • Please spend some time to properly indent your code. The braces are floating everywhere except where they should be in nicely formatted code. You have two more opening than closing braces, which makes your function part of the success callback function, despite what you are telling us in the "EDIT" ;-)
  • After your recent edit, you still have one more opening brace than closing, and your indentation is not right at all. Please use proper indentation. It is the first thing a programmer would need to get right as it will solve many issues even before they surface. Hint: already on the second line of your code the indentation goes wrong, and again on the 5th, 8th, ...etc.
  • @trincot sure, sorry, still green here
  • I see you are really struggling to get the indentation right. Make sure that after every opening brace, the next line is indented more, and that each closing brace is indented less than the code above it. The body of the for loop is still not OK as regards indentation.
  • sir, is there another way than getReqDetails.bind(null, item)? @trincot
  • just curious because i m still new to JavaScript, sir @trincot
  • Yes, like .click((function (item) { return function() { getReqDetails(item)}; })(item)), or you could define item in block scope and use an arrow function: let item = ...; .... .click(_ => getReqDetails(item)), ...etc, but bind is really the simplest for your current code.
  • thanks, when i passed a simple value it worked, but when i tried to pass the object as param, it returned the same error "unexpected unique identifier"
  • this is due to the fact your are converting your object to a string, if you do not define a single value, when concatenating string through "+" you are forcing to a string conversion, obtaining "getReqDetails([object Object])". You could use JSX instead of string if you want to retain refereces to methods and objects efficiently