Nicklas Pouey-Winger
Nicklas Pouey-Winger

Reputation: 3023

How can I execute php from a javascript function?

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

Answers (5)

gustyaquino
gustyaquino

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

Matt Esch
Matt Esch

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

bizzr3
bizzr3

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

fardjad
fardjad

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

Pablo Santa Cruz
Pablo Santa Cruz

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

Related Questions