简体   繁体   中英

Execute PHP function with Javascript onClick without page refresh

My research is pointing me to Ajax and/or JQuery, but I wanted to ask to make sure I understand and move in the right direction.

I've been looking to use a javascript onclick function to create a popup(alert) asking to confirm that I want to proceed and show the changes I'm about to make.

I hoped that I could use PHP $_POST or GET to echo the change in the popup/alert window. However without the page refresh it appears I can't do this, but looking for a confirmation? Should I be looking for Ajax to do this? Any thoughts/suggestions would likely give me a head start as php/ajax is sort of foreign to me.

Sample code:

<script>     
function clicked() {
    if (confirm('Do you want to submit? <?php if(isset($_POST['city'])){$city = $_POST['city'];echo $city;}?>')) 
    {
        yourformelement.submit();
    } else {
        return false;
    }
}
</script>
</head>
<form action="output.php" method="post">
  <input name="city">

<input type="submit" onclick="clicked();" value="Button" />
 </form>

</html>

You can get the input value with jQuery before submitting:

<form action="output.php" method="post" id="form">
    <input name="city" id="city_input">
    <input type="submit" value="Button" />
</form>
<script>     
    $('#form').submit(function(e) {
        e.preventDefault();
        let cityInputVal = $('#city_input').val();
        if (confirm('Do you want to submit ' + cityInputVal + '?')) 
        {
            this.submit();
        } else {
            return false;
        }
    });
</script>

The preventDefault() function stops the form submission and therefore, page refresh.

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