I'm trying since hours, to submit a form with AJAX, in order not to refresh or redirect the page.
I use this code to submit :
$('#files').on(submit, function(e) {
e.preventDefault();
$.ajax({
url:'actions.php',
type:'post',
data:$(this).serialize(),
success:function(){
console.log('sent');
},
error:function(){
console.log('not sent');
}
});
});
However, I noticed that there is nothing when I serialize the form. It's just blank. I submit my form, and a PHP script fetches the name of the button pressed to determine what to do next. In my example, the button name starts with "edit" so I'll only show the concerned part.
else if (substr($index, 0, 4) == "edit") {
$q = "UPDATE files SET file_name = '" . $_POST[$index] . "', file_path = 'users/" . $_SESSION['username'] . "/" . $_POST[$index] . "'" . " WHERE id = " . $file_id;
mysqli_query($link, $q);
rename('users/'.$_SESSION['username'].'/'.$filename, 'users/'.$_SESSION['username'].'/'. $_POST[$index]);
echo(json_encode(array('success'=>true)));
}
It keeps redirecting when I don't use the e.preventDefault()
and when I use it, it does not submit anything.
EDIT: Here is the HTML
<td>
<span name="edit22" contenteditable="true">fake</span>
<div>
<span>
<button type="submit" name="edit22" form="files" value="fake">
<i class="fa fa-check" aria-hidden="true"></i>
</button>
</span>
<span>
<button>
<i class="fa fa-times" aria-hidden="true"></i>
</button>
</span>
</div>
</td>
the fa fa-check
button, with javascript will take for value the content of the first <span>
element.
Where am I doing it wrong ?