-1

i'd like to call a jquery function from php. I tried this way, but the jquery functions are not called.

jq.action.js

$(function() {

  $("#reset" ).click(function(e){       
    e.preventDefault();
    reset_fields();
  });

  function reset_fields(){
    $(":input").prop('selectedIndex', 0);
  }

  function error_msg(){
    alert("Error");
  }

});

index.php

<script type='text/javascript' src='jquery-1.11.1.min.js'></script>
<script type='text/javascript' src='jq.action.js'></script> 

<?php
if ($_POST['id'] == '1') {

       echo '<script>reset_fields();</script>';

} else {

       echo '<script>error_msg();</script>';
}
?>

ReferenceError: reset_fields is not defined

how can I call from php the functions inside jquery? thanks!

Paolo Rossi
  • 2,490
  • 9
  • 43
  • 70

2 Answers2

1

Your problem is JavaScript scoping: the function you're trying to call is not accessible from everywhere.

$(function() {
    function reset_fields(){
        // this function is only accessible to things inside $(function(){...
    }
}

That means that you can't access it directly. However, if you place the function outside, it will work:

function reset_fields() {
    // now this function is globally accessible from anywhere
}

$(function() {
    // you can still call reset_fields() from here
}
pp19dd
  • 3,625
  • 2
  • 16
  • 21
0

Php runs on the server and javascript on the client, so the terminology "call a javascript function" is incorrect.

You can set a javascript variable with php then test that variable with javascript on the client. This will make your code a bit simpler

 var postId = '<?php echo $_POST["id"] ?>';

 if( postId === '1'){
  reset_field();
 }
 else {
  reset_field();
 }
Community
  • 1
  • 1
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45