Patrick L. Çakırlı Patrick L. Çakırlı - 2 months ago 7
HTML Question

Script doesn't function properly upon output of data

Yesterday evening, I figured out how to output data, send from my form on my index page to my content page, then have its results displayed inside my content div back on my index page.

But now I have an new problem. My Javascript will not apply its function (renderGrid) to my content div, unless I mess with the viewport, because then window.addEventListener("resize", renderGrid, false); comes into play.

I don't know how else to explain it.

Thanks,

index.html

<form id="search_form" action="content.php" method="POST">
<input id="form_search" type="search" name="name">
<input id="form_submit" type="submit" name="submit" value="Enter">
</form>

<div id="content"></div>


js

$(document).ready(function(){
var form = $('#search_form');
form.submit(function(event){
var form_search = $('#form_search').val();
if($.trim(form_search) != '') {
$.post("content.php", {name: form_search}, function(data){
$('#content').html(data);
});
}
event.preventDefault();
});
});

function renderGrid(){

var blocks = document.getElementById("content").children;
var pad = 20, cols = 3, newleft, newtop;
for(var i = 1; i < blocks.length; i++){
if(i % cols == 0){
newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;
blocks[i].style.top = newtop+"px";
}else{
if(blocks[i-cols]){
newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;
blocks[i].style.top = newtop+"px";
}
newleft = (blocks[i-1].offsetLeft + blocks [i-1].offsetWidth) + pad;
blocks[i].style.left = newleft+"px";
}
}
}
window.addEventListener("load", renderGrid, false);
window.addEventListener("resize", renderGrid, false);


content.php

<?php
include ("connect.inc.php");
$userinput = $_POST['name'];
$query = "SELECT * FROM xxx WHERE xxx LIKE '%$userinput%'";
$result = mysqli_query($db_link, $query) or die(mysqli_error($db_link));
while($row = mysqli_fetch_assoc($result)){
?>

<article>
<?php echo $row['xxx'];?>
</article>

<?php
}
?>


Picture 1 = This is what it does.
(When I submit Russia, my query will get me two results, but as you can see, these results are now on top each other upon output. This is because the JavaScript is unaware, that I have outputted something.)


Picture 2 = This is what it should look like, when outputted.
(Now, if I mess with the viewport, such as open inspect, my JavaScript begins to work (window.addEventListener("resize", renderGrid, false);), so my JavaScript works, but not when I output data, but not automatically when I output data.)

Answer

load event (as in manual) fires when your object (window) finished loading. This event doesn't fire when you load some ajax content. So, you should call your renderGrid explicitly:

$.post("content.php", {name: form_search}, function(data){
    $('#content').html(data);       
    renderGrid();
});
Comments