I would yo have a functionality similar to the StackExchange link on the top left of the Stack Overflow site.
As I understand it, after the stack exchange link is clicked, the following things happen:
the hidden div container is shown.
this div is populated with its html and the actual data using ajax (maybe jquery)
I've noticed that the html and data does not appear in the page markup, so I think it is probably fetched using javascript/jquery/ajax.
one note - I'm using asp.net mvc 2 and linq-to-sql.
Please give me examples on how this can be acheived, or maybe links to similar examples,
thanks.
You can achieve this with jQuery and page methods in the code behind.
//Gets the list of requests
function getRequestList() {
// call server-side webmethod using jQuery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Index.aspx/GetOrdersForApproving",
data: "{ }", // send an empty object for calls with no parameters
dataType: "json",
success: displayRequests,
failure: reportError
});
}
//displays the requests in the ul
function displayRequests(result) {
// ASP.NET encapsulates JSON responses in a property "d"
if (result.hasOwnProperty("d")) { result = result.d; }
// iterate through player list and add info to the markup
var ul = $("#requestsForApproval");
for (i = 0; i < result.length; i++) {
var li = $("<li class='approvalListItem'><div>"
+ "<h3>" + result[i].OrderID + " - " + result[i].Supplier + "</h3>"
+ "</div>"
+ "<div>"
+ result[i].Description
+ "</div>"
+ "<div> "
+ "<table width='100%'>"
+ "<tr>"
+ "<td>"
+ "Quant: " + result[i].Quantity
+ "</td>"
+ "<td>"
+ "Price: " + result[i].UnitPrice
+ "</td>"
+ "<td>"
+ "Total: " + result[i].Value
+ "</td>"
+ "</tr>"
+ "</table>"
+ "</div>"
+ " <div class='approvalButtons' style='display:none'>"
+ "<ul><li class='approveButton'>Approve</li>"
+ "<li class='rejectButton'>Reject</li></ul>"
+ "</div>"
+ "<input type='hidden' class='hiddenID' name='OrderLineID' value='" + result[i].OrderLineID + "'>"
+ "</li>");
ul.append(li);
}
Code Behind:
/// <summary>
/// Gets a list of Request Lines
/// </summary>
/// <returns>List of order lines</returns>
[WebMethod]
public static List<iOrderLine> GetOrdersForApproving()
{
try
{
List<iOrderLine> Lines = new List<iOrderLine>();
foreach (Objects.Database.OrderLine oOrderLine in Objects.Database.OrderLine.GetLinesWaitingFor(StaticStore.CurrentUser.UserID, int.MinValue))
{
Lines.Add(new iOrderLine(oOrderLine));
}
return Lines;
}
catch (Exception)
{
throw;
}
Related
I have a .php file where I am using both HTML and JavaScript to display items from my database. I have a JavaScript append function that is creating cards where each item is display. On my cards, I have a button that will expand the card to show product history. Some products have more history than others so the expansion needs to be dynamic. The historical data is being pulled from database and is initially in a php array. I originally was going to institute php into the javascript append function but I could not figure out how to set the JavaScript index variable 'I' to my php index. So I want to just stay with JavaScript. But I don't know how to write a loop in the middle of this append function that will loop through the historical array and populate the expansion. Below is what I am attempting. I took out a lot of the lines in the append function but you can see what I am trying to do.
function get_products() {
clear_cards();
$.each(productNumbers,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card" + i + "'>" +
"<div id='card_tab2" + i + "' class='tabcontent' data-tab='tab-name2'>" +
"<div class='details_tables'>" +
"<table>" +
"<tr>" +
"<th>Item Type</th>" +
"<th>Painted</th>" +
"<th>Last Sold" +
"<a id='_close_tab" + i + "' class='tablinks tab_override' onclick=\"openCity(event,'card_tab4" + i + "')\">" +
"<i class='large angle up icon'></i>" +
"</a>" +
"</th>" +
"</tr>" +
"<tr>" +
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength)
{
+ "<td>" + itemtypesplit[counter] + "</td>" +
+ "<td>" + itemdatesplit[counter] + "</td>" +
counter = counter + 1;
}
+
"</tr>" +
"</table>" +
"</div>" +
"</div>" +
Please help. I had it working with PHP inserted in, but I just couldn't figure out how to set it to a PHP variable.
Place this code into a function:
function getSomething(i) {
var html = '';
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength) {
html += "<td>" + itemtypesplit[counter] + "</td>";
html += "<td>" + itemdatesplit[counter] + "</td>";
counter = counter + 1;
}
return html;
}
And then use it in your HTML building block:
'<some html>' + getSomething(i) + '<some other html>'
I have a function which append some elements if a json file was loaded:
function loadNdraw(title, id){
$("#containerCharts").html("");
var date = $("#dateChart");
var jqJSON = $.getJSON("charts/" + id + "/" + date.val() + ".json");
jqJSON.done(
function(data){
$("#containerCharts").append(
"<div class='divStandard'>"
+ "<div class='titleChart'>"
+ "<div style='float: left;'>" + title + "</div>"
+ "<div style='float: right;'>" + data.lastUpdate +"</div>"
+ "<div style='clear: both;'></div>"
+ "</div>"
+ "<center><div id='" + id + "' class='bodyChart'></div></center>"
+ "</div>"
);
}
);
}
I call this function multiple times
loadNdraw("A", "a");
loadNdraw("B", "b");
loadNdraw("C", "c");
loadNdraw("D", "d");
My problem is that it does not load in this order.
Every time the page is loaded, the order of A,B,C,D is random.
How can I force it to be loaded in order?
I don't want to sort json.
You can use .promise() function in jquery
function loadNdraw(title, id){
var dfd = jQuery.Deferred();
$("#containerCharts").html("");
var date = $("#dateChart");
var jqJSON = $.getJSON("charts/" + id + "/" + date.val() + ".json");
jqJSON.done(
function(data){
$("#containerCharts").append(
"<div class='divStandard'>"
+ "<div class='titleChart'>"
+ "<div style='float: left;'>" + title + "</div>"
+ "<div style='float: right;'>" + data.lastUpdate +"</div>"
+ "<div style='clear: both;'></div>"
+ "</div>"
+ "<center><div id='" + id + "' class='bodyChart'></div></center>"
+ "</div>"
);
}
);
dfd.resolve(true);
}
Then you can simply call
$.when( loadNdraw("A", "a") ).then(
$.when( loadNdraw("B", "b") ).then(
//Some code
);
);
You can simply use .promise as per your need
The JSON scripts are being loaded asynchronously. The order in which the callbacks fire don't depend on the order in which you invoke loadNdraw, but the order in which jqJSON.done gets fired. The file that loads the fastest will cause its jqJSON.done method to be called first, and so on.
If you need these to be in order, you have a few options:
Sort the HTML structure after all results have loaded (or each time a file loads)
Load the charts sequentially, by calling loadNdraw inside of jqJSON.done, meaning that chart B would only start loading after A is done—this is likely to be much slower.
Populate the results in a temporary data structure, keep track of when all requests have completed, and then handle the DOM manipulation based on that data.
Option 3 seems to be your best bet in this situation:
function loadNdraw(title, id) {
$("#containerCharts").html("");
var date = $("#dateChart");
return $.getJSON("charts/" + id + "/" + date.val() + ".json");
}
var options = [
{ title: 'A', id: 'a' },
{ title: 'B', id: 'b' },
{ title: 'C', id: 'c' },
{ title: 'D', id: 'd' }
];
for (var option of options) {
option.promise = loadNdraw(option.title, option.id);
}
$.when(...options.map(o => o.promise)).done(function(...results) {
results.forEach(function(dataArray, idx) {
var title = options[idx].title;
var id = options[idx].id;
$("#containerCharts").append(
"<div class='divStandard'>"
+ "<div class='titleChart'>"
+ "<div style='float: left;'>" + title + "</div>"
+ "<div style='float: right;'>" + dataArray[0].lastUpdate +"</div>"
+ "<div style='clear: both;'></div>"
+ "</div>"
+ "<center><div id='" + id + "' class='bodyChart'></div></center>"
+ "</div>"
);
});
});
Note a couple of things here:
The argument to $.when is a listing of of Thenables—objects like your jqXHR with a then method. You can pass it an array objects by expanding it with the ...spread operator.
The callback for $.when takes a listing of response objects as its parameter, in the order in which the requests were made. They can be collected into an array using the ...rest parameter syntax.
I have an ajax post request for a form submit where i manipulate the page based on the values that are returned from the controller but my problem is that whenever the form is submitted i need to erase the values from the last request.For example, i submit the form and when that happens i add some text on the page if the form is submitted a second time i need to erase those values from the last time and add on the page new content.
Here is the code:
function ajaxPost(){
// DO POST
$.ajax({
type : "POST",
url : "/search",
dataType: "json",
data : {
'marcaId': $('#marcaId').val(),
'modelId': $('#modelId').val(),
'pretDeLa': $('#pretDeLa').val(),
'pretPanaLa': $('#pretPanaLa').val(),
'anFabrDeLa' : $('#anFabrDeLa').val(),
'anFabrPanaLa' : $('#anFabrPanaLa').val(),
'orasParam' : $('#orasParam').val()
},
success : function(data) {
console.log(data);
for(var i=0; i<data.length; i++){
$('.row.autovitElements').append("<div class='col-sm-3 elementAutovit'>" + "<div class='card' style='width:20rem;'>" +
"<img class='card-img-top' src=" + JSON.stringify(data[i].img) + "alt='Card image cap'>" +
"<div class='card-body text-center'>" +
"<p class='card-text text-center' style='color: black'>" +data[i].title+ "</p>" +
"<ul class='list-group list-group-flush'>" +
"<li class='list-group-item'>" +
"<div class='row'>" +
"<div class='col-md-6'>" +
"<i class='material-icons'></i><span>"+ data[i].price +"</span>" +
"</div>" +
"<div class='col-md-6'>" +
"<i class='material-icons'></i><span>"+data[i].city+"</span>" +
"</div>" +
"</div>" +
"</li>" +
"</ul>" +
"<button href=''#' class='btn btn-danger'>Save</button>" +
"</div>" +
"</div> " +
"</div> ");
}
})
I've tried with $('.row.autovitElements').hide(); but it won't work:(
for(var i=0; i<data.length; i++){
$('.row.autovitElements').append("<div class='col-sm-3 elementAutovit'>" + ...
The elements you are appending for the results of the ajax are elementAutovit, which are children of the .row.autovitElements element. So to "reset" the results, you would remove all those elements you appended, which could be done with:
$('.row.autovitElements .elementAutovit').remove()
Which would remove all those specific elements. OR, if there is nothing else in the container that you want to keep, you could simply empty it
$('.row.autovitElements').empty()
I used AJAX to dynamically create the HTML but I've encountered a problem
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'><a href='odobri_prijavu.php?id=" + m.marker_id + "'>Odobri</a>" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>Izbriši</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
</script>
I tried to use buttons first instead of anchor tags but I couldn't figure how to add event handlers to dynamically created buttons that will post a request via AJAX to some php script with the proper id as the value and the value of the textarea. So I used the anchor tag and I was able to send the id, but I can't send the value of the textarea because I don't know how to reference it and even if I referenced it, it will be NULL because its value is set to the anchor tag at the very beginning and I want to type in text in the textarea.
Instead of listening to individual "elements", you can actually listen to a parent of a specific element (You'll need to supply another parameter to on()). A popular pattern is to listen to "body" (because body is a parent to all, technically), but any non-dynamic parent element will work! Here's an example:
//notice the second parameter supplied
$("body").on("click", ".my-dynamic-element", function(e){
//awesome code that makes the world a better place goes here
//this code triggers when .my-dynamic-element is clicked, wootz
});
Event delegation is your friend.
I don`t see any actions that actually do event handling, but a simple solution would be something like:
$(document).on('click', '.your-button-class', function(){
// do your thing
});
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'>Odobri" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>Izbriši</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
function clickHandler(id){
$('#'+id) // selects the button
$('#t'+id) // selects the text area
}
</script>
I need to add a list of task after to click one row in a html table I'm using knockout js. the problem is that I'm just adding de last task from my data in a row and I need to add a new TR inside my element "$taskSelected" for each task. Here is my code
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
$.each(data, function(key, value) {
var html = "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
$taskSelected.innerHTML=html;
});
}).fail(function() {
alert("error");
});
};
}
the var $taskSelected contains another row "<tr> </tr>" basically Ii want to nested rows. Some advises please
Try this:
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
var html = "";
$.each(data, function(key, value) {
html += "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
});
$taskSelected.innerHTML=html;
}).fail(function() {
alert("error");
});
};
}
All I did was move var html outside of your each loop. This makes sure that all your previous HTML stays inside the variable, otherwise you are overwriting html each time you run through the loop (This is why you're only outputting the last one ;) ).