Submitting the form to the same page without reloading it
I am trying to submit a form using Ajax without refreshing the page. It is important that the form is submitted to the same page, which is why I am using url: 'customer-management?form_sent=yes'
.
Html
<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
<i onclick="$(this).closest(\'form\').submit()" id="' . $get_uncontacted_member->id . '" class="fa fa-phone-square called"></i>
</form>
Js
$('.called').click(function() {
$.ajax({
type: 'post',
url: 'customer-management?form_sent=yes',
data: $(this).attr('id');
success: function(r) {
alert(r);
}
})
})
PHP
if (isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes') { return 'That worked!' }
The page is reloading and I think I am doing everything wrong.
+3
source to share
3 answers
You are not transferring your data correctly. Since you are making a POST request, you should not be passing your data as a query string. Instead, pass it through a data property. Also add return false;
to prevent the form from submitting.
$.ajax({
type: 'post',
url: 'customer-management',
data: { form_sent: 'yes' },
success: function(r) {
alert(r);
}
});
return false;
You can remove this code:
onclick="$(this).closest(\'form\').submit()"
+2
source to share
Try the following:
<form method="post">
<i id="<?php echo $get_uncontacted_member->id; ?>" class="fa fa-phone-square called"></i>
</form>
<script>
$('.called').click(function()
{
$.ajax({
type : 'post',
url : 'customer-management',
data : {form_sent: 'yes',id:$(this).attr('id')},
success: function(r)
{
alert(r);
}
})
});
</script>
PHP:
<?php
if(isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes')
{
echo 'That worked!';
exit;
}
?>
+1
source to share