Source code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Content-Type: application/json');
echo json_encode($_POST);
exit(0);
}
?>
<html>
<head>
<title>Web Test</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
<form id="formTest">
<input name="username" value="admin" />
<input name="password" type="password" value="admin_pass" />
</form>
<script type="text/javascript">
$.ajaxSetup({
data: {role: 'admin'} //(I)
});
//Ajax to current page
$.ajax('test', {
method: 'post',
data: $('#formTest').serialize() //(II)
,success: function(res){
console.log(res);
}
});
</script>
</body>
</html>
I want to send the form data by jQuery AJAX, and append default data (role=admin
) to every AJAX request, but it doesn't work as I want.
I take some option like below:
data: {role: 'admin'} //(I)
(for default data)
data: $('#formTest').serialize() //(II)
(for form data)
(This is exactly as the source code above)
=> RESULT from console:{username: "admin", password: "admin_pass"}
So, this approach seem does not workdata: 'role=admin' //(I)
data: $('#formTest').serialize() //(II)
(Same URLencoded format)
=> Same as abovedata: [{name: 'role', value: 'admin'}] //(I)
data: $('#formTest').serializeArray() //(II)
(Same serializeArray format)
=> Same as abovedata: {role: 'admin'} //(I)
data: {username: 'admin', password: 'admin_pass'} //(II)
=> This approach works! But there is no built-in jQuery method to convert form data to object like that. I must use a "thirt-party" solution use$('#formTest').serializeObject()
(from here).
So, is there any way to solve this problem with jQuery only?
JQuery offer ajaxSetup
and serialize/serializeArray
method but they seem not play well with each other.