I'm using an ajax request to post a new message to a database. The page auto loads elements from the database onload. I want to delete the elements and re-add them when a user makes a post to add the current most post to the top of the list and its not working. I'm not sure why. There is no console error but it doesn't remove them.
onload ajax call
$.ajax({
url : "/getposts/",
type : "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success : function(json) {
document.getElementById('output').innerHTML = (json['message']);
for (var index = 0; index < json['user_posts'].length; index++) {
var div_make_badassness = document.createElement('div');
div_make_badassness.id = json['user_posts'][index][3];
document.getElementById('post_section').appendChild(div_make_badassness);
document.getElementById(json['user_posts'][index][3]).innerHTML = "<div id=" + json['user_posts'][index][3] + ">" + "Title:" + json['user_posts'][index][1] + "<br>" + json['user_posts'][index][0] + " Chomps: " + json['user_posts'][index][2] + "</div>" ;
}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
document.getElementById('output').innerHTML = "Request Failed.";
}
});
on submit ajax call
$.ajax({
url : "/makepost/",
type : "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: '{{ csrf_token }}',
username: username,
post_title: post_title,
post_text: post_text,
},
success : function(json) {
document.getElementById('output').innerHTML = (json['message']);
var post_section = document.getElementById("post_section");
for (var index = 0; index < post_section.length; index++) {
post_section.removeChild(post_section.childNodes[index]);
}
div tag
<div id ='post_section'>
</div>
for (var index = 0; index < json['user_posts'].length; index++) {
console.log(json['user_posts'][index][3] + json['user_posts'][index][1] + json['user_posts'][index][2]);
var div_make_badassness = document.createElement('div');
div_make_badassness.id = json['user_posts'][index][3];
document.getElementById('post_section').appendChild(div_make_badassness);
document.getElementById(json['user_posts'][index][3]).innerHTML = "<div id=" + json['user_posts'][index][3] + ">" + "Title:" + json['user_posts'][index][1] + "<br>" + json['user_posts'][index][0] + " Chomps: " + json['user_posts'][index][2] + "</div>" ;
}
Because you're using jQuery, I'll just do it in jQuery.
// Will remove any html in "post_section" and add in the new posts
function updatePostSection(user_posts) {
var post_section = $('#post_section');
post_section.html(''); // Remove all html contents inside
for(var i = 0; i < user_posts.length; i++) {
var div = $('<div>');
div.attr('id', user_posts[i][3]);
div.html("Title:" + user_posts[i][1]);
post_section.append(div);
}
}
In the success ajax function you can do something like...
// ...
success : function(json) {
updatePostSection(json['user_posts']);
},
// ...
Then you should be able to use it for both your getposts and makepost ajax calls assuming the json is the same structure.
Update: There are ways to optimize this so you're only writing to the dom once, but this is just an example.
Related
I POST my table data using ajax in database. Now I want to get back when I give click the open button.
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
debugger;
//var p = JSON.stringify('[' + data + ']');
// alert(p.GetPageInfoResult[0])
//var k = data.main[0];
//alert(data.length);
//var jsonObj = $.parseJSON('[' + data + ']');
//alert(JSON.parse(data));
var jsonPretty = JSON.stringify(JSON.parse(data), null, 2);
},
error: function () {
alert('Error');
When I give my file name I want to display my pageinfo. I get data like
[{"main":{"sub":[],"tittle":"oops","startvalue":"21","stopvalue":"45","status":"","accumalated":"","comment":""}}]
You have not cleared where you want place your resultant Json. Below is that Success result placed in div having table . It is just a sample you may change as per your requirement:
function OnSuccess(response) {
debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var page = xml.find("Table");
var row = "";
$('#popupdiv tbody').html('');
page.each(function () {
var page = $(this);
row = " " + page.find("tittle").text() + " " + page.find("startvalue").text() +
" " + page.find("stopvalue").text() + " " + page.find("status").text() +
" " + page.find("accumalated").text() + " " + page.find("comment").text() + "";
$('#popupdiv tbody').append(row);
});
}
function getResults(){
var text = encodeURIComponent(searchField.val().trim());
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&format=json&titles=" + text,
dataType: "jsonp",
success: function(data){
showResults(data, text);
}
});
}
function showResults(data, text) {
results.show();
var query = "https://en.wikipedia.org/wiki/" + text;
for (var id in data.query.pages) {
var code = "<a href=" + query + " class='results'>" + "<div class='results'>";
code = code + "<strong>" + id.title + "</strong>";
code = code + "<br>";
code = code + id.extract;
code = code + "</div></a>"
$(code).appendTo(results);
}
}
In the showResults function, its showing the id.title and id.extract as undefined. Why is that? What am I doing wrong?
When you do this:
for (var id in data.query.pages)
The, id variable is filled with a property name which is simply a string. If you want to get that value of that property, you have to reference the value of that property as in:
data.query.pages[id]
Or, if that's an object that you then want .title from, then you would need
data.query.pages[id].title
and
data.query.pages[id].extract
That's because when iterating over an object (using for-var-in-object loop), the var (id in this case) is the key, but if you need value, use object[key] syntax. Check the following code
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&format=json&titles=newton",
dataType: "jsonp",
success: function(data) {
for (var id in data.query.pages)
document.write(data.query.pages[id].title);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In your case, you are using just key=> '321123'. To get value of object use key. To get object data.query.pages[id].
for (var id in wiki = data.query.pages){
wiki[id].title;
wiki[id].extract;
}
This one should work.
function showResults(data, text) {
results.show();
var query = "https://en.wikipedia.org/wiki/" + text;
for (var id in wiki = data.query.pages) {
var code = "<a href=" + query + " class='results'>" + "<div class='results'>";
code = code + "<strong>" + wiki[id].title + "</strong>";
code = code + "<br>";
code = code + wiki[id].extract;
code = code + "</div></a>"
$(code).appendTo(results);
}
}
i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}
I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});
Consider the following JQuery loop. It appends this:
"<div id='1'>" + feedback + "</div>"
1st Question.
I want to increment the id of the appended div after the first one has been appended so that the first appended div's id is 1, the second div's id is 2 and so on.
2nd Question.
When the number of divs reaches 10, I want to delete the first appended div. Which in our case is:
<div id="1">php result</div>
This should keep looping and deleting older divs.
Here's the Jquery ajax loop:
new get_fb();
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "algorithm.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 8000);
}).responseText;
$('#BuzFeed').append("<div id='1'>" + feedback + "</div>");
}
For counting:
var get_fb = (function() {
var counter = 1;
return function(){
var feedback = $.ajax({
...
}).responseText;
$('#BuzFeed').append("<div id='" + counter + "'>" + feedback + "</div>");
}
})();
get_fb();
and for automatic removal, after
var $buzfeed = $('#BuzFeed').append("<div id='" + counter + "'>" + feedback + "</div>");
add
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.first().remove(); }
Additionally, your code uses some not-so-good practices. The re-write, including my additions would be:
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
dataType: "html", // based on chat
url: "algorithm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>");
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.first().remove(); }
setTimeout(get_fb, 8000);
}).fail(function(jqXhr, textStatus, errorThrown) {
var $buzfeedresults = $("<div id='BuzFeedError'></div>");
$buzfeedresults.text('Error: ' + textStatus);
if (typeof console !== 'undefined') {
console.error(jqXhr, textStatus, errorThrown);
}
});
};
})();
get_fb();