ioan ioan - 1 month ago 6
Ajax Question

Submitting form with AJAX not working. It ignores ajax

I've never used Ajax before, but from researching and other posts here it looks like it should be able to run a form submit code without having to reload the page, but it doesn't seem to work.

It just redirects to ajax_submit.php as if the js file isn't there. I was trying to use Ajax to get to ajax_submit without reloading anything.

Is what i'm trying to do even possible?

HTML form:

<form class="ajax_form" action="ajax_submit.php" method="post">
<input class="input" id="license" type="text" name="license" placeholder="License" value="<?php echo htmlentities($person['license1']); ?>" />
<input class="input" id="license_number" type="text" name="license_number" placeholder="License number" value="<?php echo htmlentities($person['license_number1']); ?>" />

<input type="submit" class="form_button" name="submit_license1" value="Save"/>
<input type="submit" class="form_button" name="clear1" value="Clear"/>
</form>


in scripts.js file:

$(document).ready(function(){
$('.ajax_form').submit(function (event) {
alert('ok');
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize(),
success: function (data) {alert('ok');}
});
});
});


in ajax_submit.php:

require_once("functions.php");
require_once("session.php");
include("open_db.php");

if(isset($_POST["submit_license1"])){
//query to insert
}elseif(isset($_POST['clear1'])) {
//query to delete
}


I have "
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
"
in the html head

Answer

form.serialize() doesn't know which button was used to submit the form, so it can't include any buttons in the result. So when the PHP script checks which submit button is set in $_POST, neither of them will match.

Instead of using a handler on the submit event, use a click handler on the buttons, and add the button's name and value to the data parameter.

$(":submit").click(function(event) {
    alert('ok');
    event.preventDefault();
    var form = $(this.form);
    $.ajax({
        type: "POST",
        url: "ajax_submit.php",//form.attr('action'),
        data: form.serialize() + '&' + this.name + '=' + this.value,
        success: function (data) {alert('ok');}
    });
});
Comments