Reputation: 3023
How would I go about executing a php-script from a javascript-function?
<?php if ( isset( $results['errorMessage'] ) ) { ?>
<script type="text/javascript>somemethod(<?php echo $results['errorMessage'] ?>) </script>
<?php } ?>
Sorry for the bad formatting - not sure how to use code in this editor :S
Upvotes: 0
Views: 134
Reputation: 767
Are you trying somethig like call a simple JS function with a message?
<?php
if(isset($results['errorMessage'])){
echo '<script type="text/javascript>somemethod("'.$results['errorMessage'].'")</script>';
}
?>
Upvotes: 0
Reputation: 22956
If this is part of a template your example just needs to tweaking to generate the correct JavaScript on the page:
To fix this example you could try
<?php if ( isset( $results['errorMessage'] ) ) { ?>
<script type="text/javascript>
somemethod(<?php echo "'" . $results['errorMessage'] . "'" ?>);
</script>
<?php } ?>
But as other answers suggest, it may better to go down the ajax route. Generating JavaScript is often a bad design choice.
Upvotes: 0
Reputation: 1955
i use this one to send request with javascript and its works perfectly :
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
alert(xmlHttp.responseText);
}
and the html code :
<html>
<head>
<script type="text/javascript" src="log.js"></script>
</head>
<body>
<a href="" onclick="httpGet('message.php?url=http://bizzare.com/?id=1')">Get Message</a>
</body>
</html>
Upvotes: 0
Reputation: 20394
You can't! Javascript executes on client-side (ie. client's browser) and PHP executes on the server.
What you can do is to make an Ajax request to your PHP script and do something according to the results.
Upvotes: 1
Reputation: 181270
You need to make an HTTP REQUEST from JavaScript to call a remote PHP page/script.
The way you are trying to do it is not possible at all.
Upvotes: 1