using a JSON object as a parameter in a JavaScript function

I am trying to pass specific elements from a JSON object as arguments in a JavaScript function. Here is the script I am using:

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp1=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function()
{
    if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
    {
        var txttmp2 = xmlhttp1.responseText;
        var obj2 = $.parseJSON(txttmp2);
        var text1= document.getElementById("tabs-Mil");
        var objln=obj2.post.mypost.length;
        //alert(objln+"");
        for(var counter=0;counter<objln;counter++)
        {
            text1.innerHTML+=" '"+obj2.post.mypost[counter].status+"' @ <a href='#'>"+obj2.post.mypost[counter].namalokasi+"</a>&nbsp;on "+obj2.post.mypost[counter].tanggal+"<br/><a href='#' onclick='addcomment("+obj2.post.mypost[counter].idpost+","+localStorage.loggeduser+")'>comment</a><hr width='80%' align='left'><br/>";
            text1.innerHTML+="<span id='comments' name='comments'></span>";
        }
    }
 }
xmlhttp1.open("GET","http://localhost:280/finaltask/forjson.php?tmpid="+iduser+"&proses=showpost",true);
xmlhttp1.send();

function addcomment(idcheckin,iduser)
{
    $("#formcomment").show();
    var detpost=document.getElementById("detail-post");
    alert(idcheckin+"/"+iduser);
}

I have successfully passed the JSON object element using the line onclick='addcomment("+obj2.post.mypost[counter].idpost+","+localStorage.loggeduser+")'

However, when the function addcomment(idcheckin,iduser) is executed, it shows that 'idcheckin' is 'undefined'...

Can someone provide assistance with this issue?

Answer №1

Avoid attaching complex event handlers by concatenating strings. It is recommended to utilize a library such as jQuery for this purpose:

$("<button></button>").text("Click Me").click(function () {
    updateData(obj.userProfile.myProfile[counter].id, ...);
})

Answer №2

Make sure that your return values meet expectations. Verify the validity of idpost, and consider implementing logging at the beginning of the loop.

    for(var count=0;count<objln;count++)
    {
        console.log('loop results ' + count + ': ' + JSON.stringify(obj2.post.mypost[count])); // double check output of selected element
        alert('idpost: ' + obj2.post.mypost[count].idpost); // Verify result
        text1.innerHTML+=" '"+obj2.post.mypost[count].status+"' @ <a href='#'>"+obj2.post.mypost[count].namalokasi+"</a>&nbsp;on "+obj2.post.mypost[count].tanggal+"<br/><a href='#' onclick='addcomment("+obj2.post.mypost[count].idpost+","+localStorage.loggeduser+")'>comment</a><hr width='80%' align='left'><br/>";

Additionally, consider changing:

addcomment("+obj2.post.mypost[count].idpost+","+localStorage.loggeduser+")

to:

addcomment(\""+obj2.post.mypost[count].idpost+"\",\""+localStorage.loggeduser+"\")

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

Sending JSON data containing special characters from AngularJS to Ruby server

I am currently working on creating a search form that utilizes Ruby for the back end and Angular for the front end. The search query is constructed in Angular in JSON format and then sent to Ruby through a RESTangular service. Everything was functioning c ...

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

What is the best way to customize the styles of Material UI V5 Date Pickers?

Attempting to customize Mui X-Date-Pickers V5 through theme creation. This particular component is based on multiple layers. Interested in modifying the borderColor property, but it's currently set on the fieldset element, so need to navigate from Mu ...

Restricting the input range with JQuery

Need assistance with limiting user input in a text box for amounts exceeding a specified limit. Attempted using Ajax without success, considering jQuery as an alternative solution. Any expertise on this matter? function maxIssue(max, input, iid) { v ...

Using Reactjs to automatically populate text into a React-Select Input field

I have implemented react-select in my project. Sometimes, I encounter the need to update my react-select input field without directly interacting with it (such as injecting text into it). However, I am unable to find a proper way to achieve this based on ...

Using AJAX to call a PHP function within a PHP script

I have successfully implemented an AJAX file that can execute content from a PHP file. However, my concern is how to specifically call a particular function within the PHP file if there are multiple functions present. Below is my current AJAX code: $(doc ...

Vuex getters not displaying expected values in computed properties until entire page has finished loading

When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded. For instance, I have an example of an isRegister ...

Building a dynamic map with React components using an array

Using the passed ID, a new element is dynamically generated: const Icon: FC<IconPropsI> = ({iconId, ...rest}) => { const iconsMap: IconsMapT = { IconUser: IconUser, IconTime: IconTime, IconVideo: IconVideo } return createElement ...

Can you explain the functionality of this Angular JS code snippet?

How is it possible that the following code snippet works in Angular JS? var app = angular.module('store',[]); (function(){ app.controller('StoreController',function(){ this.blabla = student; }); })(); var student = ...

A method to verify the presence of a specific element within a list using JavaScript

I'm trying to validate if the list retrieved from the application contains the expected element. Can you please review my code and let me know where I might be making a mistake? this.verifyOptionsInDropdown = async function(){ var optionList = a ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

Do AJAX requests make Cross-site scripting attacks more significant?

Currently, I am in the process of developing a React application that utilizes a PHP (Codeigniter) backend. Despite Codeigniter not handling this issue automatically, I have taken it upon myself to delve into the matter. While I comprehend the importance ...

Failed to convert value to a string

I'm dealing with a frustrating issue and I just can't seem to figure it out. The error message I'm getting is Cast to string failed for value "{}" at path "post". { "confirmation": "fail", "message": { "message": "Cast to string fai ...

What is the best method for converting nested arrays into a table format?

I am attempting to present my data in a tabular format with headers labeled key1 and key2. Below is the code I have written: render() { console.log((this.state.message)); const datamapping = Object.entries(this.state.message); cons ...

Using data attributes in Material UI: A comprehensive guide

Recently, I started integrating Material Design React into my project. However, I encountered an issue where the data-someField does not pass the value to the dataset map. For example: <Input data-role=‘someValue’ onChange={this.onChange} /> o ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

What are the steps for converting a structured text document into a SQL table?

I am currently working on a project that involves the need to save and load a structured text document, similar to MS Word, into/from a MySQL table. For instance, if given a sample document like sample.doc, the goal is to save both the content and formatt ...

Pass a JSON object to PHP when AJAX call is successful

Within my Controller, there exists an array named $data. Here is the output of its var dump: array 'urls' => array 0 => array 'link_id' => string '1' (length=1) 'link_name ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...