Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

When I tried to call a PHP function into JavaScript from some external PHP file, but it's not working, Herewith I have attached my code:

This is PHP code:

<?php

function add($a,$b){

  $c=$a+$b;

  return $c;

}

function mult($a,$b){

  $c=$a*$b;

  return $c;

}

function divide($a,$b){

  $c=$a/$b;

  return $c;

}

?>

This is JavaScript code:

<script>

  var phpadd= add(1,2); //call the php add function

  var phpmult= mult(1,2); //call the php mult function

  var phpdivide= divide(1,2); //call the php divide function

</script>

Can anyone help me with this?

1 Answer

0 votes
by (26.7k points)

You can able to use ajax request, you can take the below example, it uses jQuery:

jQuery.ajax({

    type: "POST",

    url: 'your_functions_address.php',

    dataType: 'json',

    data: {functionname: 'add', arguments: [1, 2]},

    success: function (obj, textstatus) {

                  if( !('error' in obj) ) {

                      yourVariable = obj.result;

                  }

                  else {

                      console.log(obj.error);

                  }

            }

});

And your php will look likes:

<?php

    header('Content-Type: application/json');

    $aResult = array();

    if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }

    if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }

    if( !isset($aResult['error']) ) {

        switch($_POST['functionname']) {

            case 'add':

               if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {

                   $aResult['error'] = 'Error in arguments!';

               }

               else {

                   $aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));

               }

               break;

            default:

               $aResult['error'] = 'Not found function '.$_POST['functionname'].'!';

               break;

        }

    }

    echo json_encode($aResult);

?>

I hope this will help.

Want to become a Java expert? join Java Certification now!!

Related questions

0 votes
1 answer
asked Dec 22, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Nov 29, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 13, 2021 in Java by dante07 (13.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...