Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Simple AJAX ~ Viewport Width to PHP variable

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 ??
 }
 }
 });
 });
about 4 years ago · Juan Pablo Isaza Report

0

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 class="MainImage" 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']; ?>">
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!