简体   繁体   中英

call JavaScript function in $(document).ready(function() {})

I want to run a ajax function in page load and onChange , below is my code:

function ajax_get_subject(ID)
{
    alert('function called');
    $.ajax(
    {
        type: 'POST',
        url: 'ajax_get_subject.php', 
        data: {CourseID: ID},
        dataType: 'json',
        success: function(data)
        {
            if(data['error'] == null)
            {
                //do something
            }
            else
            {
                //do something
            }
        },
        error: function(ts)
        {
            alert("AJAX Error: \n" + ts.responseText);
        }
    });
}

Below is ready() function where I call the ajax_get_subject function:

$(document).ready(function()
{
    //populate at 1st when page load
    $(function()
    {
        var ID = <?php echo $CourseID?>;
        ajax_get_subject(ID);
    });
});

The function ajax_get_subject is not triggered. But if I call the function in $('element').change(), it works. Is there any wrong with my code?

I think you're trying to use PHP code inside JS files that are not executed by PHP. You have to move declaration somewhere to HTML file.

Suggested solution

I often define PHP values at the top of the file in order to use them in JavaScript, for example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            window.phpValues = window.phpValues || {};
            window.phpValues.courseId = '<?php echo $CourseId ?>';
        </script>
        <script type="text/javascript" src="path/to/your/script.js">
    </head>
    ....
</html>

...then in your script.js you can use it as:

$(window).ready(function() {
    alert(phpValues.courseId); // alerts value of $CourseID
});

I have a syntax error, which at line var ID = <?php echo $CourseID?>; , thank you @Felix Kling for mention it in the comment.
The value of $CourseID is a string but without double quotes, I just simply change the code to var ID = "<?php echo $CourseID?>"; and it works.
And also thanks for mention on problem of nested document.ready()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM