Last anchor tag not getting added properly with jQuery append method

I have the following code where I am trying to add anchor tag in the HTML as show below :

$.ajax({
    url: 'http://localhost:8080/MyAPI/getLinks',
    type: 'GET',
    dataType: 'json',
    success: function(data) {

        var jsonObj = JSON.parse(JSON.stringify(data));

        $.each(jsonObj.linksList, function(key, value) {

            $(".dropdown-content").append('<a href=' + value.webLink + '>' + value.linkText + '</a>');

        });
    },
    error: function(request, error) {
        console.log("Inside Error Function ; Request: " + JSON.stringify(request));
    }
});

<div class="dropdown">
    <button class="dropbtn">Links</button>
    <div class="dropdown-content"></div>
</div>

And here’s the JSON that I am using :

{
	"webservice_status": {
		"status": "SUCCESS",
		"message": ""
	},
	"linksList": [{
		"linkText": "Example 1",
		"toolTip": "Example 1",
		"webLink": "http:/example1.com/home",
		"orderList": 30
	}, {
		"linkText": "Example 2",
		"toolTip": "Example 2",
		"webLink": "https://example2.com",
		"orderList": 40
	}, {
		"linkText": "Example 3",
		"toolTip": "Example 3",
		"webLink": "https://example3.com",
		"orderList": 50
	}, {
		"linkText": "Example 4",
		"toolTip": "Example 4",
		"webLink": "https://example4.com",
		"orderList": 52
	}]
}

Everything is getting added properly, except the last one as shown below :

<div class="dropdown">
    <button class="dropbtn">Quick Links</button>
    <div class="dropdown-content">
       
        <a href="http:/example1.com/home">Example 1</a>
        <a href="https://www.example2.com">Example 2</a>
        <a href="https://www.example3.com">Example 3</a>
        <a href="https://example4.com"></a>
        "Example 4"
    </div>
</div>

I am wondering why the Example 4 is getting added after </a> tag and not before it just like others?

I don’t know why it isn’t working, for you. I have copied some of what you provided, made minor changes to reflect my environment (minus the AJaX call), and previewed in FireFox.

<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<title>Untitled Document</title>
	</head>

	<body>
		<div class="dropdown">
			<button class="dropbtn">Quick Links</button>
			<div class="dropdown-content">

			</div>
		</div>	
<script src="jquery-3.2.1.min.js"></script>
<script>
	const thisJSON = {
	"webservice_status": {
		"status": "SUCCESS",
		"message": ""
	},
	"linksList": [{
		"linkText": "Example 1",
		"toolTip": "Example 1",
		"webLink": "http://example1.com/home",
		"orderList": 30
	}, {
		"linkText": "Example 2",
		"toolTip": "Example 2",
		"webLink": "https://example2.com",
		"orderList": 40
	}, {
		"linkText": "Example 3",
		"toolTip": "Example 3",
		"webLink": "https://example3.com",
		"orderList": 50
	}, {
		"linkText": "Example 4",
		"toolTip": "Example 4",
		"webLink": "https://example4.com",
		"orderList": 52
	}]
};
const jsonObj = JSON.parse(JSON.stringify(thisJSON));
        $.each(jsonObj.linksList, function(key, value) {

            $(".dropdown-content").append('<a href=' + value.webLink + '>' + value.linkText + '</a>');

        });
</script>
	</body>
</html>

The above works per your expectations. So, I wonder if the AJaX call might be interfering, somehow. My code does this:


<button class="dropbtn">Quick Links</button>
<div class="dropdown-content">

<a href="http://example1.com/home">Example 1</a><a href="https://example2.com">Example 2</a><a href="https://example3.com">Example 3</a><a href="https://example4.com">Example 4</a></div>
		

V/r,

^ _ ^

Thank you !

even i did a quick test here in JSFiddle and it worked fine

Not sure what’s going on with the code.

Have you tried alerting or inserting the data into a div to make sure that your JSON is formatted as expected?

V/r,

^ _ ^

I didn’t quite understand. Could you elaborate more on this? Thanks

Sure. :slight_smile:

Before this line of code: var jsonObj = JSON.parse(JSON.stringify(data));

Do something like: alert(JSON.stringify(data));

OR: $('.dropdown-content').text(JSON.stringify(data));

To view the returning JSON and make sure that everything is formatted as it should be.

HTH,

^ _ ^

I did this and saw the whole JSON response in the alert window.

Was it all there, properly formatted, with no extras?

V/r,

^ _ ^

Yes. It looks good , properly formatted. I actually copied the alert window content and pasted it on jsonlint.com to check the validity and it appeared to be a valid json.

However, one thing I noticed that when I removed the last entry from the database. The last entry which was the second last entry before deletion didn’t behave abnormally and everything was fine. I added the last entry again and it fell off of the list again which is weird.

What’s with orderList values being factors of 10 except for the last that has a value of 52?

Hmm, not sure. The database guy put it in that manner. I can ask him to change it and then test. Do you think that changing it to maybe 60 might be a good idea?

I don’t know, but to me it suggests that “52” is meant to be a submenu of “50”.

I’m guessing there is (or should be) code other than the “append” bit that works with those values to put together nesting.

I figured out the problem. And I was able to replicate it in this JSFiddle here :

As you can see, this link "webLink" : "https://example4.com/", has an extra forward slash in the end. I removed it and changed it to "webLink" : "https://example4.com", and it started working fine.

I forgot to add that extra slash before and hence I wasn’t able to replicate the problem in JSFiddle.

Do you know why this extra slash was causing this problem?

Thanks

1 Like

Not a clue, sadly. It’s not like the slash is escaping the end quotation mark. That’s a real head-scratcher.

V/r,

^ _ ^

Not really, once you’re pointed to it.

The generated text starts with <a href=http://example4.com/>, which jQuery interprets as a self-closed element (XML syntax => <a href="http://example4.com"/>).

A good example why you should ALWAYS put attribute values in quotes.

1 Like

So, in this scenario, the JSON response would look odd, right? I mean it would change like this for webLink :

{
    "linkText" : "Example 4",
    "toolTip" : "Example 4",
    "webLink" : ""https://example4.com/"",
    "orderList" : 52
  }

Not like that, no. That is not valid syntax. I suppose you could try escaping the inner quotation marks. But IMHO that would be hacky and the better approach would be to fix the code that puts the value into the HTML

I see. So i guess, this part of code needs to be modified from the JSFiddle http://jsfiddle.net/ynvq7t93/4/ :


 $(".dropdown-content").append('<a href=' + value.webLink + '>' + value.linkText + '</a><br/>');

So, modifying the above line of code just for webLink and introducing double quotes, do you think it would be a good idea? Please correct me if I misunderstood something here. Thanks !

Try this:

$(".dropdown-content").append('<a href="' + value.webLink + '">' + value.linkText + '</a><br/>');

V/r,

^ _ ^

Yes. The single quotes in the JavaScript are enclosing strings so they can be concatenated with the variable values. They do not become part of the HTML.

Depending on how much of it there is, it can get messy looking fast, but I think if you insert double quotes into those single quote enclosed strings it would be fine. eg.

.. 'attribute="' + variable + '" ' ..