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'); ?>');
}
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'); ?>');
}
Share
Improve this question
asked Jun 4, 2013 at 19:03
Dsfljk HeselkjdshfDsfljk Heselkjdshf
111 silver badge2 bronze badges
2
- In this specific case you can use an echo ("<script> alert('" . mail_tome('person') . "')</script>"); .. but this is a workaround the best way is to use AJAX – Lefsler Commented Jun 4, 2013 at 19:08
- Do not forget that php will generate an HTML and will return it to the client. PHP is processed on the server and the final information is returned to the client. – Lefsler Commented Jun 4, 2013 at 19:10
3 Answers
Reset to default 4Its not possible, PHP is processed on the server, while Javascript is rendered on the client side after the server has pleted 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./jQuery.ajax/
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.
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
}
});
}