Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda