Created
January 21, 2016 08:28
-
-
Save pcoder/ddbae93693a4afe710c4 to your computer and use it in GitHub Desktop.
A simple php js ajax interaction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// the server script to go on to the PHP server | |
// header to allow CORS | |
header("Access-Control-Allow-Origin: *"); | |
// declare the stub function to handle the GET request | |
function stub_function($val){ | |
// we can use the $val which is the GET parameter here | |
echo "Hello!"; | |
} | |
if(isset($_GET['value'])){ | |
// pass the get parameter to the stub_function | |
stub_function($_GET['value']); | |
} | |
?> | |
// The client side JS code to call the above PHP script | |
var xhr = new XMLHttpRequest(); | |
// server url with the GET parameter | |
var server_url = 'http://myserver.com/server.php?value=test'; | |
xhr.open('GET', server_url); | |
xhr.send(null); | |
// I assume a simple call_back function that prints the response code | |
function callback(response_code){ | |
console.log("The response is " + response_code); | |
} | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState === 4) { | |
// handle 200, 400 and 500 responses | |
if (xhr.status === 200) | |
callback(xhr.responseText); | |
} else if (xhr.status === 400){ | |
callback('Error: ' + xhr.status); | |
} else if (xhr.status === 500){ | |
callback('Error: ' + xhr.status); | |
} else { | |
callback('Error: Other than 400 or 500 error. ' + xhr.status); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment