knot22 knot22 - 4 months ago 17
PHP Question

Error in PHP file for Ajax response

I found this helpful example:

https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

that shows how to work with data using Ajax. However, the article does not give details about what the PHP file should contain to make the example actually work.

I have tried this:

<?php
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
echo json_encode($computedString);
?>


And variations thereof, to no avail. The result is a message box that says undefined. What should be in the PHP file for this example to make it work?

Here is the HTML page, complete with the JS:



<label>Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>

<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function()
{
var userName = document.getElementById("ajaxTextbox").value;
makeRequest('test.php',userName);
};

function makeRequest(url, userName)
{
httpRequest = new XMLHttpRequest();

if (!httpRequest)
{
alert('Giving up - cannot create an XMLHTTP instance.');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('userName=' + encodeURIComponent(userName));
}

function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
try
{
var response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
})();
</script>





EDIT:

The alertContents() function was modified as follows:



function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
console.log(response);
console.log(httpRequest.responseText);
var response = "default message";
try
{
response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);

return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}





The first console.log line is line #44 in the script. Rerunning the program and looking in the Console here is what happens:
enter image description here

When



console.log(response);





is commented out this is the result:
enter image description here

ANOTHER EDIT:

The problem does indeed appear to have been in the PHP script. Here is the updated PHP script and the result:



$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['computedString' => $computedString];
echo json_encode($array);





enter image description here

A further improvement:



$array = ['userData' => $name, 'computedString' => $computedString];





results in:
enter image description here

Ash Ash
Answer

Updated:

Based on my understanding with your comments, it looks liek your PHP file is not returning the JSON response. It is returning the text whihc you passed from your form. So your responseText is simple string.

Hence, when you are trying to read it's property, it is undefined. Try the following code now.

function alertContents()
  {
    if (httpRequest.readyState === XMLHttpRequest.DONE)
    {
      if (httpRequest.status === 200)
      {
          if(httpRequest.responseText == '')
           {
                alert('Error in code');
                return;
           }
        alert(httpRequest.responseText);

      }
      else
      {
        alert('There was a problem with the request.');
      }
    }
  }

Original: There is an issue with the variable scope in your code.

var response = JSON.parse(httpRequest.responseText);

Here, you are defining response as a variable inside the try block and then trying to alert outside the block. That is why it is undefined.

Either you should move the alert statement inside the TRY block or define the variable outside.

 function alertContents()
  {
    if (httpRequest.readyState === XMLHttpRequest.DONE)
    {
      if (httpRequest.status === 200)
      {
        //alert(httpRequest.responseText);

        var response = "Some default message";
        try
        {
            response = JSON.parse(httpRequest.responseText);
        }
        catch(e)
        {
            console.log(e.message + " in " + httpRequest.responseText);
            return;
        }
        alert(response.computedString);
      }
      else
      {
        alert('There was a problem with the request.');
      }
    }
  }
Comments