0

I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.

<script>
    $( document ).ready(function(){

    Date.prototype.yyyymmdd = function() {

        var yyyy = this.getFullYear().toString();
        var mm = (this.getMonth()+1).toString();
        var dd  = this.getDate().toString();

        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
    };

    function requestContent()   {

        var date = new Date();
        $.ajax({
            type:'POST',
            url:'php/app/adminTimeline.php',
            data:{
                date: date.yyyymmdd()
            },
            success: function(data) {
                if (data == '') {

                    alert("No data found!");
                } else {
                    //  $("#loading_spinner").css({"display":"none"});
                    $('#timeline-content').prepend(data);
                }
            },
            error: function(data)   {
               // $("#loading_spinner").css({"display":"none"});
                alert("Something went Wrong!");
            }
        });

    }

window.onload = requestContent();
});
</script>

The document.onready method and window.onload the method seems not to be working too. Ps: I have the Jquery library linked in the header too.

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
  • If you want it to run immediately, use an IIFE (immediately invoked functional expression). Look that up to learn more about them – Araymer Jul 10 '17 at 17:17
  • 1
    I doubt the line window.onload = requestContent(); is doing what you expect as you are assigning the value returned by that method (which will be undefined in this case) instead of assigning the method itself. – Nathan Montez Jul 10 '17 at 17:31
  • My assumption is that this code is being executed some time later in the page timeline, after onload has occurred. Refreshing makes it work because then it runs before. Is this a SPA or Hybrid SPA? – Kevin B Jul 10 '17 at 18:34

2 Answers2

0

The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.

However where you create the date object, uses this, which executes after the document is fully loaded

$(document).ready(function(){
    //Code
});

This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (@sagid) pointed out, window.onload cannot be a returning value but must be a function.

i.e.

window.onload=function(){
    //Code
};

This means, your solution is to change window.onload=requestContent(); to

$(document).ready(function(){
    requestContent();
});

Good luck!

Ben
  • 2,200
  • 20
  • 30
  • window.onload is when the entire document loads, in most browsers, but not always after DOM is ready. document.ready is when the DOM is ready, but elements like images may not be loaded. https://stackoverflow.com/questions/588040/window-onload-vs-document-onload – Ben Jul 10 '17 at 18:39
  • Regardless of browser behavior, in his code, since he used different events, the date object may not be created before it is used in a function, which I believe is why the error occurred. By using the same event for both, we ensure they are executed sequentially, hopefully fixing his problem. – Ben Jul 10 '17 at 18:49
  • I agree that using the same event for both is the correct course. Just with the wording of the answer, *"The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded."* is incorrect, or at best misleading. the window cant be done loading if the entire document hasn't loaded. I suspect that if the OP used the window.load event handler only, the same problem would persist. – Kevin B Jul 10 '17 at 18:51
  • 1
    What is more likely is the OP is loading in this javascript via ajax or a script tag some time later. jQuery's document ready handler will always run regardless of whether or not the dom is already ready, however the window load event only runs once. – Kevin B Jul 10 '17 at 18:52
0

Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

https://learn.jquery.com/using-jquery-core/document-ready/


Also you're calling requestContent()

window.onload must be function, not returning value.

$(document).ready(function(){
  // here you ajax
}

https://jsfiddle.net/cqfq5on5/1/

Sagid
  • 383
  • 2
  • 13