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

276
Vistas
Why AJAX dont´t pass value of name from html File-(JS part) to PHP File using POST?

I tried to pass value of name from .js file to PHP using POST method. But when I start the code, there isn´t any alert.
In console is only: Uncaught ReferenceError: $ is not defined
Do you know what could be improved?

<html>
<body>
<head>
<script type="text/javascript">


const name = "asdasd";

$.ajax({
  url: "TargetFile.php",
  method: "POST",
  data: {
    name
  },
  success: function (result) {
    alert(result);
  },
  error: function (error) {
    alert("Error " + error.status);
  }
})
    
</script>
</head>
</body>
</html>
<?php
  $name = $_POST['name'];
  if (empty($name)) {
    echo "Name is empty";
  } else {
    echo $name;
  }
}
?>
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You need to load the jQuery lib before using it. And also the head tag should be outside of the body tag.

<html>
    <head>    
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script type="text/javascript">


           const name = "asdasd";

           $.ajax({
               url: "TargetFile.php",
               method: "POST",
               data: {
                   name
               },
               success: function (result) {
                   alert(result);
               },
               error: function (error) {
                   alert("Error " + error.status);
               }
           })

        </script>
    </head>
    <body>
    </body>
</html>
about 4 years ago · Santiago Trujillo Denunciar

0

As a simple, single page, test script that will send a POST request to the server which sends the response for the ajax callback. As others have stated - you should include the jQuery library but you need to change the payload to a valid object literal. The POST request expects name=value pairs as per below.

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        $result=!empty( $_POST['name'] ) ? $_POST['name'] : 'Name is empty';
        exit( $result );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Basic jQuery Ajax POST</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
        <script>
        
            const name = "Geronimo frequently kicked ass";

            $.ajax({
              url: location.href,   //"TargetFile.php"
              method: "POST",
              data: {
                'name':name
              },
              success: function(result) {
                alert(result);
              },
              error: function(error) {
                alert("Error " + error.status);
              }
            })      
        </script>
    </head>
    <body>
        
    </body>
</html>

Using 2 separate scripts, one that makes the request (index.html) and the other that processes the request and sends the response (targetfile.php)

index.html

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Basic jQuery Ajax POST</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
        <script>
        
            const name = "Geronimo kicked ass";

            $.ajax({
              url: "TargetFile.php",
              method: "POST",
              data: {
                'name':name
              },
              success: function(result) {
                console.log( result )
              },
              error: function(error) {
                alert("Error " + error.status);
              }
            })      
        </script>
    </head>
    <body>
        
    </body>
</html>

targetfile.php

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        $result=!empty( $_POST['name'] ) ? $_POST['name'] : 'Name is empty';
        exit( $result );
    }
?>

Both scripts in same directory, request is made OK and console message is displayed ( removed annoying alert )

about 4 years ago · Santiago Trujillo 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