-2

With the help of AJAX, I've been trying to prevent the automatic redirection to a blank PHP page after submitting a form, but I'm not managing. The data submitted to the form is being entered into the MySQL table, but upon clicking submit, I'm always redirected to the blank insert.php page. Here is the HTML form:

            <tr>
                <td></td>
                <form class = "ajax" action = "insert.php" method="POST">
                    <td><input type="text" class = "inputs" name = "dcs" id = "dcs"/></td>
                    <td><input type="text" class = "inputs" name = "qty" id = "qty"/></td>
                    <td><input type="text" class = "inputs" name = "rate" id = "avg"/></td><td></td>
                    <td><div style = "position: relative;"><input type="submit" onclick="add_new_entry();" id = "submit"/></div></td>
                </form>
                <td></td>
            <tr>  

Here is the jQuery function:

        $(document).ready(function() {
        
            $('form.ajax').submit(function(event) {
                event.preventDefault();
                var that = $(this),
                    url = that.attr('action'),
                    type = that.attr('method'),
                    data = {};

                that.find('[name]').each(function(index, value) {
                    var that = $(this),
                        name = that.attr('name'),
                        value = that.val();

                    data[name] = value;
                });

                $.ajax({
                    url: url,
                    type: type,
                    data: data,
                    success = function(response) {
                        alert(response);
                    }
                });
                return false;

            });

        });

Here is insert.php:

<?php

include "db_connect.php";

$code = 4;
$dcs =  mysqli_real_escape_string($conn, $_POST['dcs']);
$qty = mysqli_real_escape_string($conn, $_POST['qty']);
$rate =  mysqli_real_escape_string($conn, $_POST['rate']);
$total = $qty * $rate;

$sql = "INSERT INTO entries  VALUES ('$code',
            '$dcs','$qty','$rate','$total');";

// $conn is the connection
mysqli_query($conn, $sql)

mysqli_close($conn);

?>

Please let me know of the changes that I should make so that I'm not redirected to the PHP page after submitting the form.

Let me know if I should provide any other code snippets.

Thanks a lot.

  • Does this answer your question? [Prevent redirect after form is submitted](https://stackoverflow.com/questions/4038567/prevent-redirect-after-form-is-submitted) – OMi Shah Jul 31 '21 at 17:19
  • 1
    What does `add_new_entry();` do? Also, an easier way of getting all inputs would be to just do `data = that.serialize();` instead of your `that.find(....)` function. – M. Eriksson Jul 31 '21 at 17:21
  • Check your browsers console and I'm sure you have some error messages in there. You have some syntax error which probably stops your JS from being executed at all and will there for submit the form "normally". `success = function(response) ` should be `success: function(response) ` – M. Eriksson Jul 31 '21 at 17:24
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Jul 31 '21 at 17:26
  • @MagnusEriksson thanks a lot, both your suggestions were needed to fix my problem! – Vibhu Dalal Jul 31 '21 at 17:55

1 Answers1

0

So there is a neat trick where you can add return false; on the onclick function to prevent the page from submitting. I think the issue in here is that you submit the form already before you prevent it from submitting, what you could do otherwise is creating a click event before the submit part which needs to prevent the submittion of the formm OR use the jquery $.post en instead of the submit event