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

<?phpecho$_POST['data'];
?>

Solution 2:

Ajax (using jQuery)

<scripttype="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 responseconsole.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 zeptovar foo = prompt('something');
$.ajax({
    type: 'GET', //or POSTurl: 'the_php_script.php?foo=' + foo
    success: function(response){
        console.log(response);
    }
});

and the php file

<?phpecho ($_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 zeptovar 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--><formid="the-form"><inputtype="text"name="foo" /><inputtype="submit"/></form>

and the php:

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

Post a Comment for "Js Prompt To Php Variable"