can you give me an example code of calling java script
function in php variable using AJAX.or with out ajax??????
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 |
What are the methods of array in java?
What is difference between web service and api?
what method is used to get a user's IP address?
Does php need html?
How to turn on the session support in php?
What is difference between put and post method in http?
How do you identify independent and dependent variables in regression analysis?
What is cURL in PHP?
Can I use php in html?
What are magic constants in php?
What is config file in php?
What type of comments are supported by PHP.