1

I have a file called try.php where there is code below having all javascript, PHP and html file in itself.

<?php

if(isset($_POST["submit"])){
    echo "hello";
}

?>
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form method="POST" id="myForm">
    <input name="name" type="text" placeholder="Your Name">
    <input name="email" type="text" placeholder="email">
    <input name="submit" type="submit" value="Submit">
    <div id="display"></div>
</form>
<script>
$(document).ready(function(){
    $("#myForm").submit(function(event) {
        event.preventDefault(); //prevent default action 
        window.history.back();
        var form_Data = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "try.php",
            data: form_data,
            cache: false,
            success:function(response){
                alert(response);
            }
        });
    });
});

</script>
</body>
</html>

The target of above code is just to submit form without reloading the page simply using AJAX and the form data should be handled by php here just echo "hello". The above code works fine it submits and php handles all properly but page is reloading. What should be the change in code?

1 Answers1

1

Try this as javascript code

$(document).ready(function(){
    $("#myForm").click(function(event) {
        event.preventDefault(); //prevent default action 

        var form_Data = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "try.php",
            data: form_Data,
            cache: false,
            success:function(){
                alert("hello");
            }
        });
    });
});
Niyoj oli
  • 342
  • 3
  • 15
  • 3
    I recommend explaining where the problem was instead of simply pasting the correct code. This way more people can learn from the error. – VVV Mar 04 '20 at 04:52