How to Use PHP in a JavaScript Function

How can I call PHP functions by JavaScript?

Yes, you can do ajax request to server with your data in request parameters, like this (very simple):

Note that the following code 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_functions_address.php like this:

    <?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);

?>

How to call a JavaScript function from PHP?

As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.

All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.

Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.

So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".

There are many ways to do this, but here are a couple.

Using just PHP:

echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;

Escaping from php mode to direct output mode:

<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>

You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.

Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.

Here's an example of what I think you're doing with jQuery's AJAX

$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;

// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();

// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);

function someOtherFunctionYouWantToCall() {
// stuff
}

Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.

$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);

* Or JSON or XML etc.

Use PHP variable as Javascript function parameters

Seems like you forgot about quotes, when you are passing strings into function.

<script>
$(document).ready(function () {
autoFill('{{ $dropDown }}', '{{ $emptyDropDown }}');
});
</script>

You can do it this way, but you shouldn't, because Laravel Blade do it for you itself.

<?php echo "<script> autoFill('".$dropDown."', '".$emptyDropDown."'); </script>"; ?>

How do I embed PHP code in JavaScript?

If your whole JavaScript code gets processed by PHP, then you can do it just like that.

If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.

For example, in your index.php (or wherever you specify your layout), you'd do something like this:

<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>

You could then use my_var in your JavaScript files.

This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.

Call Javascript function and execute PHP at the same time?

You can just load the new page with PHP after you check the login. Unless you have some other reason you need to do it with JavaScript, I think it makes more sense to do it in PHP anyway, because you'll want to do different things depending on whether or not the login was successful.

if ($result->num_rows > 0) {
$_SESSION["email"] = $_POST['email'];
header('Location: new url');
exit;
}
else {
echo "Incorrect username or password. Please try again!";
}

Is it possible to write javascript function inside of php code?

Yes that's entirely possible. Basically all that happens here is the value which is echoed by PHP gets embedded in the JS and the whole JS block is then passed to the browser, which runs it - effectively the same as if you'd hard-coded the value instead of echoing it.

The issue you'll have with this specific code is that you can't echo within an echo...instead just concatenate the value into the string you're already building!

e.g.

<?php echo "<script> javscript_function(".$php_number_variable."); </script>"; ?>

Or, since you're using double-quote strings, the variable can be interpolated directly:

<?php echo "<script> javscript_function($php_number_variable); </script>"; ?>


Related Topics



Leave a reply



Submit