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!!!
});
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);
});
}
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.
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 trying to make a dynamic form wherein a single item has a file, text and select html input types and number of items can be dynamic. The problem is when doing AJAX using jquery, the Form wont serialize for the file input type. Please suggest any technique to do it. My code is below:
<form id="Form1" enctype="multipart/form-data">
<div id="divMain"></div>
<div>
<button id="Upload" type="button" value="Upload"><span>Upload</span></button>
<input id="Add" type="button" value="Add" />
</div>
</form>
<div id="status"></div>
<script type="text/javascript">
var counter = 0;
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
</script>
Change Your To script It Will Definately Work. :-)
<script type="text/javascript">
var counter = 0;
$(document).ready(function () {
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
});
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
});
</script>
Second Option
http://www.uploadify.com/documentation/uploadify/multi/
Prefer This It will Uploaded Multifiles on one time with great UI. :-)
I have the following javascript.
Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null?
I checked the javascript and the variable "cnt" is 1 not 2.
Why would that be?
Malcolm
[code]
$("#Save").click(function () {
var title = $("#recipetitle").val();
var category = $("#category").val();
var preptime = $("#prepTime").val();
var preptimeperiod = $("#lstPrepTime").val();
var cooktime = $("#cookTime").val();
var cooktimeperiod = $("#lstCookTime").val();
var rating = $("#rating").val();
var method = $("#method").val();
var jsontext = '{ "RecipeTitle": "' + title + '",';
jsontext += '"CategoryID":' + category + ',';
jsontext += '"PrepTime":' + preptime + ',';
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",';
jsontext += '"CookTime":' + cooktime + ',';
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",';
jsontext += '"Rating":' + rating + ',';
jsontext += '"Method":"' + method + '",';
var ing = "";
var cnt = 0;
$("#ingredients tr.ingredientdata").each(function () {
if ($("td.ingredient", this).text() != "") {
ing += '{ "IngredientName": "' + $("td.ingredient", this).text() + '",';
ing += '"Units": ' + $("td.units", this).text() + ',';
ing += '"Measure": "' + $("td.measure", this).text() + '"} ,';
}
cnt = cnt + 1;
});
alert(cnt);
if (ing != "") {
jsontext += '"Ingredients": [';
ing = ing.substring(0, jsontext.length - 1);
jsontext = jsontext + ing;
jsontext += ']';
}
jsontext += '}';
var json = eval('(' + jsontext + ')');
//var json = { Field: 1 };
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
I would recommend a refactoring of your javascript as it would help you identify the errors more easily. Also checkout with FireBug the actual JSON request being sent to the controller:
$("#Save").click(function () {
var ingredients = $('#ingredients tr.ingredientdata').map(function(index, element) {
return {
ingredientName: $('td.ingredient', element).text(),
units: $('td.units', element).text(),
measure: $('td.measure', element).text()
};
});
var json = {
RecipeTitle: $('#recipetitle').val(),
CategoryID: $('#category').val(),
PrepTime: $('#prepTime').val(),
PrepTimePeriod: $('#lstPrepTime').val(),
CookTime: $('#cookTime').val(),
CookTimePeriod: $('#lstCookTime').val(),
Rating: $('#rating').val(),
Method: $('#method').val(),
Ingredients: ingredients
};
$.ajax({
url: '/Recipe/Save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function () {
//alert("DONE!!");
}
});
});