userK1400 userK1400 - 2 months ago 11
jQuery Question

Making a form submit NOT reload the page

I am still learning proper and more efficient ways of writing code - at the moment I am stuck on this current issue.

I have a form that currently works fine - writes to the sql database, then reloads the current page. I would like the form to NOT reload the page.

I know there is a way to do this with jQuery and Ajax -- honestly I'm not skilled yet with these.


  1. If there's a way to do this with PHP/HTML - I would love guidance on this method.

  2. If the only answer is Java and Ajax - I would love guidance for this specific instance of changing this form to not reload the page.



Screen shot of what the button looks like -- three colors to represent 3 stages of tracking payment on invoices. Red turns to yellow when clicked, yellow to green, green back to red (in case of a mistake click).

Button example

Here's front end code for my form:

<form action="jump_invoicepaid.php" method="post">
<input type="hidden" name="invoicepaid" value="'.$projectid.'">');
if ($projectpaid == 2) {
echo('<button type="submit" name="action" class="greenbutton" value="unpaid">Paid</button></form>');
} else if ($projectpaid == 1) {
echo('<button type="submit" name="action" class="yellowbutton" value="paid">Paid</button></form>');
} else {
echo('<button type="submit" name="action" class="redbutton" value="sent">Paid</button></form>');
}


Here's the back end code for my form:

if ($_POST['action'] == paid) {
///marking project as paid
include_once('toolbox.php');
$projectid = $_POST['invoicepaid'];
mysqli_query($con, "UPDATE kmis_projects SET project_paid='2' WHERE project_id= '$projectid'");
header('Location: ./?page=pastevents');

} else if ($_POST['action'] == sent) {
///marking project as sent
include_once('toolbox.php');
$projectid = $_POST['invoicepaid'];
mysqli_query($con, "UPDATE kmis_projects SET project_paid='1' WHERE project_id= '$projectid'");
header('Location: ./?page=pastevents');

} else if ($_POST['action'] == unpaid) {
///marking project as unpaid
include_once('toolbox.php');
$projectid = $_POST['invoicepaid'];
mysqli_query($con, "UPDATE kmis_projects SET project_paid='0' WHERE project_id= '$projectid'");
header('Location: ./?page=pastevents');
}


I do want to learn jQuery and ajax fully, it's next on my to learn list. I know they would make this issue a lot easier to solve.

UPDATE -- I spent some time with the link posted, suggesting it was a duplicate question of the link. I do see why... but it's not the same at the heart of what I'm asking or the answer that was given in the link. I think the link could be "an" answer to the issue - but I was interested in any ways of solving the issue without having to use jQuery and AJAX -- and if that was unavoidable, then specifically how AJAX would fit into my code and this specific situation. I equally think this is unique from the link, given that my buttons are populated with 3 different "if" checks, to write a different value depending on what button is populated and clicked.

UPDATE 2 --
Here's the current code I'm working with. The ajax isn't sending name or value of button though it seems.

<script>
$( document ).ready(function() {
$("button").click(function(e) {
e.preventDefault(); // prevent page refresh

$.ajax({
type: "POST",
url: "jump_invoicepaid.php",
data: $(this).serialize(), // serialize form data
success: function(data) {
window.location.replace("?page=pastevents");
},
error: function() {
// Error ...
}
});
});
});
</script>

<form action="">
<input type="hidden" name="invoicepaid" value="'.$projectid.'">

if ($projectpaid == 2) {
echo('<button type="submit" name="action" class="greenbutton" value="unpaid">Paid</button></form>');
} else if ($projectpaid == 1) {
echo('<button type="submit" name="action" class="yellowbutton" value="paid">Paid</button></form>');
} else {
echo('<button type="submit" name="action" class="redbutton" value="sent">Paid</button></form>');
}

Answer

In order to execute the server-side script (PHP) from the client side (static HTML and JavaScript), you need to use the Ajax technology. In essence, Ajax will allow you to send and/or retrieve data from the server "behind the scenes" without affecting your page.

JavaScript, a client-side scripting language used to add interactivity to your webpage, already supports Ajax. However, the syntax is rather verbose, because you need to account for differences across browsers and their versions (Internet Explorer version 5 up to 11 in particular have their own implementation different from Chrome or Mozilla).

You, as a developer, can avoid these technicalities by using a front-end framework such as jQuery (other good examples are Angular.js, Vue.js, and others). jQuery is essentially a library of code written in vanilla JavaScript that simplifies common tasks such as querying DOM. It also provides expressive syntax for using Ajax. It will resolve browser incompatibilities internally. This way you can focus on your high-level logic, rather than low-level issues like that.

Once again, jQuery code is also JavaScript code. So place the following <script> tag, as you would normally do with JS, somewhere in your page.

<script>
$( document ).ready(function() {
    $("form").submit(function(e) {
        e.preventDefault(); // prevent page refresh

        $.ajax({
            type: "POST",
            url: "jump_invoicepaid.php",
            data: $(this).serialize(), // serialize form data
            success: function(data) {
                // Success ...
            },
            error: function() {
                // Error ...
            }
        });
    });
});
</script>

First, this code will run once the page is loaded. Second, it will attach a submit event handler to every <form> in your HTML page. When you click on the <button type='submit'>, this event will fire. e.preventDefault() will halt the normal submission of the form and prevent page refresh. Note that e is the event object that contains info about the submit event (such as which element it originated from).

Next, we are sending the actual Ajax request using $.ajax method from jQuery library. It is a generic method, and we could as well have used $.post, since we are specifically doing the POST request. It will be received by your PHP file jump_invoicepaid.php.

Now, in your PHP file, you have the following line: header('Location: ./?page=pastevents'); which forces a redirect to the home page with a GET parameter. If you want to have the same behavior, then you would need to remove that line, and put window.location.replace("/?page=pastevents") to your JavaScript code:

// in your Ajax request above...
success: function(data) {
    window.location.replace("/?page=pastevents");
},

This would refresh the page however, because you are essentially requesting the home page with a GET method. I am guessing that this is done in order to update information on the page. You could do so without redirecting, by adding / changing / removing elements on your page (i.e. in DOM). This way, you would send data from the server back to the client, and if the response is received successfully, in your JavaScript you can obtain that response and manipulate your webpage accordingly.

If the latter interests you, then consider using JSON format. You just need to do json_encode in your PHP, and then on the client-side, parse the JSON string using JSON.parse(...). Read on here for example.

Hope this helps!

Comments