Running Javascript function from another domain [duplicate] - javascript

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Closed 4 years ago.
To start off JS is NOT my strong suite. What I am trying to do is run some code between 2 sites. So for example we have site A, and site B.
Site B contains a file called auth.js which the content is below.
function test() {
alert("bingo");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// document.getElementById("demo").innerHTML = this.responseText;
alert( this.responseText );
}
};
xhttp.open("POST", "https://siteb.com/auth.php", true);
xhttp.send();
};
Now inside site A I am including auth.js and running the function test()
As of now I am getting the alert message fine, however I'm receiving a console message about CORS (which i googled a bit and it doesn't make sense to me).
All of the code is living on site B. I'm wanting to run a php script when this js file is called, then output the data back as javascript on site A. So my php script will do all of the authentication and structure new js code and echo it out.
What am I missing to make CORS work properly?
Thanks in advance.

ok so finally got some code to work for me. Heres what I did.
inside auth.php on Site B I've added the following lines of code.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
Right now this is allowing all traffic to come through. If you want to restrict it to a specific domain, then swith the * to http://example.com
and also modified the file auth.js on Site B
function test() {
alert("bingo");
$.ajax({
type: 'POST',
url: 'https://siteb.com/auth.php',
crossDomain: true,
data: {},
async: false,
success: function(response) {
alert(response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
}
});
};
so now on site A. I'm calling only test();
hope this helps someone else

Make a PHP file which will send the request in PHP CURL, gets the response and sends that response to the browser. Instead of sending a request from Javascript to the final target, send this to your own server and make sure your PHP is being executed. This should resolve the CORS issue. Other potential problems will be that you will have to make sure that the script, link, a, img tags have proper path.

Related

HTML/Javascript- get data from raw pastebin

I have a webpage in which I need to just get the raw data of a specified pastebin file, let's just say http://pastebin.com/qnNPx6G9, and store it as a variable. I've tried many, many, many variations on xml and ajax requests, but nothing works. Here's what I've tried. What am I doing wrong?
I've tried with Ajax:
$.ajax({
url: "http://pastebin.com/api/api_post.php",
type: "GET",
dataType: "x-www-form-urlencoded",
data: {
"api_dev_key": "mydevkey",
"api_option": "paste",
"api_paste_code": "blah blah"
},
success: function(res) {
alert(JSON.stringify(res));
},
error: function(res) {
alert(JSON.stringify(res));
}
});
//this is in the form of create paste, because I was seeing if it would work where get did not- it didn't.
And with regular XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('POST'/*also tried GET*/, 'http://pastebin.com/raw/qnNPx6G9', true); //I've also tried /raw.php?i=qnNPx6G9
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(this.responseText);
}
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send("api_option=trends&api_dev_key=DEVKEY");
//I tried trends because creating a paste and getting a paste didn't work.
Please help! I'm sorry if this is a stupid question or anything is unclear, I'm not that good at understanding APIs. Thanks!
And no, I can't use PHP.
You are trying to make a CORS request that pastebin obviously doesn't allow as console shows up this error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
I think your only option is to use a server-side programming language in order to access pastebin remotely, CORS requests are only allowed just in the case the where remote server authorised it, else you have no way to bypass it.
Read more about CORS here

XMLHttpRequest receiving undefined

