Ryan D Ryan D - 2 months ago 13
PHP Question

ajax form request still reloads page

I am trying to submit a form using ajax with jquery mobile without it refreshing the page and am having no luck..

I have this form -

index.php:

<script>
function SubmitForm() {
var name = $("#name").val();
$.post("bump.php", { name: name},
function(data) {
//alert(data);
});
}
</script>


<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>


Here is bump.php

$date = date('y/m/d H:i:s');
$id = $_POST['name'];
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";

if ($conn->query($sql) === TRUE) {

} else {
echo "Error updating record: " . $conn->error;
}


I would like to maintain my position on the page but it refreshes each time? What am I doing wrong here?

Answer

Use event.preventDefault(); Cancels the event if it is cancelable, without stopping further propagation of the event.

Default behaviour of type="image" is to submit the form hence page is unloaded

function SubmitForm(event) {
  event.preventDefault();
  var name = $("#name").val();
  $.post("bump.php", {
      name: name
    },
    function(data) {
      //alert(data);
    });
}
<form method="post" data-ajax="false">
  <input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
  <input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm(event);" value="Send" />
</form>

Comments