1

I have two javascript file one with the functions and another with the eventlistener. This is how I declare them

<body>
    <script src="../script/Main%20Functions.js"></script>
    <script src="../script/Main-events.js"></script>
</body>

Main Functions.js

checklike(userId,postId);
function checkLike(userId, postId) {
    $.ajax({

        type: "POST",
        url: "../Main.asmx/get_liked",
        data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var result = response.d;
            console.log('ok');
            $.each(result, function (index, data) {
                var liked = data.liked;
                if (liked == true) {
                    $("#" + postId).prev().parent("button").css("background", "#ccc");
                }
                else {
                    $("#" + postId).prev().parent("button").css("background", "white");
                }
            });

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Function Error "checkLike"');
        }

    });
}

Main-events.js

const d = document.querySelector.bind(document);
const D = document.querySelectorAll.bind(document);
const logOut = d('.lOut h3');
const iFrame = d('#if1');
const alias = d('.codename-label h2');
const monito = d('.monito-label');
const monitoChecklists = D('.monito-checklist');
const displayPicture = d('#displayPic');
const btnReveal = d('.btn-reveal');
const btnSubmit = d('.btn-submit');
const btnLike = D('.buttonLike');
console.log('ok2');
btnLike.forEach(function (like) {
    like.addEventListener('click', function (e) {
        console.log(this);
    })
});

but when I open the html the console.log('ok2'); executes first not the console.log('ok') . Is there a way on telling the javascript to load specific file first before executing the file for eventlistener?

EDIT 1: The adding of eventlistener for the btnLike loads first before the javascript added the elemet on the page.

EDIT 2: Okay upon investigation

Before trying eventlistener I use this jquery code

$(document).on('click', '.buttonLike', function () {
    var color = $(this).css("background-color");
    var id = $(this).find(".postID").attr("id");
    if (color == "rgb(204, 204, 204)") {
        $(this).css("background-color", "white");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) - 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Remove_Like(id);
    }
    else {
        $(this).css("background-color", "#ccc");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) + 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Add_Like(id);
    }
});

it works fine and I found out that it uses the document and check if the target has class name .buttonLike am i right?

6
  • What is in your Main-events.js file? Only console.log('ok2'); ? Commented Dec 5, 2017 at 7:14
  • The two script files are loaded in the correct order, but the Ajax call is happening asynchronously. The first console statement is executed when the Ajax call has finished Commented Dec 5, 2017 at 7:14
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Dec 5, 2017 at 7:15
  • @PatrickHund I will post the real dilemma i'm facing Commented Dec 5, 2017 at 7:15
  • @PatrickHund please see the edited version. Commented Dec 5, 2017 at 7:18

2 Answers 2

1

ajax is Asynchronous Javascript and XML.

So, being asynchronous, the console.log are not being called in order. And as ajax might be taking a while to get called, the 'ok2' is getting called first.

The solution to this is to call the 'ok2' inside the success or done method of $.ajax

Sign up to request clarification or add additional context in comments.

7 Comments

please re-read the edited version. So if I follow this logic, I need to add the eventlistener on the success?
why are you calling checklike(userId,postId); at the begining and not in the addEventListener method
@VianOjedaGarcia Try calling the checklike() method inside the addEventListener method. Seems more logical
Is that really the right way? because when the page load first. It gets the post (facebook like) and check how many likes this post have. Then create the element.
I got your problem now. What you should do is, is to create the element inside the success method and then add the event listener to it. That'd solve it.
|
1

If you want to load another js file in your ajax call than you can use this

jQuery's $.getScript() is buggy sometimes, so I use my own implementation of it like:

jQuery.loadScript = function (url, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'script',
        success: callback,
        async: true
    });
}

and use it like:

if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
    //Stuff to do after someScript has loaded
});

or simply

You can listen to the script's load event, and do things with the results as you would. So:

var script = document.createElement('script');
script.onload = function () {
    //do stuff with the script
};
script.src = something;

document.head.appendChild(script); //or something of the likes

Another option

will fire when a script is finished loading.

You will not be able to do something like:

<script src="/foo.js"></script>
<script src="/bar.js"></script>
<script>
function alertonload(src){
   console.log(src+' is loaded');
}
scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
    scripts[i].onload = function(){ alertonload(scripts[i].src); };
}
</script>

This is pure conjecture and speculation; I have not tried it and there's probably better ways to write it, but this will not do what you're looking to do. EDIT: The scripts are loaded as the browser sees them, not after the fact. They will be loaded before this occurs.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.