carstorm carstorm - 3 months ago 8
Javascript Question

How to send parameter via js to a ajax js file

My HTML has this in it:

<script src="../scripts/jquery-1.8.1.min.js"></script>
<script src="../scripts/displayTable.js"></script>


The displayTable.js consists of this:

$.ajax({
url: "https://carcraft.atsbusinessandgames.com/xmls/carcraft_1-10-2Test.xml",
type: "Get",
dataType: 'xml',
success: function (result) {
$(result).find('Module').each(function() {
var name = $(this).attr("name");
var url = $(this).find('url').text();
var authors = $(this).find('authors').text();
var version = $(this).find('version').text();
var date = $(this).find('date').text();
var description = $(this).find('description').text();
$("#ModsList").append("<tr>" + "<td>" + "<a href=" + url + ">" + name + "</a>" + "</td>" + "<td>" + authors + "</td>" + "<td>" + version + "</td>" + "<td>" + date + "</td>" + "<td>" + description + "</td>" + "</tr>");
});
},
failure: function() {
alert("Notify the site owner that the xml file is unreadable.");
}
});


How would I make it so that I can pass the url as an argument rather than hard-coding it into the js file, this way I can use the same file across many pages on my site?

Answer

Define a function in displayTable.js, then call it after you load the script.

So diaplayTable.js would contain:

function displayTable(url) {
    $.ajax({
        url: url,
        type: "Get",
        dataType: 'xml',
        success: function (result) {
            $(result).find('Module').each(function() {
                 var name = $(this).attr("name");
                var url = $(this).find('url').text();
                var authors = $(this).find('authors').text();
                var version = $(this).find('version').text();
                var date = $(this).find('date').text();
                var description = $(this).find('description').text();
                $("#ModsList").append("<tr>" + "<td>" + "<a href=" + url + ">" + name + "</a>" + "</td>" + "<td>" + authors + "</td>" + "<td>" + version + "</td>" + "<td>" + date + "</td>" + "<td>" + description + "</td>" + "</tr>");
            });
        },
        failure: function() {
            alert("Notify the site owner that the xml file is unreadable.");
        }
    });
}

Then you use it as:

<script src="../scripts/jquery-1.8.1.min.js"></script>
<script src="../scripts/displayTable.js"></script>
<script>
$(document).ready(function() {
    displayTable("https://carcraft.atsbusinessandgames.com/xmls/carcraft_1-10-2Test.xml");
});
</script>