1

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

5
  • The undefined sounds like a JS issue. Can you post the JS? Commented Jul 21, 2016 at 3:34
  • Look at jQuery's website. Lots of examples there. :-) Commented Jul 21, 2016 at 3:35
  • Learning by Debugging. Request the php file with your browser and see what happens. Try different inputs and compare the outputs to your expected results. Commented Jul 21, 2016 at 3:36
  • @Jonas w: When the PHP script is requested with the browser this is displayed on the screen: "Hi, no name". Commented Jul 21, 2016 at 3:41
  • The fact that the PHP script gives an acceptable result when called in the browser supports @chris85's suggestion that it's a JS issue. But what is the issue?? Commented Jul 21, 2016 at 3:43

1 Answer 1

1

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.');
      }
    }
  }
Sign up to request clarification or add additional context in comments.

7 Comments

I made this change to the code but still get the same "undefined" message box.
use console.log(response) and let me know what does it show in the console area.
And are you getting the httpRequest.responseText as expected ? use console.log(httpRequest.responseText) as well.
Where should that line go in the code? Sorry, I'm a newbie at JS/Ajax.
When alert(httpRequest.responseText); is uncommented the code works properly - a message box pops up that says "Hi, Joe" when Joe is entered in the text box.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.