Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda