Home > Enterprise >  How AJAX mystery can be solved of a variable inside quotes?
How AJAX mystery can be solved of a variable inside quotes?

Time:09-11

I have copied codes from some sites to explore how Ajax works in pure Javascript. I experienced a strange code that inside quotes have the variable which retrieved the value of input from the HTML form. If we change the variable in the quotes or put some text in the quotes then it does not print the input value. Let me give the HTML and Ajax code here:

<HTML>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Form Example</title>
</head>

<body>
   <label for="fname">First Name</label>
   <input type="text" id="fname" size="50"  placeholder="First Name"> 
   <br />
   <div id="fnp"></div>
   <br />
   <button type="button" onclick="custajax();">Submit</button>
   <br/><br />

   <script>

      function custajax(){
          var xm = new XMLHttpRequest();
          var url = "cust.php";

          var fn = document.getElementById("fname").value;
          
          /* Please see the below code that if fname inside the quotes is changed
             to anything then it doesn't print the value. */
          var strange = "fname=" fn;

          // var strange = "Any text = "   fn;  (it doesn't work of if we put directly fn in the xm.send(fn)


          xm.open("POST", url, true);
          xm.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          xm.onreadystatechange = function() {
               if(xm.readyState == 4 && xm.status == 200) {
                   var return_data = xm.responseText;

                   document.getElementById("fnp").innerHTML = return_data;
               }
          }

          xm.send(strange); // it works
          //xm.send(fn); //  it doesn't work
     }

   </script>
   </body>
   </html>

PHP:

   <?php
       if ( isset( $_POST[ "fname" ] ) ) {
            echo "<br /><br />First Name =  " . $_POST[ "fname" ];

       };
   ?>
   

CodePudding user response:

By this part you're specifying the input name that is fname

 var strange = "fname=" fn;

As you know, we recognize input value by the name of it. since here we're specifying it's name as fname we can get it as follows:

$_POST['fname']

And if you want to change the name from fname to example you should also apply this in your PHP

$_POST['example']
  • Related