eqinna eqinna - 7 months ago 16
Javascript Question

pass paramenter to document ready function from another page

I have this code in a separate js-file to load content into a page without reloading the page:

$(document).ready(function(){

//Catch the form's submit event:
$('#skipreload').submit(function() {
//Create AJAX call:
$.ajax({
//Get form data:
data: $(this).serialize(),
//GET or POST method:
type: 'GET',
//The file to call:
url: 'webaddress.php',
//On success update div with response:
success: function(response) {
$('#form_output').html(response);
}
});
return false;
});
});


I call the function in a page like this:

<html>
<body>
<head>
<script src="js/script.js">
<!-- Want to create variable to pass parameter to document ready function here -->
</script>
</head>
<body>
(...)


Now I want to pass the 'webaddress.php'-url as a parameter from the HTML-page to the script.js-file and its submit function, but I cannot make this work. Does someone know how this can be done?

Answer

As @Satpal already mentioned, you could create a global variable inside of your HTML which will be accessible in the external script

<html>
<body>
<head>
<script>var myUrl = 'webaddress.php';</script>
<script src="js/script.js"></script>
</head>
<body>
(...)

In script.js:

url: myUrl,

Be careful: In that case you must not forget to provide this value in each HTML file that uses script.js, otherwise you will get "undefined" for myUrl.

Comments