I have an HTML document, which loads content from a PHP file using an AJAX call. The important bit of my code is below:
default.html :
/*more code above*/
var PHP_URL = "content.php";
var Content = document.getElementById('Content');
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange =
function() {
if(ajaxRequest.readyState==4) {
if (ajaxRequest.status==200)
Content.innerHTML = ajaxRequest.responseText;
else
Content.innerHTML = "Error:<br/>unable to load page at <b>"+PHP_URL+"</b>";
Content.className = "Content Solid";
}
}
ajaxRequest.open("GET",PHP_URL,true);
ajaxRequest.send();
/*more code below*/
Is it possible for the file at 'content.php' to detect that it has been called from 'default.html', or a different calling document as necessary?
Most well-known Ajax frameworks like jQuery and mooTools add a specific header which you can check with PHP:
if (strcasecmp('XMLHttpRequest', $_SERVER['HTTP_X_REQUESTED_WITH']) === 0)
{
// Ajax Request
}
I guess the best would be to set a request header in your AJAX call, such as
st.setRequestHeader('X-Sent-From','default.html')
then in content.php,
$sentFrom=$_SERVER['HTTP_X_SENT_FROM']; // outputs default.html
$_SERVER['HTTP_REFERER'] might be what you want
Reference
http://php.net/manual/en/reserved.variables.server.php
It is not possible to simply detect that a request came from an AJAX call on the server. You could, however, add a parameter that you send when requesting it via AJAX that indicates it is coming from an ajax call.
For example:
/*more code above*/
var PHP_URL = "content.php?mode=AJAX";
var Content = document.getElementById('Content');
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange =
function() {
if(ajaxRequest.readyState==4) {
if (ajaxRequest.status==200)
Content.innerHTML = ajaxRequest.responseText;
else
Content.innerHTML = "Error:<br/>unable to load page at <b>"+PHP_URL+"</b>";
Content.className = "Content Solid";
}
}
ajaxRequest.open("GET",PHP_URL,true);
ajaxRequest.send();
/*more code below*/
If simply detecting that the call came from default.html is enough (and not distinguishing between an AJAX call or a clicked link), then checking the Referrer header will do the trick, as suggested by #Jamie Wong.
Related
I am trying to make a call to our API server from a simple java-script function. Below is the code that I use:
function jack() {
//fullURL defined here
debugger;
var xhr = new XMLHttpRequest();
var onLoadHandler = function(event) {
/* do something with the response */
debugger;
}
var onErrorHandler = function(event) {
/* do something with the response */
debugger;
}
xhr.open('GET',fullURL);
xhr.onload = onLoadHandler;
xhr.onerror = onErrorHandler;
xhr.send();
}
I could not load the complete fullURL because the page said: "Your post contains the invalid external" so I can confirm it starts with http and goes to /api/phpInfo.php
I open a browser to this page and start Firebug. In the Firebug console I make a call to jack() and end up in var onErrorHandler = function(event). Firebug is telling me that event is "error" but I need to know what error? If I go to my PHP server I can see in the log that the call was made and a server 200 code was returned? Firebug also shows that the "HTML" tab returned blank but a call to fullURL does return the info page to me (in a browser)
Help please.
This worked for me!!!
Javascript:
var httpReq = getXMLHTTPRequest();
function makeCall() { var myurl =
"http://111.111.111.111:11111/api/phpInfo.php"; myRand =
parseInt(Math.random()*999999999999999); var modurl =
myurl+"?rand="+myRand; httpReq.open("GET", modurl, true);
httpReq.onreadystatechange = useHttpResponse899; httpReq.send(); }
function useHttpResponse899() { if (httpReq.readyState == 4) {
if(httpReq.status == 200) { // do all processings with the
obtained values / response here } } }
and on the PHP server in phpInfo I had:
<?php
header('Access-Control-Allow-Origin: *');
phpinfo();
?>
i am having trouble making this part of code to work, basically i want to call this function which sends a variable to a php page. Ive tested that the variable is there and also tested that my php page is accepting information as it should be , however i cant make this Ajax thing work.
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else
{ // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name=myname';
AJAX.open("POST", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
This is my php part which should accept the variable
<?php
$var=$_GET['Name'];
echo $var;
?>
Okay firstly you need to change your request to GET from POST
like
AJAX.open("GET", url, true); // Open the url this object was set-up with.
and you also need to update this line
from
var url='http://localhost/main.php?Name=myname';
to
var url='http://localhost/main.php?Name='+myname;
my full script is:
<script type="text/javascript">
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name='+myname;
AJAX.open("GET", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
</script>
you might also be missing the callback function so add it so that it looks like this
function callback(x, y) {
alert(x);
}
And call your AJAX function by
ajaxRequest("ashley");
Here is your required main.php code (even though this isn't what you should be using AJAX for
<?php
session_start();
if(isset($_GET["Name"])) {
$_SESSION["Name"] = $_GET["Name"];
}
if(isset($_SESSION["Name"])) {
echo $_SESSION["Name"];
} else {
echo "The AJAX has not been run!";
}
?>
There are two ways to send an ajax request to server
Either GET or POST
1. GET Method:
var url='http://localhost/main.php?Name='+myname; // you can add any numner of vars here
AJAX.open("GET", url, true);
AJAX.send();
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_GET['Name'];
}
2. POST Method:
AJAX.open("POST","ajax_test.asp",true);
AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
AJAX.send("Name="+myname);
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_POST['Name'];
}
Is it possible to choose what response to get back from a PHP script called with ajax. It is possible to say that instead of getting back what the script writes that I want the entire script to be treated as a URL and have that as the response?
I am calling a PHP script like this.
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function LoadCalendar() {
http.abort();
http.open("GET", "luxcal/index.php?cP=2", true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
/* document.getElementById('litcal').src = http.responseText; */
document.getElementById('litcal').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
Loading the PHP script response in a div innerHTML works. I would rather load the response in an iframe. Does the http object have an option to get the URL response, e.g. http.responseURL? I could then do document.getElementById('litcal').src = http.responseURL. Thanks.
if you want to load response in an iframe, just do it in HTML without using AJAX
HTML
<iframe id="litcal"></iframe>
Javascript
<script type="text/javascript">
document.getElementById('litcal').src = 'luxcal/index.php?cP=2';
</script>
I have the following code generating content on my site:
<div class="content" id="links">
<?php displayTitle("Links"); ?>
<?php displayContent("Links", $isLoggedIn); ?>
</div>
The content has a button that calls a Javascript function 'addLink()' to edit itself. Here is the Javascript with an Ajax call to change the content:
function addLink(){
var ajaxRequest; // The variable that makes Ajax possible!
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send(null);
}
'addLink.php' adds things to a table, theoretically allowing the content function 'displayContent()' to show the new entries in the table ('displayContent()' queries a table).
The PHP call works fine, but I have to refresh the page to see the changes.
Is there some problem with how I am doing this? Possibly because there are already PHP calls in the inner HTML when the page is loaded in the first place?
Any help is appreciated, I'm a bit of a beginner with Ajax.
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
Sorry a little correction. You are attempting to access the pre-ajax php scripts inside ajax callback function. That's not how it works. You want the data that is retrived after-ajax call. Ajax retrives the output from the GET request, and store in ajaxRequest.responseText. Try replacing that and then see what you get.
In your addLink.php you should add the link and then echo out the data that you wish to display as the responseText. What had happened is that you inject the data VIA addLink but you never actually display it on the client side VIA ajax correctly. However, when you refresh the page, the script retrives what has been injected and display it accordingly.
In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.
Is there any way to check the database for value without refreshing the page?
It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.
You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.
While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.
EDIT - Here is my illustration - this uses Prototype's Form.serialize function.
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.
Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.
Its a pain, but that's how HTTP works.