3

I am using Javascript to send an Ajax request and with the returned data, I am creating an "a" tag with an onclick event that calls another method, with a parameter. This is the code 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');
                });

            }
        });
}

Now, when I try to press an "a" tag, I get the error

Uncaught SyntaxError: missing ) after argument list

Now, I noticed that it only happens when I call a method with a parameter in the onclick function because, earlier I tried to call a function with no parameter and it goes inside of it. However, when I tried to pass a parameter, it returns that error..

Am I not seeing something here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

If your item is a string, you need to enclose the value in quotes within your onclick JavaScript. Since you are already using single quotes to build your HTML string, you can add single quotes encoded as \x27.

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

See also: Escape quotes in JavaScript

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42