JQuery Ajax POST请求触发成功但数据未传递问题求助
Let's break down the key problems in your code that are causing the data not to be passed correctly, even though the alert is popping up:
1. Wrong Success Callback Implementation
The way you've written the success handler is a common mistake:
success: alert('yay')
This executes alert('yay') immediately when the AJAX object is created, not when the request actually succeeds. That's why you see the alert but the request might not be working properly. You need to wrap it in an anonymous function so it only runs after a successful response:
success: function() { alert('yay'); }
2. Invalid AJAX URL
Using $_SERVER["DOCUMENT_ROOT"] gives you the server's file system path (like /var/www/html/inhoud/dashboard/change_order.php), but browsers can't use file system paths for AJAX requests. You need a web-accessible URL instead. Depending on your site's structure, use either a relative path or a root-relative path:
// Root-relative path (starts with /) - works if your site is at the domain root url: '/inhoud/dashboard/change_order.php', // OR relative path (if this script is in a subdirectory relative to change_order.php) url: 'dashboard/change_order.php',
3. Minor: Unscoped Variable in Loop
Your id variable inside the .each() loop isn't declared with var, let, or const, which makes it a global variable. While this might not break the request, it's bad practice and can cause unexpected behavior later. Fix it with:
var id = $(this).attr('id');
Fixed Full Code
Here's the revised script with all these fixes, plus a cleaner way to build the ids string using jQuery's .map():
<script> $(function(){ $('.sortable').sortable({ stop:function() { // Cleanly build the ids string using map() var ids = $('.sortable div').map(function() { return $(this).attr('id'); }).get().join(','); $.ajax({ // Use a web-accessible URL url: '/inhoud/dashboard/change_order.php', data: {ids: ids, user_id: '<?php echo $user_id; ?>'}, type: 'POST', // Correct success callback success: function() { alert('yay'); }, // Optional: Add an error handler to debug failures error: function(xhr, status, error) { console.log('AJAX Error:', status, error); console.log('Response:', xhr.responseText); } }); } }); }); </script>
Debugging Tips to Confirm It's Working
- Open your browser's Developer Tools (F12) and go to the Network tab. Trigger the sortable stop event, then look for the POST request to
change_order.php. Check:- If the request returns a 200 OK status
- The Payload tab to see if
idsanduser_idare being sent correctly
- In your
change_order.php, add this at the top to verify data is being received:
<?php var_dump($_POST); exit; ?>
This will show you exactly what data the script is getting. If you see the correct ids and user_id, then the issue is in the rest of your change_order.php logic.
内容的提问来源于stack exchange,提问作者Thoder

