I am currently using Ajax to update a feed of information. The Ajax should add to the current list of results rather than replace the existing results.
So far I have created the Ajax required to fetch the data from a database, but in the callback function I am using the following callback function
fetchPosts.onreadystatechange = function() {
if(fetchPosts.readyState === 4) {
$("#resultfeed").html(fetchPosts.responseText);
}
}
Obviously using $("#resultfeed").html(fetchPosts.responseText); in the callback function means that any prior results are overwritten on the page. How can I change this so that the results add to the current list of results?
Use append or prepend
$("#resultfeed").append(fetchPosts.responseText); // Adds at the end
$("#resultfeed").prepend(fetchPosts.responseText); // Adds at the top
Related
I have problem loading partial views in mvc. Im trying to load the view with jquery and it kind of works. It either displays two divs filled with the right information or four filled with the same. But it loops through the array so the in paramater changes and I get a warning.
The process or thread has changed since last step
I have a array in jquery that is filled with four values and I need the value in that list as a paramater in the ActionResult.
The code I have
public ActionResult TvShow(string channel)
{
var model = un.SortAllPrograms(channel);
return PartialView("TvShow", model);
}
and jquery
$(document).ready(function () {
var nameOfChannel = ["TV3", "TV4", "TV6", "TV8"];
debugger
$.each(nameOfChannel, function (index, value) {
$('.showContainer').append('<div class="number">' + value + '</div>');
$('.number').load('Home/TvShow', { channel: value });
});
});
I would really appreciate some help or advice on how to make this work.
The issue is, For each ajax call, you are loading the response of the ajx call to the div with class number. So the ajax call which gets the last response will be used to update all the div's with that css class. This is the reason you are seeing more than one divs with same response at time, but this will be also random because every time your server takes different time to respond for each calls. Sometimes, the call for TV6 will be the one which takes more time. Since ajax is asynchronous, when the response comes back, it updates all the available divs with class number at that point. It is possible that your loop is executing it's second iteration at that, so you have only 2 divs present with that css class, hence it will update only those 2 divs.
Ideally you want to load to the div which was created for the specific in the array you are looping.
This should do it.
$(function() {
var nameOfChannel = ["TV3", "TV4", "TV6", "TV8"];
$.each(nameOfChannel, function (index, value) {
var $d = $("<div class='number'>")
.load('#Url.Action("TvShow")',{ channel: value });
$('.showContainer').append($d);
});
});
Keep in mind that, your current approach is making n number of calls to server (where n is the size of the array). You might consider sending the array as the parameter and making a single call which can return the markup for all the items, resulting in one single call. Use the approach which makes more sense to your use case.
I'm using sailsjs to insert data from GET parameter of the URL (mydomain.com/prod_master/addsupp).
The page is /prod_master/addsupp which is accepting GET parameters to insert in database.
In javascript I need to do loop and insert more than one record
following is the javascript code i'm using:
<script>
for(var i=2;i<(rCount);i++)
{
supplier=tbl.rows[i].cells[3].children[0].value;
del_lead_time=tbl.rows[i].cells[4].children[0].value;
min_qty=tbl.rows[i].cells[5].children[0].value;
window.location="/prod_master/addsupp?supplier="+supplier+"&del_lead_time="+del_lead_time+"&min_qua="+min_qty;
}
</script>
However I can confirm that using my url mydomain.com/prod_master/addsupp?supplier=val&del_lead_time=val2&min_qua=val3 its adding records to database perfectly
but in loop if i use window.location=url then its not working.
Any solution?
Note: if is there any jQuery solution then also let me know.
In loop you can't use window.location=url to call any url and do some task. Because javascript execution will be faster than you think. Once it has replaced URL in window.location, in next loop it will replace same and it will conflict with previous call.
Better approach would be calling that URL using ajax call.
I'm giving you psudo code using jQuery to do GET request.
<script>
for(var i=2;i<(rCount);i++)
{
supplier=tbl.rows[i].cells[3].children[0].value;
del_lead_time=tbl.rows[i].cells[4].children[0].value;
min_qty=tbl.rows[i].cells[5].children[0].value;
urlToCall="/prod_master/addsupp?supplier="+supplier+"&del_lead_time="+del_lead_time+"&min_qua="+min_qty;
$.get(urlToCall, function(response){
console.log(response); //you might want to see returned response
});
}
</script>
I am using jQuery to get a list of suppliers for a part number.
I then want to load some extra data about the supplier/part number combination once the edit form appears. The problem is that the dataurl method (which I am calling in the beforeInitData method) to get the suppliers does not complete before the beforeShowForm method executes. Therefore I do not have a supplier to look up when the form first loads. Is there a way to run the function after the dataUrl method completes to get the extra data?
I have tried JQGrid editoptions dataurl not using ajax get? and got it going but I know there will be conflicts because the ajaxSelectOptions method gets called for every request and sometimes my requests will be coming from different places with different requirements.
Here is the code that I am using for my grid:
jQuery("#receiptPartsTable").jqGrid('editGridRow',"new",
{
height:400,
width:800,
reloadAfterSubmit:false,
recreateForm: true,
beforeInitData: function(form)
{
var selectedPart = rowData.part;
var selectedPartQty = rowData.qty;
//Getting list of suppliers
$("#receiptPartsTable").jqGrid('setColProp', 'supplier', { editoptions:{dataUrl:'getSuppliersForPart.php?part=' + rowData.part} });
},
beforeShowForm: function(form)
{
var selectedPart = rowData.part;
var selectedPartQty = rowData.qty;
$('#part').val(selectedPart);
$('#qty').val(selectedPartQty);
//$('#supplier').val() is not set yet;
var supplier = $('#supplier').val();
//This method is getting called before there is a supplier
getPartDetails(rowData.part, supplier);
//Set up onChange listener. After selecting a supplier, get the part details
$('#supplier').change(function() {
var supplier = $('#supplier').val();
getPartDetails(selectedPart, supplier);
});
}
You posted no definition of jqGrid which you use. The context in which you execute the above code is also not quite clear. Do you get rowData before from the currently selected row? Where you define it?
Nevertheless I think that you went in the correct direction and that you found already the correct way to solve the problem. The usage of complete callback of ajaxSelectOptions is probably the only way which you can use. You wrote about some "conflicts", but not posted more details.
I would recommend you to examine properties of this inside of complete callback. jqGrid set context option (see the line) of the $.ajax call (exactly like in the answer which you already found yourself). So you can use this.elem, this.options and this.vl inside of complete callback. this.vl is the value from the cell in case if editing of existing row. Typically it's the name of the option which will be selected. this.options has tree important properties which you can use: this.options.dataUrl, this.options.id, this.options.name. In case of form editing are the values this.options.id and this.options.name the same. In case of inline editing this.options.id will have rowid and _ ad the prefix. It gives you the possibility to execute different code inside of complete callback for different selects where you use dataUrl.
One more remark. In the most cases you can remove call of setColProp from the beforeInitData and use the approach suggested in the answer and the another one:
ajaxSelectOptions: {
data: {
id: function () {
return $("#receiptPartsTable").getGridParam('selrow');
},
part: function () {
return rowData.part;
}
},
complete: function (jqXHR, textStatus) {
var columName = this.options.name, response = jqXHR.responseText;
...
}
}
You can use just editoptions: {dataUrl: "getSuppliersForPart.php"} The URL will be appended with part and id parameters (see the above code). Instead of id you could use getRowData to get content from other columns based of rowid of currently selected row for example.
I'm trying to get my jQuery to work in this flow:
Parse json using $getJson
Loop through returned JSON and create divs for each JSON item
Once done, repeat but instead with another json file and append the results to the existing results.
But as of now I can't call another function AFTER the first loop is done, because the function gets called before the page is populated. How can I finish the populating loop, and then call another function?
I appreciate any help you can give me. Still learning as you can tell.
function test() {
var i;
for(i=0;i<=10;i++) {
$("div#test").append("<div id='"+i+"'></div>");
}
when_loop_is_done();
}
function when_loop_is_done() {
var i;
for(i=0;i<=10;i++) {
$("div#test div#"+i).append("<span>foo</span>");
}
}
Essentially I'm grabbing JSON from a separate page on my server, then looping through and populating the content using variables from that JSON object. The issue is no matter what I do, the second function always gets called before jQuery populates the content. So if I were to call an alert after the loop is done the page would pop up the alert and then load in all of the appended html.
Store your results in a variable or property. Then, use $(document).ready(fn) to wait for the page to finish loading and populate the page or finish your work when it has finished loading.
Your code should look something like this:
$.getJSON('/remote.json', function (response) {
// do the first loop using the response json
})
.done(function () {
// do the second json request and loop through the results
});
Any code you call inside the done() method's callback function will wait until the previous method in the chain is complete. You should definitely review the API documentation for $.getJSON: https://api.jquery.com/jquery.getjson/
I need to call two functions sequentially (means one by one) in javascript on onclick event.
The requirement is to get the data from the backend and then make the cell highlight.
Below code snippet is used for this:
cell1.onclick=function() {
getData("FileName");
setTimeout("setHighlight('FileName')", 500);
};
Currently i am using the setTimeout for calling the second method after a delay of 500ms.
The problem with above code is if getData method takes more than 500ms to get the data from backend then in that case cell would not get highlighted.
Is there any way to do this?
Thanks
Jyoti
To get data from the backend, you probably are using AJAX.
And in the callback function you are populating the data. After this step, call the highlight function.
You probably have something like this:
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
// do something with the response here
highlightData(); //<---- the function to highlight data
}
}
You should add another parameter to getData, which is a function to execute when you have the data. So,
function getData(filename, callback) {
// get the data
// when you have the data, do callback(filename);
}
then you can do
getData("FileName", setHighlight);