1

I have a form that saves some data in a MySQL table, and after doing it, the website is redirecting to the index.php page, which I don't want to occur, I just want it to stay in the same page.

I have some ajax passing the form values:

      $("#incomeSave").click(function() {

      alert("incomeSave");

    $.ajax({

      type:"POST",
      url: "actions.php?action=incomeSave",
      data: "date=" + $("#incomeDate").val() + "&value=" + $("#incomeValue").val() + "&category=" + $("#incomeCategory").val() + "&subcategory=" + $("#incomeSubCategory").val() + "&account=" + $("#incomeAccount").val() + "&description=" + $("#incomeDescription").val(),

      success: function(result) {

      alert(result);

      } 

    })

  })

Then the query is executed:

    if ($_GET['action'] == "incomeSave") {

    if (!$_POST['value']) {

        echo "Valor vazio";

    } else {

            mysqli_query($link, "INSERT INTO incomes (`user_id`,`income_date`,`income_value`,`income_category`,`income_subcategory`,`income_account`,`income_description`) VALUES ('1','". mysqli_real_escape_string($link, $_POST['date'])."','". mysqli_real_escape_string($link, $_POST['value'])."','". mysqli_real_escape_string($link, $_POST['category'])."','". mysqli_real_escape_string($link, $_POST['subcategory'])."','". mysqli_real_escape_string($link, $_POST['account'])."','". mysqli_real_escape_string($link, $_POST['description'])."')");

            echo "After SQL";

    }

}

What should I do so the page is not redirected to the index.php?

Pablo Brenner
  • 183
  • 1
  • 1
  • 10

1 Answers1

0

If you have a <form> tag in your HTML, any <button> or <input type="button"> will trigger a reload automatically. To prevent this from happening, you need to pass an element parameter and call the .preventDefault() method. Here's what you should do using e as the parameter:

$("#incomeSave").click(function(e){
    e.preventDefault();
    alert("incomeSave");
    $.ajax({
        type:"POST",
        url: "actions.php?action=incomeSave",
        data: "date=" + $("#incomeDate").val() + "&value=" + $("#incomeValue").val() + "&category=" + $("#incomeCategory").val() + "&subcategory=" + $("#incomeSubCategory").val() + "&account=" + $("#incomeAccount").val() + "&description=" + $("#incomeDescription").val(),
        success: function(result){
            alert(result);
        }
    });
});

Also, your database is open to SQL injection, use parameterized statements!

Zeke
  • 1,281
  • 1
  • 18
  • 26
  • This worked just fine! Thanks a lot Zeke! Also thanks for the SQL tip, I have been programming for just a few months as a hobby so I did not know about it, I will definitely read about it and implement! All the best! – Pablo Brenner Apr 04 '17 at 04:25
  • I'm glad. Please refer to this question to learn about parameterized statements and a whole lot more too: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 Happy coding! – Zeke Apr 04 '17 at 04:27