I'm making a widget on iphone but I can't get data from the url.
On IE, I can get data. However, on chrome and on iphone I can't get the data but it only shows undefined instead of data.
function a() {
var url="www.xxx.xxx";
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
xmlDoc = request.responseXML;
}
please help me!! I'm really appreciated for any answers.
Create a function something like below,to receive the data from server.
request.onreadystatechange = function(){
if(request.readyState == 4){
console.log(request.responseText);
}
}
Please make sure that you are making request from the same Origin. That means if you are in site www.abc.com then you can make request for www.abc.com/download/ or www.abc.com/site and so on. But if you request for www.gdb.com then it will probably fail with this error in your console "No 'Access-Control-Allow-Origin' header is present on the requested resource." The browser prevents this activity for security reasons. It needs to be on the same domain.
Try using JQuery sometimes. It's API is very easy to use and is very helpful for doing tasks. You will need to add the script to the page first like this:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
You can download the script or use the live version and link to it like above.
Next you can make a call like this to make a GET request. Observer that it returns data when successful. This makes your job easy but remember you need to make call from same domain.
$.ajax({
type: "GET",
url: "http://wwww.something.com"
})
.done(function( data ) {
alert(data);
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
To know more about Cross Site HTTP Requests: CORS
Here is a thread that may help you to understand better: “No 'Access-Control-Allow-Origin'
would setting the responseType work?
call the request.responseType = 'document'; before send.

Cross Domain XML to Javascript from PHP

I want to send XML data from php(domain A) to a remote javascript file(domain B).
I can't have them on the same domain, and I can't have any other files on on domain B.
I've read about sending a JSONP object from php instead of XML, but as I understood from a tutorial, I would need a php proxy on the same domain as where the javascript file is located. tutorial link
(xhr.open("GET", "xmlproxy.php?url=" + escape(url), true); <= this line kinda tells me, that the xmlproxy.php has to be on the same domain as the actuala javascript)
Any suggestions, on how could I do this?
LATER EDIT AFTER ThW's answer
Now I have the following sample code :
The testlog.php file
<?php header('Access-Control-Allow-Origin: *');
print "<Logs><Log><id>Test Log</id></Log></Logs>";
?>
The javascript function that is called on page load:
function getTestLog() {
alert("Gets here!");
$.ajax({
url: "anotherdomain/testlog.php",
data: requestVars,
dataType: 'xml',
success: function(xml){
alert(xml);
},
error: function (xhr, err) {
alert("Error: " + xhr.readyState + "\nstatus: " + xhr.status + "\nerror:" + err);
alert("responseText: " + xhr.responseText);
}
});
}
The problem is, that it's not getting into the ajax thing
If you control the PHP that outputs the XML you can use CORS.
By default Javascript can only open resources from the domain it was loaded. Other resources have to allow that they can be loaded by a Javascript on a different domain.
To do that add a header to the PHP-Script:
header('Access-Control-Allow-Origin: http://javascript-domain.tld');
Or to allow the loading of the XML from anywhere:
header('Access-Control-Allow-Origin: *');
You're using jQuery and here might be a problem if you're not sending the correct content type from PHP.
header('Content-Type: application/xml');
To validate that it is the Cross Domain that it is blocking the reading open you Javascript console in the browser. It should output an error message. In Firefox it is something like:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://domain.tld/path/to/resource. This can be fixed by
moving the resource to the same domain or enabling CORS
If you get the request, it should show up in the Network-Tab of your developer tools and you can validate the HTTP response headers.
Here is simple JS snippet using XHR, it forces the content type.:
var xhr = new XMLHttpRequest;
xhr.overrideMimeType("application/xml");
xhr.addEventListener(
'load',
function (xhr) {
return function () {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr.responseXML);
}
}
}(xhr)
);
xhr.open('GET', 'http://php-domain.tld/script.php');
xhr.setRequestHeader("Accept", "application/xml");
xhr.send();

Get json ajax php form to work remotely

