AJAX CORS call not working on PHP - php

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();
?>

Related

script within a php page not executed when called using ajax

Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}

How to receive jQuery post response before completing execution of PHP script?

I have a simple jquery function that sends a post request to a PHP file like this:
$.post('/file.php',
{
action: 'send'
},
function(data, textStatus)
{
alert(data);
});
And a PHP file:
<?php
/* Some SQL queries here */
echo 'action done';
/* echo response back to jquery and continue other actions here */
?>
jQuery by default waits till executing the whole PHP script before giving the alert. Is there a way to alert the action done before executing the rest of the PHP file??
Thanks
It is possible with plain Javascript ajax. The onreadystatechange event will fire with a readyState of 3, when data is received before the request is complete.
In the example below, newData will contain the new piece of data. We have to do some processing because the XHR actually gives us the entire data so far in responseText and so if we only want to know the new data, we have to keep a record of the last index.
var httpRequest, lastIndex = 0;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState === 3) {
var newData = httpRequest.responseText.substring(lastIndex);
lastIndex = httpRequest.responseText.length;
console.log(newData);
}
};
httpRequest.open('POST', '/file.php');
httpRequest.send('action=send');
As for jQuery ajax, this answer suggests jQuery lets you bind to the readystatechange but I haven't tested it.

Javascript-Ajax not able to send any data

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'];
}

Ajax http.responseText URL vs text

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>

Panoramio API access using AJAX - error "Origin hxxp://foo.bar is not allowed by Access-Control-Allow-Origin."

I am currently experiencing this issue, and am wondering why...?
The error message is:
"XMLHttpRequest cannot load http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=?.
Origin hxxp://foo.bar is not allowed by Access-Control-Allow-Origin.
test_panoramio.html:59Uncaught SyntaxError: Unexpected token )"
"hxxp://foo.bar" refers to the site I am running the script from.
The "test_panoramio.html" on the site contains e.g. the following :
var url = "http://www.panoramio.com/wapi/data/get_photos?
v=1&key=dummykey&tag=test&offset=0&length=20&minx=-
30&miny=0&maxx=0&maxy=150&callback=?";
function myScriptFn()
{
if (window.XMLHttpRequest) {
myAjax = new XMLHttpRequest();
if ( typeof myAjax.overrideMimeType != 'undefined') {
myAjax.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
myAjax = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('The browser does not support the AJAX XMLHttpRequest!!!');
}
myAjax.onreadystatechange = function()
{
handleResponse();
}
myAjax.open('GET', url, true);
myAjax.send(null);
}
function handleResponse()
{
if (myAjax.readyState == 4){ // Response is COMPLETE
if ((myAjax.status == 200) || (myAjax.status = 304))
{
// do something with the responseText or responseXML
processResults();
}else{
alert("[handleResponse]: An error has occurred.");
}
}
}
function processResults()
{
myObj = eval( '(' + myAjax.responseText + ')' );
...
doSomething()
...
}
The Panoramio URL works if typed directly to the browser.
Please could you help me with this, I am running out of hope...:(
Thank you in advance,
Yours
Marko
What you're hitting is the same origin policy which prevents cross-domain requests via XMLHttpRequest. There is a work-around if the site support is (and the one you're trying to access doed!), JSONP. This means all you need is a <script> tag with that callback parameter populated, like this:
<script type="text/javascript" src="http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=myFunction"></script>
And a function with the same name:
function myFunction(data) {
//data is what came back, it's a javascript object
}
You can test out a working example here.

Categories