Skip to content Skip to sidebar Skip to footer

JS Prompt To PHP Variable

Is this possible? Or do I really need to AJAX JS first? var eadd=prompt('Please enter your email address');< /script>'; $e

Solution 1:

Its not possible. You should use ajax. jQuery was used in the following example:

<script>
var eadd=prompt("Please enter your email address");
$.ajax(
{
    type: "POST",
    url: "/sample.php",
    data: eadd,
    success: function(data, textStatus, jqXHR)
    {
        console.log(data);
    }
});
</script>

in php file

<?php
echo $_POST['data'];
?>

Solution 2:

Ajax (using jQuery)

<script type="text/javascript">
$(document).ready(function(){

var email_value = prompt('Please enter your email address');
if(email_value !== null){
    //post the field with ajax
    $.ajax({
        url: 'email.php',
        type: 'POST',
        dataType: 'text',
        data: {data : email_value},
        success: function(response){ 
         //do anything with the response
          console.log(response);
        }       
    }); 
}

});
</script>

PHP

echo 'response = '.$_POST['data'];

Output:(console)

response = email@test.com


Solution 3:

Is not possible directly. Because PHP is executed first on the server side and then the javascript is loaded in the client side (generally a browser)

However there are some options with or without ajax. See the next.

With ajax. There are a lot of variations, but basically you can do this:

//using jquery or zepto
var foo = prompt('something');
$.ajax({
    type: 'GET', //or POST
    url: 'the_php_script.php?foo=' + foo
    success: function(response){
        console.log(response);
    }
});

and the php file

<?php
    echo ($_GET['foo']? $_GET['foo'] : 'none');
?>

Witout ajax: If you want to pass a value from javascript to PHP without ajax, an example would be this (although there may be another way to do):

//javascript, using jquery or zepto
var foo = prompt('something');
//save the foo value in a input form
$('form#the-form input[name=foo]').val(foo);

the html code:

<!-- send the value from a html form-->
<form id="the-form">
    <input type="text" name="foo" />
    <input type="submit"/>
</form>

and the php:

<?php
    //print the foo value
    echo ($_POST['foo'] ? $_POST['foo'] : 'none');
?>

Post a Comment for "JS Prompt To PHP Variable"