So, essentially I have this Javascript which interprets the JSON from my php code. It works great on the local server, however, when I try to move the script to a different server it will not work. I have added the
<?php header("Access-Control-Allow-Origin: *"); ?>
also i've declared my database connection as global within my PHP function.
I'm confused as to why these solutions aren't working.. Also, I understand some of the script is iffy, but I'm only interested in figuring out why its not working from different servers.
<script type="text/javascript">
$("document").ready(function(){
$(".sendText").submit(function(){
$("#sendButton").prop("disabled",true);
$(".errors").html("");
$(".success").html("");
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "jsonp", //new edit
url: "http://myurl.com/testing/jsonpost.php?callback=test", //new edit
data: data,
success: function(data) {
if(data["success"]=="yes") {
$(".success").html("Message Sent!");
$(".formContainer").html("" + data["json"] + "");
}
else {
if(document.getElementById("sendButton").disabled = true){ document.getElementById("sendButton").disabled = false; }
$(".errors").html("" + data["errors"] + "");
}
}
});
return false;
});
});
</script>
Some Info when I look at the web console from firebug:
Access-Control-Allow-Orig... *
Connection Keep-Alive
Content-Length 0
Content-Type application/json
Date Wed, 24 Sep 2014 04:22:57 GMT
Keep-Alive timeout=5, max=100
Server Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips DAV/2 mod_bwlimited/1.4
X-Powered-By PHP/5.4.29
Looks like it is communicating with server but not able to interpret data? thoughts?
Also, this error comes up in the console from the remote server but not when I run on local server:
SyntaxError {stack: (...), message: "Unexpected end of input"}message: "Unexpected end of input"stack: (...)
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…
parsererror
The PHP code is pretty long (and I prefer not to release all of it) - however here is the shortened version:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
require "../database/db.php";
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$c="1";
global $con;
$return = $_POST; //to reference post
$content=$return["content"];
//see if content is 140 characters or less
if(strlen($content)>140){ $c="0"; $lerror="<li>Your message must be 140 characters or less in length!</li>"; }
if($c=="0"){ //doesnt pass validation
$return["success"]="no";
$return["errors"]="$lerror";
}
if($c!="0"){ //passes validation
$return["success"]="yes";
}
if(isset($_GET['callback'])){ //jsonp edit
$return["json"] = json_encode($return);
echo $_GET['callback']."(".json_encode($return).")"; //jsonp edit
}
}
Also after converting to JSONP on remote server - get error -
"jQuery111006159528985153884_1411663761720 was not called"
When dealing with jQuery AJAX using a data type of JSON, any notice, warning or error produced by the server side script will cause issues. The reason being is the outputted PHP errors break the JSON encoding that jQuery is expecting.
I suspect the two environments are not identical, perhaps a different PHP version, missing PHP extension or different settings in the php.ini file.
The best thing to do is to use the provided jQuery AJAX error callback to console log any errors allowing you to essentially troubleshoot any issues being thrown by the server side script.
!!! EDIT 3 !!!
Client Code
$.ajax({
type: "POST",
dataType: "json",
url: "http://myurl.com/jsonpost.php",
data: data,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
Server Side Code
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
echo json_encode(array('success' => 'yes'));
Using this bare bones version of your code I can successfully make a cross domain request and console log the response. If you implement this code and it still does not work there is something else at play at the server and/or network level.
You can make AJAX calls to a backend API, it needs to return JSONP format and not just JSON, otherwise you can get error. This is due to same origin policy:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy.
This discussion may be helpful to understand JSONP:
Can anyone explain what JSONP is, in layman terms?
However, one alternative is disable the security of Google Chrome browser, then it will work. But this is not a solution. It is better to use JSonP format.

Cross-origin request blocked when using AJAX

Hey I just installed script on same host, twice, just different accounts.
The scripts worked fine, but for random reason, one of them started to drop all AJAX requests, and print the following messsage in Mozilla:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.yoursite.com/vote/ajax/xmlhttp/claim. This can be fixed by moving the resource to the same domain or enabling CORS.
When I access the link directly, works fine, but with AJAX it just fails.. on the other account (host account) it works fine so far.
On my VPS and pc it works fine.
In PHP error log, it prints undefined variables, which is not really possible, how can AJAX affect this, especially in this random situation, where it works and sometimes now on this host.
My JS:
var reward = $("#rewards ul li");
var selected = [];
var limit = <?php echo $limit; ?>;
var errors = $(".error");
var timeout;
console.log(limit);
$("#claim").click(function() {
$("#claim").text('Checking...');
if ($("#username").val() == "") {
$("#claim").text('Claim my reward(s) now');
showError("Fill in your in-game username.");
return;
}
if (selected.length == limit) {
$.ajax({
type: "POST",
url: "<?php echo $post_url; ?>",
data: {username: $("#username").val(), rewards: JSON.stringify(selected)},
success: function(data) {
$("#claim").text('Claim my reward(s) now');
if (data.substr(0, 6) == 'error:') {
showError(data.substr(6));
}
else {
$("#claim").text('Success!');
$(".section").html(data);
}
}
});
}
else {
showError("You must select " + limit + " rewards(s) to continue.");
}
});
Let me know if you need the functions I used too.
What is causing this problem?
I tried adding the following response:
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
But it's bad because it will still have undefined variables in it, and still process the response which will cause JavaScript syntax errors.
Thanks in advice.
if i understood you right you are trying to pass data between to different servers;
the answer to this is JSONP, it works like JSON but should pass that CORS problem.
to do so you need to change a little bit your php code and ajax code.
in php you need to wrap the JSON data in a callback and in AJAX you need to define - dataType: "jsonp", read more about jsonp here: What is JSONP all about?.
it worked for me!

Categories

Resources