0

I am protecting my forms with a captcha code to prevent using bots submitting loads and loads of forms. This form works with AJAX and won't refresh the page like it usually does. I have everything set now and it is working. but.. So this is the form im talking about to help understand.

enter image description here

When you click on request a new password, i need the code to change on the input field. I do change the code after requesting a password like this in newpass.php

$_SESSION['capcode3'] = $capcode3;

This is my javascript code:

<script>
    $("#formoid").submit(function(event) {
      event.preventDefault();
      var form_data = $(this).serialize(); //Encode form elements for submission

      $.ajax({
            type: "POST",
            url : "data/newpass.php/",
            data : form_data 
        });
      document.getElementById("captcha").value = "<?php echo $_SESSION['capcode3']; ?>";
    });
</script>

So by using document.getElementById it would change the input value but, instead of setting the new value, it sets the old value. So if the code is ABC123 and the new code is DEF456 it wont change to DEF456

Is there a better way to send the new code back to the input field?

Note: I have tested if $_SESSION['capcode3'] will change it's value with a positive result.

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
  • 2
    `` gets executed only once, when you initially load the resource that contains this JS code from the server. You can change the contents of your session all you want, that will not change the value of your input field - because the value inside your JS code never changes. You should go read https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming first of all, to acquire the understanding in that regard that you currently seem to be missing. – misorude Jan 21 '19 at 12:32
  • The PHP script you make the AJAX request to should return this value, and then you should update the form field with it from within the success handler of your AJAX call. – misorude Jan 21 '19 at 12:32

2 Answers2

0

You did not specify a success handler in your ajax. Ajax is handled async, thus needs a callback to where the data will be passed when the request is succesfuly handled

  $.ajax({
        type: "POST",
        url : "data/newpass.php/",
        success: function(data) {
             //change UI here
             document.getElementById("captcha").value = data;
        },
    });
DarkBee
  • 16,592
  • 6
  • 46
  • 58
-1

Please add code in success of ajax because may be session value will be changed on ajax success.

  $.ajax({
        type: "POST",
        url : "data/newpass.php/",
        data : form_data,
        success :function(data){
           document.getElementById("captcha").value = data;
        }
    });

Please try with this.

Madhuri Patel
  • 1,270
  • 12
  • 24