Jquery isnt loading Partial View like it should - javascript

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.

Related

AJAX calling Django view function not only once but for previous attempts as well

I have a code that should delete a list item.
// Triggers when the item "element_to_click" is double clicked and calls the
// function named show_hide_function()
$( element_to_click ).one('dblclick', function(e) {
show_hide_function(input_mt_key, update_form_mt, input_mt, button_text,
csrfmiddlewaretoken)});
// Creates a button to delete the selected item, then calls delete_function()
function show_hide_function(input_key, form, input, button_text, csrf_token){
const del_btn = document.createElement("button")
del_btn.name="my_del_btn"
form.appendChild(del_btn);
const button_text_del = document.createTextNode("X")
del_btn.appendChild(button_text_del)
del_btn.setAttribute("class", "update_delete_buttons")
// On click on del_btn, calls the function named delete_function()
$( del_btn ).on('click', function(e) {
delete_function(input_key,csrf_token)});
};
// Sends a form to backend (django) and on success, calls another function
// named jsonToDict() which I believe, is not part of the problem. So I don't
// include it here.
function delete_function(input_key, csrf_token){
$(document).on('submit' , function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/posted/delete/',
data:{
item_id:input_key.value,
projectURL: projectURL_,
csrfmiddlewaretoken:csrf_token,
},
success: function (data){
jsonToDict(data, "update_delete_form")
};
});
});
};
And simplified version of my django view function looks like this:
def deleteDictionary(request):
print("called")
if request.method == 'POST':
var2 = request.POST['item_id']
projectURL = request.POST['projectURL']
value_holder = Task.objects.filter(taskID=var2).values_list('taskIdentifier')
.
.
.
.
.
response_data = json.dumps(jsonString)
return HttpResponse(response_data, content_type='application/json')
else:
pass
This is how my items look
This is how they look on double click:
When I delete first item, I get no error. When I do the same thing for the second item (without refreshing the page), it also gets deleted, but I get the following error on frontend:
I go back to server side and check whats going on, I see that on click onto delete button of second item, the view function is called twice (function prints "called" twice.) and naturally, it creates problem for the rest of the code which I didn't include here, since I think that is not the problem (the input provided by form should be added into a list, and then that list is being worked. Since function is called twice, it creates an empty list and function gives an error).
Moreover, when I refresh the page and delete 3 items, it creates that error twice (first call works fine, second and third creates error, meaning, django view function is called 2 times and 3 times respectively)
I think you get the idea.
So somehow, AJAX calls my django view function n times where n is the item number I attempt to delete, even tho I click on different items' delete button...
In the past, I didn't have these event listeners and functions. I had my AJAX form without being in a function and it worked perfectly. Now that I want it to work for each item separately, it gives this error.
What I tried so far:
I checked if the delete_function() function is called twice when I click on second item's delete button. The answer is NO. Everything you see in JS code above is called only once. But somehow AJAX remembers the previous attempts and calls the django view function for those attempts too.
I'd like to underline that the view function works fine. If I tried to delete 5 items, all 5 items are deleted regardless of the function creating an error or not. But since function is called multiple times unnecessarily, it slows my code dramatically.
Short version of my question is, how can I avoid AJAX to submit the form for previous attempts.

$("Div").load() appending html page after completion of $(document).ready() when written inside $(document).ready()

