An uncaught SyntaxError occurred due to an omission of a closing parenthesis after the argument list in code that is otherwise

I have a Javascript code that sends an Ajax request and upon receiving the data, it creates an "a" tag with an onclick event that triggers another method along with a parameter. Below is the implementation:

function loadHistory() {
        var detailsForGet = {
        userId: sessionStorage.getItem("userName")
    }
    $.ajax({
        type: "GET",
        url: "https://localhost:44326/User/getTwitterSearchHistory",
        data: detailsForGet,
        success: function (data) {
            jQuery.each(data, function (index, item) {
                console.log(item)
                $('<a href="#" onclick="historySearch(' + item + ')">' + item + '</a><br/>').appendTo('#forHistory');
            });
        }
    });
}

function historySearch(text) {
    console.log(text)
    document.getElementById('tweetSearching').innerHTML = "Searching...";
    $.getJSON("https://localhost:44326/api/Twitter/GetSearchResults?searchString=" + text)
        .done(function (data) {
            if (data.length == 0) {
                document.getElementById('tweetSearching').innerHTML = "No matches Found!";
            }
            else {
                document.getElementById('tweetSearching').innerHTML = "Found " + data.length + " matches!";
                console.log(data)
                document.getElementById('searchResults').innerHTML = "";
                $('<h3 style="text-align:center; color: white">Search Results</h3> <hr/>').appendTo('#searchResults');
                $.each(data, function (key, item) {
                    $('<ul style="list-style:none;"><li><span style="font-weight: bold; color: white">Post </span><span style="color: white">' + item.FullText + '</span><br/><span style="font-weight: bold; color: white">Uploader</span><span style="color: white"> ' + item.CreatedBy.Name + " @" + item.CreatedBy.ScreenName + '</span><br/><span style="font-weight: bold; color: white">Date</span><span style="color: white"> ' + formatDateTwitter(item.CreatedAt) + '</span><li/><hr/></ul>').appendTo('#searchResults');
                });

            }
        });
}

When I attempt to click on the "a" tag, I encounter an error

Uncaught SyntaxError: missing ) after argument list

This issue only arises when calling a method with a parameter in the onclick function. Previously, I tried calling a function without a parameter, and it worked fine. However, passing a parameter results in this error.

Am I missing something important here?

Answer №1

If the value of your variable is a string, it's important to remember to wrap it in quotes when using onclick JavaScript. When working within an HTML string that already uses single quotes, you can include single quotes by encoding them as \x27.

$('<a href="#" onclick="historySearch(\x27' + item + '\x27)">' + item + '</a><br/>').appendTo('#forHistory');

For more information, check out: How to Escape Quotes in JavaScript

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

Cutting Out Sections of a List

I'm currently working on an app that involves looking up and navigating to specific locations. I've encountered an issue with the coordinates in my code containing a ',0' at the end, which is not compatible with Google Maps. Manually re ...

Refine your search by name following the implementation of a character-altering filter

Encountered a scenario in which there is a need to filter elements generated by the 'ng-repeat' directive. I have implemented a custom filter that replaces one character with another and vice versa for each element created. However, when attempt ...

Exploring the intricacies of debugging async/await in Node.js with the help of

Having trouble debugging an "await" instruction in my async function. Every time I try, a promise is returned instead of the expected value. I've noticed there's supposed to be an "Async" button where the red square is located in this picture but ...

"Want to learn how to dynamically disable an input field in AngularJS when another field is selected? Find out how to achieve this using the

Hey there, I'm dealing with two input fields. Input field A is a drop-down menu and input field B. They both have the same value (same ng-model). My goal is to clear the second input field whenever the user selects an option from the dropdown. Can any ...

Failure [ERR_STREAM_WRITE_AFTER_END]: writing past the endpoint [npm-request using socket.io]

My server has a socket server running, and on my laptop, I have a socket.io-client service. When both are turned on, they establish a connection. When other users request information from my server, the server sends that request to my laptop via a socket. ...

How can I sum up each array elements using a forEach loop in JavaScript?

Check out my code snippet: var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]]; var averageData = []; data.forEach(function(entries) { entries.reduce(function(a, b) { return a + b[1]; }, 0); console.log(entries); }); I want to sum ...

PHP suffered a breakdown of its encoding capabilities when utilized alongside Ajax and jQuery

Trying to understand the issue, I am attempting to send the string "Técnico" to PHP, but it appears as "Técnico" in the $_POST variable. This problem is specific to this particular project. I have three other projects running on Apache2 (in the same / ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...

The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues wh ...

What is the method for configuring input in a session without having to submit it?

I am encountering a major issue with my PHP MVC pattern website. On one page, I did not implement a "POST" submit method and now I am facing difficulties in passing quantity to the products/order page. If I use a Submit button, the next page does not funct ...

How to retrieve multiple values from a single select dropdown form field using React

In my React Material form, I have a select dropdown that displays options from an array of objects. Each option shows the name field, which is set as the value attribute (cpuParent.name). However, I also need to access the wattage field (cpuParent.wattage) ...

Is there a way to retrieve the parent window's domain in a child window (opened with window.open) when both windows are located on different

Can anyone offer assistance with cross-domain communication between windows? Looking to use window.open(); function. ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...

SQL query - establishing a connection between two database tables

I am currently working with two tables in my Access database. The first table is called Messages and it contains the following fields: MessageID MessageFrom MessageTO MessageSubject Messages The second table is named User and it consists of these fields ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...

Specify "Accept" headers using jQuery when fetching data within an iframe

I am working on a webpage where I am adding an iframe dynamically like this: $('<iframe id="testIframe" />').src('http://www.google.nl/').appendTo('body'); The accept headers being sent while loading the content in thi ...

What is the best way to implement media queries for mobile phones and desktop computers?

I've come across similar questions before but still can't wrap my head around it. Here's my dilemma: I want the index page of my website to display in desktop layout on desktops and mobile jquery on mobile devices. Currently, I have set up m ...

Error occurs consistently with AJAX, PHP, and SQL newsfeed

Striving for Progress Currently, I am engrossed in developing a newsfeed and enhancing my proficiency in utilizing Ajax through jQuery. My ultimate aim is to create a seamless user experience where individuals do not need to refresh the page to view the l ...

SelectBoxIt jquery plugin can be applied after the completion of populating options in the select element with AngularJS

Utilizing AngularJS, I am dynamically populating a select box with the code below: <select ng-model="department" ng-options="dept as dept.name for dept in departmentList" class="fancy"> <option value="">-- select an optio ...

Is it possible to save a JavaScript interval in a jQuery element's data property?

In the process of developing a jQuery plugin, specifically a jQuery UI widget known as Smooth Div Scroll, I encountered an issue where I needed to store references to intervals that were unique to each instance of the plugin on a page. If I simply declared ...