Home > Mobile >  Simple AJAX ~ Viewport Width to PHP variable
Simple AJAX ~ Viewport Width to PHP variable

Time:02-27

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

CodePudding user response:

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

 $(document).ready(function() {

with;

 $(window).on('resize', function() {

Code below, PHP file should be a separate file so it can be fetched by AJAX.

 <?php
 header('Content-type: application/json');
 $viewPort = $_POST['viewPort']; // You may want to protect this data using mysqli_real_escape_string
 // Viewports under 800px width
 if (($viewPort) < 800) {
 $response = "small";
 }
 // Viewports over 800px width
 if (($viewPort) > 800) {
 $response = "large";
 }
 // Allow front end to read result
 echo json_encode($response);
 ?>


 //jQuery script
 $(document).ready(function() {
 var viewPort = $(window).width();
 console.log(viewPort); // Check we have the width
 $.ajax({
 url:"somefolder/myPHPfile.php", // Referencing above PHP (should be a separate file)
 method:"POST",
 data:{viewPort:viewPort},
 dataType:"json",
 success:function(a) {
 if (a == "small") {
 console.log("the viewport size is small");
 // Do some other function ??
 }
 if (a == "large") {
 console.log("the viewport size is large");
 // Do some other function ??
 }
 }
 });
 });

CodePudding user response:

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.

<img  src="<?php echo get_field('main_slider_image')['url']; ?>"
srcset="<?php echo get_field('main_slider_image_mobile')['url']; ?> 835w, <?php echo get_field('main_slider_image')['url']; ?> 836w"
alt="<?php echo get_field('main_slider_image')['alt']; ?>">
  • Related