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);
?>
<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>
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.');
}
}
}
console.log(response);
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['computedString' => $computedString];
echo json_encode($array);
$array = ['userData' => $name, 'computedString' => $computedString];
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.');
}
}
}