ian-campbell
ian-campbell

Reputation: 1665

Ajax json response not getting appended to the page

I want to append a json object to the page. I get it successfully via ajax, but it's not showing up.

<form onsubmit="return false;">
{% csrf_token %}
   Search:<input type="text" name="artist" id="artist" />
    <button class="updateButton" onclick="createlist()">submit</button>
</form>

function createlist(){
$.ajax({
    type: "POST",
    url: "/rest/",
    dataType: "json",
    data: {
        artist: $('#artist').val()
    },
    headers: {
        'X-CSRFTOKEN': "{{ csrf_token }}",
    },
    success: function(data){
        $('#output').html(data); //also tried data.content
    }
});
}

The response appears to be in one long escaped string when I view the response and preview in devtools.

"[{\"fields\": {\"artist\": \"Leonardo da Vinci\", \"link\": \"https://trove2.storage.googleapis.com/leonardo-da-vinci/galloping-rider-and-other-figures.jpg\", \"title\": \"Galloping Rider and other figures\"}, \"model\": \"serve.art\", \"pk\": 63057}

How can I wrangle this into something usable?

Upvotes: 0

Views: 95

Answers (3)

Suchit kumar
Suchit kumar

Reputation: 11859

you should try like this:

var output=""; 
	 var data="[{\"fields\": {\"artist\": \"Leonardo da Vinci\", \"link\": \"https://trove2.storage.googleapis.com/leonardo-da-vinci/galloping-rider-and-other-figures.jpg\", \"title\": \"Galloping Rider and other figures\"}, \"model\": \"serve.art\", \"pk\": 63057}]";
	data =  JSON.parse(data)
for(x in data){
	console.log(data[x]);
output=output+"Artist:"+data[x].fields.artist+"<br>"+"Link:"+data[x].fields.link+"<br>"+"Title:"+data[x].fields.title+"<br>"+"Model:"+data[x].model+"<br>"+"PK:"+data[x].pk+"<br>";
	
}
		 $('#output').html(output); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div  id="output"></div>

Upvotes: 1

Varun Chakervarti
Varun Chakervarti

Reputation: 1042

No you cannot append an object to a HTML element.

Don't parse the JSON, just append in the format(string) as you are getting.

I have tried and successfully appended to the HTML element but in the string format.

Upvotes: 1

Ryo
Ryo

Reputation: 2123

use

JSON.parse

and you'll get the data.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Upvotes: 1

Related Questions