JS Prompt to PHP Variable [closed]

随声附和 提交于 2019-11-28 06:54:50

问题


Is this possible? Or do I really need to AJAX JS first?

<?php
echo'< script type="text/javascript">var eadd=prompt("Please enter your email address");< /script>';
$eadd = $_POST['eadd']; ?>

and how can I do that with AJAX?


回答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'];
?>



回答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




回答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');
?>


来源:https://stackoverflow.com/questions/26209967/js-prompt-to-php-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!