Fetching javascript array content after postback - javascript

I have an array that is dynamically filled from some server-side C#. When the page loads that C# builds the content for a JQuery function. If the user changes a control, the page triggers a postback and that c# refills the content of my array with the correct data. However, even though it changes the data according to Firebug, I only see the data from the original array contents.
for example: The page initially loads this
<script>
function pageLoad() {
var ary= new Array('original-1','original-2', 'original-3', 'original-4');
}
</script>
On post back, it loads this (when I inspect it with firebug this is what is loaded on postback)
<script>
function pageLoad() {
var ary= new Array('updated-1','updated-2', 'updated-3', 'updated-4');
}
</script>
Even though the new content is loaded, I still get the original data not the updated data.
My question is: How can I use the data that is given on postback?
I feel like there is an easy fix, I just can not wrap my brain around it.

Declare your var ary=array() OUTSIDE the function so it has global visibility.
<script>
var ary= new Array('');
function pageLoad() {
ary= new Array('original-1','original-2', 'original-3', 'original-4');
}
</script>

Related

Attempting to change pages without full reloading in django and javascript

I have tried to do something with Django and javascript. So for example, if I want to go to my "about" page from my "home" page, I only want to load the contents of the page. There are many similar elements in both pages (such as a header image and navbar) that does not need to be reloaded. I have already 80% achieved what I want, my code is below:
javascript
function loadcontent(url, classname) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// below changes the url to the new page
window.history.pushState(url, url, url);
var htmlres = document.createElement("div");
// get the html from the ajax response and then change the required parts.
htmlres.innerHTML = this.response;
document.querySelector(classname).innerHTML = htmlres.querySelector(
classname
).innerHTML;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
window.addEventListener("popstate", function(e) {
window.location.reload();
});
example link for about page
<a onclick = "loadcontent('{%url 'about_page'%}', '.content')" id = 'About'>About</a>
Django views.py about page
def about_page(request):
if request.is_ajax():
return HttpResponse('mainsite/about_page.html')
return render(request, 'mainsite/about_page.html')
First, of all I would appreciate feedback if this is actually a good idea or not. I have just started learning web programming and this is a mini-project of sorts.
Secondly, my issue is with pressing the back button on my browser. With the current code, I cause it to reload the url because if I press the back button and go back to my "Home" page without reloading, the webpage still displays the same thing on my "About" page.
Having to reload is not ideal since I went through the trouble of creating a way to only load certain parts of my webpage. Is there any way to store what has changed, so that when I "popstate()", it will revert the changes? One possible way is to call my loadcontent() function when popstate happens. However as shown in my function, I need to pass it the url to go to, and class name of the "div" that I want to swap. Is there a way to store the previous URL and which classname was changed?
Thirdly, as shown in my load content function, I don't really know what the "state" parameter sent to history.pushState() is for... I understand that it is a key-value dictionary-like object, however, when is it stored and when will I need to access it? Is it useful for my case where I just need to reload content without any user-selected items?
The only thing I can think of now is to do something like to use {wasloaded: True} as my state parameter, so that when I do "popstate()", it is able to identify if the current page was loaded through my loadcontent() or not, and handle it as required. (I guess this is because if someone came to my page from a totally different website, I would need to reload their page instead of trying to do loadcontent().)
Thank you for taking the time to read this!
Your approach is not good for this.
you have to follow following steps to achieve this;
the DOM which you want to update on JS event should have a unique ID or class.
make your ajax call which should return JSON response not HttpResponse and JSONResponse should have HTML field, rendered HTML of you template. You can use get_template and render methods for this.
On success, you have to update the HTML of the page by selecting the unique DOM container.

Re-execute js on back without reloading the whole page

Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}

jQuery - How to call a function after stored input values are reloaded?

Got this field:
<input id="foo" />
And I'm calling this function right after page load:
function alert_value() {
input_value = $("#foo").val();
alert (input_value);
}
In some cases the values entered by the user are stored and displayed on page refresh by the browser, which is, in my case, a valueable feature.
Problem is, there's a gap between page load and the moment the stored input values are loaded. Since I'm calling the function during this gap, it misses the input field value.
I get the right result when doing
setTimeout(alert_value, 1000);
But I'd rather call the function immediately after the values are reloaded.
How to catch the moment of stored input fields values load?
From what I understood from your question, you want to call the function as soon as the page has reloaded completely. I think this should work correctly.
$(window).bind("load", function() {
input_value = $("#foo").val();
alert (input_value);
});
I hope this is what you're looking for.
jQuery needs to know what object you want the data from. The object has an ID, which is "foo". In your jQuery you need to address that ID.
So basically change #id for #foo:
$(function(){
/* Load this content after the page is loaded */
function alert_value() {
input_value = $( '#foo' ).val();
alert (input_value);
}
})

Auto refresh JS with appendchild command that grabs data from an external file

I am creating a chat system and I am using html/php/jquery.
How can I append a child with data from an external file to a div using javascript auto refresh feature?
The code that I have:
<script>
var auto_refresh = setInterval(
function()
{
$('#messages_box').load('refresh_messages.php');
}, 1000);
</script>
The code above refreshes the whole DIV with data grabbed from the mentioned document.
<script>
var auto_refresh = setInterval(
function()
{
var textnode=document.createTextNode("Water");
document.getElementById("messages_box").appendChild(textnode);
}, 1000);
</script>
And the code above, appends the text to the div I want.
I want to "combine" this two and obtain the following result:
Auto-refresh an external php file every second and if there are new results (messages in my case) the messages_box DIV should be updated with the results using the appendchils JS method.
I want to create a chat messaging system that will grab messages if a new result is encountered when loading the external php fild. I want to use the appendchild method, because by doing this I will practically add a new child to the div, not refresh the whole div. I absolutely need to append stuff, not to load the whole DIV again.
It seems to me that what you are looking for is an AJAX request.
Here's how I would set this up:
Have a database set up to store messages
Have a PHP file with various functions to both retrieve and send messages to/from the database.
Have another PHP/HTML file with javascript that creates an AJAX request to the other PHP file on a regular basis.
There is tons of documentation on how to create ajax requests with pure javascript, but I personally prefer to used the jQuery .ajax() function.

Executing JQuery after page load only after clicking a specific link

I have a link in my app that when clicked, leads to another page. I want to execute some JQuery on this new page after it loads, but only if that specific link is clicked to get to the page.
I have this JQuery:
$('#new_to_topics').click(function(){
$(document).ready(function() {
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
});
});
where #new_to_topics is the id of the link that leads to the new page and
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
is the JQuery code I want to execute on that new page. However, this does not work. How should I do this?
You could pass a location hash to the new page, and then conditionally run some javascript based on that hash.
If my link was to mynewpage.html#fromXlink (this would show in the address bar)
My javascript on mynewpage.html could be:
$(document).ready(function() {
if (location.hash == '#fromXlink') {
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
}
});
You could add a variable to the query string i.e. somepage.aspx?fromthislink=true
and then pick that up in jquery.
This shows how
If it cam from that link then fire off your jquery.
You can use window.name to pass data to the target page (although I would prefer passing data in the hash, if possible).

Categories