How to display the content of a JSON array? - javascript

My Django app sends through AJAX POST/GET communications arrays representing parts of my DB. As you can see on the picture, this is a typical array with all the objects. The objects represent a messages to integrate in a chat box. Just to clarify, the amount of objects might vary, so I need a loop function or smthg to display all the objects within the response array .
Therefore, I need to display these arrays, combining HTML and JS.
This is my exact AJAX Json response
HTML:
<div id="display"></div>
JS:
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/checkview",
success: function(response){
console.log(response);
$("#display").empty();
for (var models_to_return in response.message)
{
var temp="<div class='container darker'><b>"+response.messages[models_to_returney].user_id+"</b><p>"+response.messages[models_to_return].room+"</p><span class='time-left'>"+response.messages[models_to_return].datetime+"</span></div>";
$("#display").append(temp);
}
},
error: function(response){
//alert('An error occured')
}
});
},1000);
})
</script>
But nothing is displaying.

you can do like this
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/checkview",
success: function(response){
console.log(response);
$("#display").empty();
for (var model in response.models_to_return)
{
var temp="<div class='container darker'><b>"+model.user_id+"</b><p>"+model.room+"</p><span class='time-left'>"+model.datetime+"</span></div>";
$("#display").append(temp);
}
},
error: function(response){
//alert('An error occured')
}
});
},1000);
})

Related

using javascript onload() and ajax to retrieve php array

I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.

How to connect to the Parse Javascript API? (502 error)

I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});

How to redirect response from ajax request

I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});

Looping through the URL in an AJAX call in jquery

So I recently asked a question concerning looping through data in a json file from an asynchronous AJAX call in jquery that uses callback functions (Looping through AJAX and callbacks in jquery) and I got a lot of good help, but now I wonder if I were to have 3 different json files (same structure and naming convention, but holding slightly different data) and their URLs in an array called myURL, would there be a way to loop through the AJAX call for all three URLs and output each of their respective results on a webpage? Below is my code:
<html>
<head>
<title>Weather Data for Emergency Models</title>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
<script Language="JavaScript">
//New Array for my URLs
var myURL = ["ticker1.json","ticker2.json","ticker3.json"];
function hmm(callback) {
$.ajax({
url : myURL[j], //<<<---Want to loop through this array
dataType: 'json',
success: function(response){
callback(response);
}
});
}
hmm(function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
document.write('<br>');
});
});
</script>
</body>
</html>
$.each(myURL,function(i,url){
hmm(url,function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
document.write('<br>');
});
});
});
And in your function -
function hmm(url,callback) {
$.ajax({
url : url,
dataType: 'json',
success: function(response){
callback(response);
}
});
}
Try this
for(var k=0,len=myURL.length; k<len; k++)
$.ajax({
url : myURL[k++], //<<<---Want to loop through this array
dataType: 'json',
success: function(response){
callback(response);
}
});
}

Return a set from ajax to JavaScript

I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.

Categories