Reputation: 296
I am making a small drag and drop app using jQuery UI's Sortable feature. The jQuery works fine but when I try to encode the array of all of the lines in their order, the PHP script on the other side reads the array as NULL
and I cannot figure out why. Here's everything in the order that they appear in my first script:
The HTML
<form method="post" id="reorder" action="orderupdate.php">
<input type="hidden" id="post_ids" name="post_ids">
<button type="submit">REORDER</button>
</form>
<ul id="photo-selector">
<li id="img1"><img src="images/img1.jpg"></li>
<li id="img2"><img src="images/img2.jpg"></li>
<li id="img3"><img src="images/img3.jpg"></li>
<li id="img4"><img src="images/img4.jpg"></li>
<li id="img5"><img src="images/img5.jpg"></li>
<li id="img6"><img src="images/img6.jpg"></li>
</ul>
The JS
$(document).ready( function(){
var formOrder = document.getElementById('reorder');
formOrder.addEventListener('submit', function(){
var post_ids_field= document.getElementById('post_ids');
var ul_id = document.getElementById("photo-selector");
var post_ids = ul_id.getElementsByTagName("li");
post_ids_field.value = JSON.stringify(post_ids);
alert("check");
});
});
When clicking the "REORDER" button in the form up top it sends to orderupdate.php
which is as follows
<?php
$post_ids = json_decode($_POST['post_ids']);
var_dump($post_ids);
require("opendbas3.php");
foreach ($post_ids as $x => $value) {
$query = "UPDATE dav_posts SET p_order='$x' WHERE post_id='$value'";
$result = mysql_query($query, $link);
}
?>
Now when I do submit, it redirects me to the PHP script orderupdate.php
it doesn't execute the query and I found out that the foreach
loop cannot read the $post_ids
array. I only get NULL
with my var_dump()
. Also, the alert
in the JS script doesn't fire off on either the ready()
function or the event listener's submit. It just redirects to the PHP script.
Is something out of order? What could be wrong? Thanks in advance.
Upvotes: 0
Views: 128
Reputation: 102793
You can't call JSON.stringify on DOM elements -- that is the reason the alert never fires. You'll find it crashes with TypeError: Converting circular structure to JSON
.
What you need to do is map the li
array to an array of strings:
var id_strings = [];
for (var i=0 ; i<post_ids.length ; i++) {
id_strings.push(post_ids[i].getAttribute("id"));
};
post_ids_field.value = JSON.stringify(id_strings);
Upvotes: 1
Reputation: 423
Try to use
post_ids = $("#photo-selector").sortable( "toArray");
post_ids_field.value = JSON.stringify(post_ids);
Upvotes: 0