Use buttons to post to a php script

谁说我不能喝 提交于 2020-01-05 04:55:12

问题


Basically I am going to have a control panel for an application I'm working on that is just an array of buttons. I want to pass information about which button was pressed to the script that will handle the actual commands. I can't quite figure out how to use POST do that... Here's some code that I have so far.

<php
include("writemessage.php");
echo " <form action='writemessage.php' method='POST'>
<input type='submit' name='message' value='custom1'/>
<input type='submit' name='message' value='custom2'/>
</form>";
?>

As far as I can gather from reading through some tutorials and documentation it should be working? The writemessage.php script just puts the information in a file, and I tested it with GET and it worked just fine.

<?php
$file = 'log.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Change file to command.
$current = $_POST[message];
// Write the contents back to the file
file_put_contents($file, $current);
?>

I want it to submit in background. I want it to appear as though it doesn't refresh or navigate anywhere..


回答1:



No Ajax

In fact it works... just a few details to fix (noted in comments):

<?php //<-- here it was "<php" fix that!
    include("writemessage.php");
    //Don't sent people over to writemessage, otherwise why did you include it?
    echo '<form action="" method="POST">
    <input type="submit" name="message" value="custom1"/>
    <input type="submit" name="message" value="custom2"/>
    </form>';
    //Note: I changed quotes, no big deal
    echo $current; //you can read $current
?>

writemessage.php:

<?php
    $file = 'log.txt';
    if (isset($_POST['message'])) //check if isset, also use quotes
    {
        // Change file to command.
        $current = $_POST['message']; //again quotes
        // Write the contents back to the file
        file_put_contents($file, $current);
    }
    else
    {
        if (file_exists($file)) //check if file exists
        {
            // Open the file to get existing content
            $current = file_get_contents($file);
        }
        else
        {
            // default value?
            //$current = '???';
        }
    }
?>

Ajax

I didn't notice you said "submit in background", does it mean you don't want a page load? you can do that with Ajax...

<?php include("writemessage.php"); ?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
    function _submit(value)
    {
        //This is the value set locally, do you want to be able to get values from other users? that is a whole level more complex
        $('#current').html(value);
        //Here we send the info the server via AJAX with jQuery
        var ajax = $.ajax(
        {
            type: "POST",
            url: "writemessage.php",
            data: {message: value}
        });
        //This is the value form the server, note: it may change from another client and this will not be updated
        ajax.done(function(response)
        {
            $('#current').html(response);
        });
    }
</script>
<form action="">
    <input type="button" name="message" value="custom1" onclick="_submit('custom1')"/>
    <input type="button" name="message" value="custom2" onclick="_submit('custom2')"/>
</form>
<span id="current"><?php echo $current; ?></span>

Note 1: I'm using jQuery from the url http://code.jquery.com/jquery-1.10.2.min.js choose the version you want and place it in your server instead.

writemessage.php:

<?php
    $file = 'log.txt';
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && array_key_exists('message', $_POST))
    {
        $current = $_POST['message'];
        file_put_contents($file, $current);
        echo $current; //this is the response we send to the client
    }
    else
    {
        if (file_exists($file)) //check if file exists
        {
            $current = file_get_contents($file);
        }
        else
        {
            //$current = '???';
        }
    }
?>

Note 2: You also be interested in POST-REDIRECT-GET.




回答2:


Make sure you have distinct names for your buttons, that's how you are going to reference them in the $_POST array.

For example, instead of what you have, try this:

<input type='submit' name='message_1' value='custom1'/>
<input type='submit' name='message_2' value='custom2'/>



回答3:


1 - As you want to submit this via background, you need to use Ajax. I'll show how to use with Jquery's Ajax.

2- As you want to post in background, you don't need <form> anymore:

    <php
    include("writemessage.php");
    ?>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>

        //Post data to "writemessage.php" on background (AJAX)
        function customSubmit(optionVal)
        {

            $.ajax({
              url: "writemessage.php",
              data: { 
                    'message': optionVal
                },
            }).done(function(data) {
              //if you want to see what this return, use alert(data);
            });

        }


    </script>



echo "
<input type='button' name='message1' value='custom1' onclick="javascript:customSubmit("custom1");"/>
<input type='button' name='message2' value='custom2' onclick="javascript:customSubmit("custom2");"/>
";
?>

3 - now in your read file, you can read POST "hidOption" as value of selected button:

<?php
$file = 'log.txt';
// Open the file to get existing content
$current = file_get_contents($file);

// Change file to command.
$current = $_POST["message"]; //Here is "hidOption"!

// Write the contents back to the file
file_put_contents($file, $current);
?>

Easy as that.




回答4:


<form method="post">
    <div class="response"></div>
    <input type="submit" name="message" value="custom1" />
    <input type="submit" name="message" value="custom1" />
<form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    jQuery(function ($) {
        $('form').on('submit', function (e) {
            e.preventDefault();
            $.ajax({
                context : this,
                data : $(this).serialize(),
                type : 'post',
                url: 'writemessage.php'
            }).success(function (response) {
                $(this).find('.response').html(response);
            });
        });
    });
</script>

Also, your writemessage.php file could be cleaned up a bit.

<?php
$file = 'log.txt';
if (file_exists($file))
{
    // Do some kind of validation on your input.
    if (in_array($_POST['message'], array('custom1', 'custom2'))
    {
        file_put_contents($file, $_POST['message']);
        echo "<p>The value is {$_POST['message']}</p>";
    }
    else
    {
        echo '<p class="error">Illegal value!!</p>';
    }
}


来源:https://stackoverflow.com/questions/20295406/use-buttons-to-post-to-a-php-script

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