I have been trying to get an ajax call to work inside a function triggered by an onclick event. When I use event.preventDefault the page is not reloaded but the ajax call does not work, no data is added to my database. When I comment out that line the page is reloaded but everything else works.
function clickFunction(elem) {
var var1 = elem.id;
var var2 = var1.split("_");
// elem.preventDefault();
if (var2[0] == "Add") {
if (var2[1] == "Calls") {
console.log("Calls");
console.log(var1);
event.preventDefault();
var data = $(this).serialize();
$.post('progressSheetDynamic', data).done(function (response){
$(".1").html(parseInt($('.1').html(), 10)+1);
Calls.update(50);
});
}
}
}
Html code
<form action="{{ route("progressSheetDynamic") }}" method="post" id= {{ $addID }}>
<input name="increment" value="increment" type="hidden"> </input>
<input type="hidden" name="id" value= {{$activities}} >
<button type="submit" class="styleHover styleButton" onclick="clickFunction(this)" id= {{ 'Add_'.$newText }}> + </button>
</form>
I have checked the logs and the function is going into the if statement. I have also tried using preventDefault on the button click event, by doing elem.preventDefault(); but this does not work. Neither does using return false.
return false;
to youronclick
.onclick="clickFunction(this); return false;"
– I.G. Pascualonclick="clickFunction(this)"
toonclick="clickFunction(this, event)"
and add theevent
parameter to your function, like:function clickFunction(elem, event) {...
– user1106925var data = $(this).serialize();
should bevar data = $(elem.form).serialize();
Thethis
will be a reference to thewindow
object, whereaselem
is thebutton
soelem.form
will be the form to serialize (assuming that's what you wanted). – user1106925