0

Im running a form in a webshop that looks like this:

<form>
  <input type="number" name="quantity" value="" required = "required" />
  <input type="radio" name="homeDelivery" value="" required = "required" checked="true" />
  <input type="radio" name="homeDelivery" value="" required = "required" />
  <input type="submit" value="buy" name="submitBuy" class="buy formConfirm" />
</form>

After the submit button is pressed I run a simple error check in php from the info I get from $_POST. I have an array called $errors, if my error check finds any errors it adds them to my array, else not, and if the array stays empty til the end, my form will submit the data, else not.

I do however want to have a JS confirmbox after pressing submit, that will only popup if there are no errors in the actual form. So to my actual question: Is it possible to check in javascript code if my $errors variable is empty? Something that works like this:

if(empty($errors)) {
   //run code
}

If it is possible Id like my javascript code to look something like this(I think you get the idea);

$('.buyConfirm').on('click', function(){
   if (errors == NULL) {
      return confirm('Are you sure?');
   }
   else {
      return false;
   }
});

Any help is appreciated,

Cheers!

1
  • 1
    Cleanest/quickest way would be to do validation on the form with javascript. Commented Oct 27, 2016 at 14:12

1 Answer 1

2

You need to output your PHP var as a JS array, best using json_encode, and then consume that in your condition

<script>
    var errors = <?php echo json_encode($errors); ?>;
    if (errors.length < 1) {
        if (confirm("Are you sure?")) {
            // User has no errors and has confirmed
        } else {
            // User has no errors but did not confirm
        }
    } else {
        // User has errors
    }
</script>
Sign up to request clarification or add additional context in comments.

5 Comments

That will allow the form to be posted without validation, validated at the server and then when the page is returned you would need to click the buy button again to be told it failed validation. This requires client-side validation (ideally both).
That wasn't the question, the question was how to use a PHP variable in javascript
Honestly, do you think this answers the OP's question?
I've understood your comment now. I hadn't updated the original example other than the conditional on the error variable
Thanks for understanding. I still don't think the OP is being clear, but this definitely answers their question.

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.