I want to pass screen width (viewport) to a PHP variable.
I am not familiar with AJAX but as I understand this is the proper way to do it.
I run my website (Coding a WordPress theme) in a local server at the moment (XAMPP) & getting the following error when I try to pass the JS variable to PHP.
POST http://localhost/ 404 (Not Found)
Below is the AJAX part of the code:
<?php
// Handle AJAX request (start)
if (isset($_POST['ajax']) && isset($_POST['name'])) {
echo $_POST['name'];
echo "test";
exit;
}
// Handle AJAX request (end)
?>
<!-- Script -->
<script>
document.addEventListener("DOMContentLoaded", function() {
var ViewPort = $(window).width();
console.log(ViewPort)
$.ajax({
type: 'post',
data: {
ajax: 1,
name: ViewPort
},
success: function(response) {
$('#response').text('name: ' + response);
}
});
});
</script>
Additionally, I don’t want to use jQuery since I load it(jQuery) on the footer & the changes based on the viewport need to be applied first.
If you could guide me through this I’ll be grateful
2
Answers
So I found a solution to my problem without using AJAX. So I wanted to pass screen width to a PHP variable in order to change display images on my website based on the device viewport(desktop or tablet).
I found out that this can be done using srcset.
Below will take the current screen width, save as a variable, send this variable through to PHP using AJAX then it will return results using JSON based on how the PHP code handles the AJAX POST data it has been sent.
If you want this to be dynamic, in the jQuery script replace the first line
with;
Code below, PHP file should be a separate file so it can be fetched by AJAX.