I’m new to PHP and Ajax. I am working on a dynamic website for personal use which requires the website to respond to the window width of the client.
At the moment this is set up to send the width through an Ajax GET request and just print the size back to the screen, although this PHP script will print a response before the page gets to load, leaving a static ‘width < 1275’ at the top of the page which will never be removed.
How would I go about solving this issue? Thanks
HTML
<body>
<div class="contents">
</div>
</body>
JavaScript
$(document).ready(function() {
var width = $(window).width();
$.ajax({
url: 'functions.php',
type: 'GET',
data: {size : width},
success: function(response) {
$('#contents').html(response);
}
});
$(window).resize(function() {
var width = $(window).width();
$.ajax({
url: 'functions.php',
type: 'GET',
data: {size : width},
success: function(response) {
$('#contents').html(response);
}
});
});
});
PHP
<?php
$width = $_GET['size'] ?? '';
if($width < 1275)
{
echo('<div class="column">' . 'width < 1275' . '</div>');
}
else
{
echo('<div class="column">' . 'width > 1275' . '</div>');
}
?>
2
Answers
Try your AJAX code with
async: false
like:Well your js code is just fine. 1s make sure you have jquery,
here is the CDN: https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js ,
Then change
<div class="contents">
to<div id="contents">
because
$('#contents').html(response);
‘#’ is for id selector & ‘.’ for class so$('.contents').html(response);
will be the code if you want to use class for DOM.and in php part functions.php do something like this :
and here is my index page :