can you give me an example code of calling java script
function in php variable using AJAX.or with out ajax??????



can you give me an example code of calling java script function in php variable using AJAX.or with..

Answer / Abhinav Asgola

To call a JavaScript function from PHP using AJAX, you can use the jQuery library. Here's an example:

1. Create a JavaScript file (example.js) containing your function:

```javascript
function getSum(a, b) {
return a + b;
}
```

2. Include the jQuery library and call the JavaScript function from PHP using AJAX:

```php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url : '<?php echo $_SERVER['PHP_SELF']; ?>',
type : 'post',
dataType : 'json',
data : {a: 5, b: 3},
success : function(data) {
console.log('Sum of numbers is: ', data.sum);
}
});
});
</script>
```

In PHP, create a script (example.php) to handle the AJAX request and return the result:

```php
<?php
$a = $_POST['a'];
$b = $_POST['b'];
$sum = $a + $b;
echo json_encode(array('sum' => $sum));
?>

Without using AJAX, you can use the PHP eval() function to call JavaScript code. However, be cautious with this approach as it may expose security risks:

```php
<?php
$jsCode = "var a = 5; var b = 3; var sum = a + b; echo 'Sum of numbers is: ', sum;";
eval($jsCode);
?>
```

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More PHP Interview Questions

What are the methods of array in java?

1 Answers  


What is difference between web service and api?

1 Answers  


what method is used to get a user's IP address?

2 Answers  


Does php need html?

1 Answers  


How to turn on the session support in php?

1 Answers  


What is difference between put and post method in http?

1 Answers  


How do you identify independent and dependent variables in regression analysis?

1 Answers  


What is cURL in PHP?

1 Answers  


Can I use php in html?

1 Answers  


What are magic constants in php?

1 Answers  


What is config file in php?

1 Answers  


What type of comments are supported by PHP.

1 Answers  


Categories