-2

I've a problem with disposition of function declaration using a mix of javascript and php language.

<script>
  //some JS code
  <?php getVideos() ?>
  //some JS code
</script>

<?php function getVideos()
      {
       //some code
      }
?>

The problem is that the function is declared in another part of the html code, and the page won't work until i don't move it before the JS code. There is a solution without need to move the php code?

EDIT: i wanna precise that my html file is with a php extension (index.php) and i can access to php variables along the entire document normally

  • there's no reason why your PHP function can not be placed before data output, so if you run into errors, fix those errors instead of searching for a problem that's not there – Garytje Jul 29 '13 at 13:46
  • there be a reason because from PHP i call a JS function, and if i place the PHP code before, the JS function hasn't been already declared, and i've the same problem – user2590550 Jul 29 '13 at 13:48
  • @user2590550 Your js function is not called by PHP, it's called at client side. What is happening is that your js function is being called before its loaded in the html document. – hdvianna Jul 29 '13 at 14:21
  • I wanna precise that my html document is a php file.. I normmaly use variables declared in php along the entire body of the document.. For exemple, i can retrieve normally a $myVar from javascript.. Why i can't do the same thing with functions? – user2590550 Jul 29 '13 at 15:42

3 Answers3

2

You have to call function using ajax call. Post to your php file using jQuery.post and in server use die to return data. PHP run at server-side

Example: In javascript:

<script>
    $(document).ready(function()
        {
            $.post(this.uri,{},function(){});
        });
</script>

In php:

<?php 
if (isset($_POST))
{
    getVideos();
    die("1");

}
function getVideos()
{
    //some code
}

?>

Hamed Khosravi
  • 535
  • 7
  • 21
1

i don't think you can call a php function from javascript. Javascript cannot run a php code, since PHP codes will run before the webpage loads, and the javascript runs after webpage loads.

Anyway, you can still use ajax to run an external PHP file like this:

$.ajax({
    url:'php/ajax_post.
    type: 'post',
    data: {function: "any_function"}
    success: function(data)
    {
        window.alert(data);
    }
});

In your PHP file, add an if statement, like this:

if(isset($_POST['function']) && $_POST['function']=="any_function")
{
    //Run your function
}

This will run your requested function, and alert the result.

131
  • 1,363
  • 1
  • 12
  • 32
0

You can use PHP's include() function to "import" functions from other PHP files.

jh314
  • 27,144
  • 16
  • 62
  • 82