0

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>
3
  • 8
    $.ajax is your best friend. Submitting a form will refresh your page, just do an asynchronous request. Commented Feb 19, 2019 at 20:20
  • Its not posible. @kemicofa answer would be your best option. Commented Feb 19, 2019 at 20:22
  • Thanks. I thought this was the case. I will start digging into Ajax . Commented Feb 19, 2019 at 20:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the example. I was able to replicate this with slightly different JQuery/Ajax code, but this example is spot on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.