简体   繁体   中英

PHP getting a response from the server

I am a little bit confused with PHP. It's a simple question

I want to submit a form. For example:

<form name='formname' action='code.php' method="POST">
    <input name='inputname' type='text'/>
    <input type='submit'>
</form>

So, the server gets whatever is typed and for argument sake it adds cool to the end of the text and echos $inputname.'cool text you got there';

How do I get that response and use it in my javascript?

Your response would be in code.php or a page that code.php redirects to.

Basically, you submit the form, it loads code.php, any logic that the form inputs use go there and interact with the database, then you choose how to redirect the user from there.

If you want to see if the inputname form input is getting set, you can do this:

<?php
        if(isset($_POST["inputname"]))
        {
            $inputname = $_POST["inputname"];
            echo $inputname;
        }
        else
        {
            echo "inputname not set!";
        }
?>

To get it to be used in your javascript, one potential way of doing that is adding a variable to the url:

./mypage.php?input=yourinputname

Then, on your main page with the form (or whatever page you redirect to), you can use PHP to check to see if $_GET['input'] exists, then echo it if you like.

If you want it on the new page - so the form is submitted, the browser goes to the PHP page specified in the form.. Then you'd have something like this..

<?php
$input = $_POST['input'] . 'Cool text you got there!';
?>
...
<script type="text/javascript">
var varName = '<?php echo $input ?>';
</script>

However, if you want AJAX style without jQuery - you'd use XMLHttpRequest to get the data from the PHP script directly into the webpage, by intercepting the event handler for the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM