jQuery AJAX call using POST is only retrieved with $_GET?
I have the following code that works:
<script type="text/javascript">
$(document).ready(function() {
// Initialise the table
$('#table_1').tableDnD({
onDrop: function(table, row) {
$.tableDnD.serialize();
$.ajax({
type: "POST",
url: "test.php?"+$.tableDnD.serialize(),
data: "",
success: function(html){
alert("Success");
}
});
}
});
});
</script>
Sending data to test.php:
开发者_如何学Python<?php
$table_1[] = $_GET['table_1'];
$i = 0;
if(!empty($table_1[0])){
foreach($table_1 as $value) {
foreach($value as $row){
$i++;
mysql_query("UPDATE mytable SET tableOrder='$i' WHERE id = '$row'");
}
}
}
?>
As you can see the table_1 array retrieves the data using $_GET, but that ajax code says we're sending with POST. If I change $_GET to $_POST it no longer works. Why is this?
When you read from $_POST
, you should pass the values in data
instead of in the URL querystring.
Your JavaScript code would have to change as follows:
$.ajax({
type: "POST",
url: "test.php",
data: $.tableDnD.serialize(),
success: function(html){
alert("Success");
}
});
Then you would be able to do:
<?php
$table_1[] = $_POST['table_1'];
?>
Your orignal code was working because as Mike Sherov noted in a comment below, any data passed in the URL querystring can always be accessed with $_GET
, regardless of the HTTP verb used to submit the data.
That because you put the parameter in the URL (which is kind of a GET way). To use POST parameter, you must put it in the data area. Like this.
<script type="text/javascript">
$(document).ready(function() {
// Initialise the table
$('#table_1').tableDnD({
onDrop: function(table, row) {
$.tableDnD.serialize();
$.ajax({
type: "POST",
url: "test.php"+,
data: "" + $.tableDnD.serialize(),
success: function(html){
alert("Success");
}
});
}
});
});
</script>
Assuming that $.tableDnD.serialize()
produces a valid query string.
Hope this helps.
I think it's because you're building the POST URL with a query string and adding the values from tableDnD to your URL.
See the documentation and specifically the section "Sending Data to the Server".
url: "test.php?"+$.tableDnD.serialize(),
This part generates a get request you need to use it like this:
$.ajax({
type: "POST",
url: "test.php",
data: $.tableDnD.serialize(),
success: function(html){
alert("Success");
}
});
Your script sends no DATA trough the POST method, and ad the target file is something with GET data, PHP just sees it as date passed trough the URL.
You need to put the data in the data option. ;)
精彩评论