Reputation: 11
I was trying to build web application where user clicks a button and it prompts them to enter email address using JavaScript prompt functionality like this.
function mail_me(x)
{
var person = prompt('Please enter your email Address','[email protected]');
}
than I want to call PHP function inside my JavaScript and pass person as parameter of that PHP function. Is it possible to do it. I have tried this so far.
function mail_me(x)
{
var person=prompt('Please enter your email Address','[email protected]');
alert('<?php mail_tome('person'); ?>');
}
Upvotes: 1
Views: 8305
Reputation: 324620
Such a thing is impossible. PHP is executed on the server, and the result is passed to the browser.
You can, however, use AJAX to send the variable to the server. Example:
var a = new XMLHttpRequest();
a.open("POST","/path/to/script.php",true);
a.onreadystatechange = function() {
if( this.readyState != 4) return;
if( this.status != 200) return alert("ERROR "+this.status+" "+this.statusText);
alert(this.responseText);
};
a.send("email="+person);
This will cause whatever the PHP script echo
s to the browser to appear in the alert
. Of course, you can customise this as much as you like, this is just a basic example.
Upvotes: 1
Reputation: 7643
You need something that is called AJAX. If you know and using JQuery it has built in functionality for AJAX.
Example:
function mail_me() {
var person = prompt('Please enter your email Address','[email protected]');
$.ajax({
type: 'post',
url: URL TO YOUR SCRIPT,
data: {
email: EMAIL_VARIABLE
},
success: function(result) {
//handle success
}
});
}
Upvotes: 0
Reputation: 9302
Its not possible, PHP is processed on the server, while Javascript is rendered on the client side after the server has completed it works.
You would need to use Ajax to take the value of person
, and pass it via ajax back to a php script on the server which would then process your request.
http://api.jquery.com/jQuery.ajax/
Upvotes: 4