Sorry if this type of question is already been answered.
I am trying to add a page using $("Div").load() inside $(document).ready().
Page is getting loaded but it is not showing anything inside its' variables.
Steps in my code:
Page starts loading
Value come from back-end code (spring java)
Loading a specific page when values are present and show them on page.
If values are null, do not load page.
Jquery version: "2.1.3"
Below is my code:
$(document).ready(
if(condition1){
var var1= data //some json data;
$('#divId').load('url/mypage.jsp');
if(condtition == true){
myFunctionToProcessData(var1);
}
}
)
I have tried ajax call, but its not working.
After completion, I can see my page is loaded and appended in division but not showing on UI and have empty variables.
Please help.
Thank you for your responses. I could not reveal my full code, so made a snippet to give an idea about what i wanted. Issue is fixed now.
Issue was: I wanted to append a JSP on certain condition inside $(document).ready() but the working of $(document).ready() is something like, it ensures executions of methods and conditions written inside it.
Problem was:
Method "myFunctionToProcessData" and "$('#divId').load('url/mypage.jsp');" was called simultaneously , and HTML was not complete at the same time when method called and due to this, my method did not find division to set values and do other validations.
To solve this I have used below approach:
Appended html/jsp page using .load function.
used an ajax method in which i am getting data.
execution steps:
1. Code appended HTML in some time (Using setTimeout function)
2. after execution of all lines in $(document).ready(), ajax function called
3. Now myFunctionToProcessData ca find divisions to set values and proper out put shown on the UI.
code:
$(document).ready(
if(condition1){
var var1= data //some json data;
setTimeout(function() {
$('#divId').load('url/mypage.jsp');
}, 10);
if(condtition == true){
$.ajax({
type : "GET",
contentType : "application/json",
data : "&sid=" + Math.random(),
url : "url", // change to full path of file on server
success : function (data) {
myFunctionToProcessData(var1);
});
}
}
)
This is just a workaround to make sure that myFunctionToProcessData executes only after jsp appended succesfully in it.
now myFunctionToProcessData is executing at the end.

Filtering items with jQuery (AJAX) - requests finish in wrong order

I am working on a project for school and it's about jQuery, PHP, symfony and all that web stuff :). It is actually my first time using jQuery and even though I have already learned something, there are still many thing I dont know how to solve.
In this project, one of the things I am supposed to make is basically filtering some results. I have a database and when the site is loaded, all items from the database are displayed in a table. Then above the table, there is a text field. When I type in it, the items in the table are filtered as I type. But sometimes, when I write for example "HP", the jQuery first finishes the request for "HP" and displays the result and then it finished the request for "H" and so it overwrites the result of "HP" and this shouldnt happen. If I make the requests synchronous, it prevents me from writing in the text field when a request is being processed. How can I make it so that the requests are completed in the order they were called?
The jQuery code of this part of the project looks like this:
var oldTerm;
function filter() {
var term = $('#term').val();
//alert(term);
if(term != oldTerm) {
$.ajax({
url: url.replace('--', term).replace(/\/$/, '')
//musi bejt synchronni
}).done(function(data) {
$('#items_table tbody').html(data);
alert(term);
// udalost se musi registrovat po nacteni radku!
$('.edit_button').click(createForm);
});
oldTerm = term;
}
}
$(document).ready(function() {
oldTerm = null;
$('#term').keyup(filter);
});
I think your best shoot is to make a queue for the ajax call maybe use a lock too. You can also use this : Queue AJAX calls

Javascript call function once loop finishes and jQuery populates content

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/

Problem with removing child

I have two drop down forms. When the first is "changed" the second is populated with some data via ajax.
It's work but the value of the second drop down is not cleared on every request (I'm using $('#second_drop_down').children().remove();)
Here is sample code
$('#first_drop_down').live('change', function() {
var x = "some ajax data recived via ajax";
$('#second_drop_down').children().remove();
$('#second_drop_down').append(f);
});
Here you have a code that works, but it is practically like yours (you have a mistake in your example, 2 differente variables "x" and "f"):
http://www.jsfiddle.net/dactivo/8jfHG/
var timeChanged=1;
$("#first_drop_down").change(function()
{
$("#second_drop_down").children().remove();
$("#second_drop_down").append("<option value=\"volvo\">Volvo"+
timeChanged+
"</option><option value=\"saab\">Saab"+ timeChanged+
"</option><option value=\"mercedes\">Mercedes"+ timeChanged+"</option>");
timeChanged++;
});
Probably the code you received by ajax is malformed (I suppose).
Do you make a synchronous Ajax call? If not, you must put the code that changes the second drop down in the callback function, otherwise you will work on data that was not yet received. Assuming you use jQuery:
$.get( 'http://www.example.com', {first:$('#first_drop_down').val()},
function(data) {
$('#second_drop_down').children().remove();
$('#second_drop_down').append(data);
});

Categories

Resources