How can I submit form data using jquery ajax without submitting the form?
I have a form on my page that I don't want to submit. Here is an example of what I am trying to do basically. When I click on the button, I want to submit an ajax request, but not submitting the form. This is the approximate format of the function that will run when my button is clicked:
function clicked()
{
try {
var url = "test.php?t1=1&t2=2"
var postData = $("#myForm").serializeArray();
$.ajax(
{
url : url,
beforeSend: function (request)
{
request.setRequestHeader('Content-Type', 'text/html; charset=utf-8');
},
type: "POST",
data : postData,
contentType: false,
processData: false,
success:function(data, status, xhr)
{
if(status == "success")
{
alert(data);
// Do something on page
}
else
{
// Do something on page
}
},
});
}
catch (e)
{
alert("Error Adding POI:\n" + e);
}
}
When I disable the form submission using the preventDefault function, the form is not submitted. However, the form just sends an ajax post request to my url "test.php? T1 = 1 & t2 = 2" without any input from my form. Without warning Default, the form is submitted and navigated away from the page. The ajax request is not being sent. Is there a way to submit form data to the url "test.php? T1 = 1 & t2 = 2" with an ajax request without submitting the form?
Thanks in advance. Any help is appreciated.
source to share
TRY:
$('input [type="submit"]').on('click',function(e){
e.preventDefault();
var url = "test.php?t1=1&t2=2"
var postData = $('this').serialize();
$.ajax(
{
url : url,
beforeSend: function (request)
{
request.setRequestHeader('Content-Type', 'text/html; charset=utf-8');
},
type: "POST",
data : postData,
success:function(data, status, xhr)
{
if(status == "success")
{
alert(data);
// Do something on page
}
else
{
// Do something on page
}
},
});
})
source to share
The following dirty hack might work when I dig up some details for you. Keep using preventDefault
to prevent form submission.
//Change
var url = "test.php?t1=1&t2=2"
var postData = $("#myForm").serializeArray();
//To
var url = "test.php"
var postData = "t1=1&t2=2&" + $("#myForm").serialize();
source to share