Ajax always within .html in the script tag?

0

I have been studying ajax, in different videos from youtube and in different pages, now my question is always the script in which ajax is going to be in the .html I always see it there, and for example I tried to pass it to another side like a .js file but it does not load anything to me only when I leave it inside the label of the .html (code js and ajax) it works to me. Is this good practice? That's wrong ? why?

here is the code that is at the end of my body at the html point.   

and here is the code that is inside simulate.js

As a result, it directs me to a php page. but if I leave it inside the html if it gives me the same data in the same html.

    
asked by juancamilovallejos0 28.02.2018 в 17:50
source

2 answers

1

I'll tell you:

  

AJAX is the technology for making asynchronous requests; must be   inside a script tag always at the end of the HTML content but   before you close the body tag.

They are put in the location that I mention because they help not to encourage the display of the page because the HTML code loads fast without problems and the heavy load of JS stays at the end so as not to ruin the user experience.

If you try to have it available for all your pages, you need to create it as an external file that for example is called functions.js and invoke it as follows:

<script src="js/funciones.js"></script>

If, for example, you use jquery for AJAX, the file structure should remain this way

 <script src="js/jquery.min.js"></script>
 <script src="js/funciones.js"></script>

The above so that the functions that we occupy of jquery are available for our code that we do.

It is the normal and general practice to order it as I mentioned, the last clarification is also within the script tags you can directly enter your javascript functions but in that way it will only work for the web page where you declare it; the best would be as I mentioned above

Greetings

    
answered by 28.02.2018 / 18:07
source
2

Separating the JS from HTML is usually a good idea, unless it is a trivial code.

You do not give any example of your code to make sure what your error is, but in principle, and assuming that your JS code is in a file ajax.js in the same folder as the HTML, what you need is to load it from your HTML with a line:

<script src="ajax.js"></script>

This line is traditionally placed in the header, although for reasons of load optimization it is often recommended to put it at the end of your body , just before line </body> .

And as you have been told, if you are loading other JS libraries (like jQuery), make sure you do it in the correct order. Yours probably should be the last one.

    
answered by 28.02.2018 в 18:09