I remember I using the jQuery ajax post last year and i could simply get the post data by typing $_POST['param']
. Today I am using it again for a project so I loaded the latest jQuery lib and used the following code:
<script type="text/javascript">
$(document).on('submit', '.ajaxform', function(e){
e.preventDefault();
var datastring = $(this).serialize();
$.ajax({
type: "POST",
data: datastring,
contentType: "application/json; charset={CHARSET}",
dataType: "json",
beforeSend: function(){
console.log($(this).serialize());
},
success: function(data){
alert('yes');
},
error: function(errMsg){
alert('error');
}
});
});
</script>
<form action="" id="register" name="register" class="ajaxform" method="post" enctype="multipart/form-data">
<input type="text" name="username" value="" />
<input type="password" name="password" value="" />
<input type="hidden" name="action" value="register" />
<input type="hidden" name="{TOKENID}" value="{TOKEN}" />
<input type="submit" value="Register" />
</form>
After I submit, I can't get the input field value by typing $_POST['username']
.
I checked the inspect element, and I noticed that something is different.
Request URL:http://project0/member.php
Request Method:POST
Status Code:200 OK
...
...
Content-Type:application/json; charset=UTF-8
...
...
Request payload:
username=asd&password=asd&action=register&29cd5e5ca1=73050db390872eb7c3fc564206b961c59a6363d6
Is that why i can't get the POST data by simply typing $_POST['param']
? How do I go back to POST data and not the payload?
data : A plain object or string that is sent to the server with the request. success : A callback function that is executed if the request succeeds.it takes as an argument the returned data. It is also passed the text status of the response.
ajax() (and various ajax shortcut methods) returns a jqXHR object, which is a superset of the browser's native XMLHttpRequest object and implements inter alia the Promise interface.
ajax returns a promise object, so that we don't have to pass a callback function.
Except:
contentType: "application/json; charset={CHARSET}"
Use(default value of content type):
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With