Thursday, 6 September 2018

Ajax does not receive a reply from the php file

This form is working perfectly fine, e.g. it stops the form submitting, there's no javascript errors in the console log. However, when I press submit, I get an alert with nothing in it. I have searched the internet for multiple solutions and they all give the same for me.
Here's my Javascript/Html
<script>
$(function(){
    $("#submit").click(function(event){
        event.preventDefault();
        $.ajax({
            type:"post",
            url:"templates/process-token.php",
            data:$("#form").serialize(),
            success:function(response){
                alert(response);
            }
        });
    });
});
</script>

<form id="form" method = "post" action = "security_check">
    <input type = "text" name = "fld1" id = "fld1" />
    <input type = "text" name = "result1" id = "result1" value = "value_from_php_page" disabled />
    <input type="submit" value="Submit" id="submit">
</form>

And here's the PHP, it's so simple but doesn't work:
<?php
    echo $_POST["fld1"];
?>

Any help here would be appreciated. Thank you.

Change data from $('#form').serialize() to a one test variable so you can see if it is JS or PHP that is causing the issue.
On your PHP page:
<?php
   isset($_POST["fld1"]) ? $myvar1 = $_POST["fld1"] : $myvar1 = 'No data passed...';
   echo $myvar1;
?>

This confirms that there is infact an fld1 in the $_POST, and if not, says so, taking away the guess work...

0 comments:

Post a Comment