This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 9 years ago.
I am trying to fetch a data file from a URL given by the user, but I don't know how to do. Actually, I can get data from my server successfully. Here is my code:
$("button#btn-demo").click(function() {
$.get('/file', {
'filename' : 'vase.rti',
},
function(json) {
var data = window.atob(json);
// load HSH raw file
floatPixels = loadHSH(data);
render();
});
});
It can fetch the binary data from my server, parse the file and render it into an image. But now I want it work without any server, which means users can give a URL and javascript can get the file and render it. I know it's about the cross-site request. Can you tell me about it and how to realize it?
Thanks in advance!
assuming your URL is the address of a valid XML document this example will go grab it. if the URL is on a different domain than the one that's holding your scripts you will need to use a server side scripting language to got out and grab the resource (XML doc at URL value) and return it your domain. in PHP it would be ...
<?php echo file_get_contents( $_GET['u'] );
where $_GET['u'] is a URL value from your USER. let's call our PHP script proxy.php. now our JavaScript will call our proxy.php and concatenate the URL value to the end which will allow us to pass the URL value to the PHP script.
addy = $("#idOfInputFieldhere").val();
$.ajax({
url: 'proxy.php?u='+addy, /* we pass the user input url value here */
dataType:'xml',
async:false,
success:function(data){
console.log(data); /* returns the data in the XML to the browser console */
}
});
you'll need to use the js debugger console in chrome to view data. at this point you'd want to pull out data in a loop and use find() http://api.jquery.com/?s=find%28%29
I'm not very familiar with jQuery, but as I know, due to the same origin policy, the browser won't let any JavaScript code to make an AJAX request to a domain other than its own. So in order to retrieve some data (specially JSON formatted), you can add a <script> element to your page dynamically and set its src property to the address of the data provider. Something like this:
<script src='otherdomain.com/give_me_data.json'/>
This only works if you need to access some static data (like the url above) or you have access to the server side code. Because in this scenario, the server side code should return an string like:
callbackFunction({data1: 'value1', data2: 'value2', ...});
As the browser fetches the item specified in src property, tries to run it (because it know it's a script). So if the server sends a function call as a response, the function would be called immediately after all data has been fetched.
You can implement the server side in such a way that it accepts the name of the callback function as a parameter, loads requested data and generates an appropriate output that consists of a function call with loaded data as a json parameter.
Related
I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'
I am aware of how REST calls work from within a Java Web application. E.g. when a URL is reached its method will be called using HTTP.
For example:
#GET
#Path("people/{id}")
public Response getPersonWithId(#PathParam("id") id) {
//return the person object with that Id
}
What I am unsure of is how this links to the front end?
Is the role of the UI ( i.e. javascript ) just to take a user to the specific URLs so that the back end methods can be called?
E.g. if a user presses a "get details" button, does the button just redirect them to this URL that deails with returning the details, and the back end functionality is then called?
WebService is not actually linked or tied to the front end similar to webapp. Instead, webservice is a service that provides result in the form of JSON/XML, Plain text Format according to request type(get, post, update, delete) and hence, the service can be used by any multiple front end application(not only web application but also smartphone app, desktop app etc.). Also, webservice can be on totally different server.
Let me give you a scenario:
Suppose, you have an front end web site ABC-Website and a backend
webservice on host: www.xyzservice.com/api with following methods:
/product - get request that return all product as list in json format.
/product/id - get request return product detail given id in json
format.
Now, if you simply type in browser www.xyzservice.com/api/product then
all product list will displayed in json format in the browser. That means, You can also read data from webservice directly in browser without front end system and i.e. webservice is not linked/tied to any front end.
Now, you want to use this webservice in your ABC-Website to display all the product list:
You call www.xyzservice.com/api/products and get JSON object that you can use to display in your html page.
<button type="button" onclick="getProducts()">Click Me!</button>
function getProducts(){
$.ajax({
type : "GET",
contentType : "application/json",
url : "http://www.xyzservice.com/api/product",
dataType : 'json',
timeout : 100000,
success : function(data) {
// now you have "data" which is in json format-same data that is displayed on browser.
displayDate(date);
},
error : function(e) {
//do something
},
done : function(e) {
//do something
}
});
}
function displayDate(){
//your codes to parse and display json data in html table in your page.
}
Lets say that your client is a website and you have a Java API.
In the javascript of your website you could do a request to the backend to retrieve the data and then present it to the user. Your javascript (using jQuery as an example) could look like the following:
// here it prints the data retrieved from the backend route (/people/{id}
$.get('http://localhost:3000/people/3',function onDataReceived(data) {
console.log(data);
})
As pointed out, jQuery is not necessary. Here is an example using regular javascript:
this.getRequest('http://localhost:3000/people/3', function onReceived(data) {
});
function getRequest(url, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
in javascript, usually you want to do these request at the background your webpage.
Im gonna try to explain this with an example:
Imagine you have a page that displays a list of cars for sell which can be fetched from the web service provided by java back-end. The back-end have an url that will respond to GET method with a JSON (or XML) object.
What you have is a HTML file where you write a structure for the displayed data and also includes a javascript file that asynchronously calls this webservice, GETs the data, parses the JSON and then it can manipulate it to the form you want to display it on the page.
In different example you can validate forms on the background, or save the forms or do any other stuff that works with the web service API.
For making these asynchronous request you can use different libraries.
Most used is ajax included in jQuery framework or fetch as n standalone library.
Before I get to the question, let me explain how we have things set up.
We have a proxy.php file, in which class Proxy is defined with functions that call upon a rest for creating/editing/getting Wordpress posts, fields etc.
Then, we have a proxyhandler.php, in which Proxy class is initialized and serves as a handle between proxy.php and a javascript file.
In javascript file we have an ajax call to proxyhandler.php in which we send our secret and other data.
Now, the problem arises here:
We define the secret through wp_localize_script, by using md5 custom string + timestamp. We send the encripted string and timestamp through ajax to proxy handler, where we use the previous (hardcoded inside proxyhandler) string and timestamp to generate a md5 string again, and check the one sent against the one generated. If they are the same, we continue by doing whatever was requested, if they dont fit, we just return that the secret didn't match.
Now, the real issue comes here - by using wp_localize_script, the variable for the secret is global and as such, anyone can utilize it via dev tools and can send any ajax request to proxyhandler that they want.
What would be the proper procedure to make it more secure? We've thought of doing this:
Instead of using wp_localize_script, we put the script inside a php file, we define the secret using a php variable and then simply echo the secret file into ajax. Would this be viable, or are there any other ways?
Instead of sending an encrypted string in global scope, then check against it, you should use nonce in your AJAX request:
var data = {
action: 'your_action',
whatever_data: who_know,
_ajax_nonce: <?= wp_create_nonce('your_ajax_nonce') ?>
};
Then, use check_ajax_refer() to verify that nonce:
function your_callback_function()
{
// Make sure to verify nonce
check_ajax_refer('your_ajax_nonce');
// If logged in user, make sure to check capabilities.
if ( current_user_can($capability) ) {
// Process data.
} else {
// Do something else.
}
...
}
Depend on the AJAX METHOD, you can use $_METHOD['whatever_data'] to retrieve who_know data without needing to use wp_localize_script().
Also remember that we can allow only logged in users process AJAX data:
// For logged in users
add_action('wp_ajax_your_action', 'your_callback_function');
// Remove for none logged in users
// add_action('wp_ajax_nopriv_your_action', 'your_callback_function');
The final thing is to make sure NONCE_KEY and NONCE_SALT in your wp-config.php are secure.
How do I extract the data below. I only want to print out the value number after "networkdiff" in this API.
This is the URL for the API from a different website:
http://21.luckyminers.com/index.php?page=api&action=getpoolstatus&api_key=8dba7050f9fea1e6a554bbcf4c3de5096795b253b45525c53562b72938771c41
I want the code to automatically retrieve the data from the URL above, and display the value after "networkdiff" to display on my other webpage.
Here's my code so far that I will put in my own webpage:
<HTML>
<body>
<script>
I don't know what I should put in this script part.
</script>
</body>
</html>
Below is the data the URL showed up as:
{
"getpoolstatus":{
"version":"1.0.0",
"runtime":10.684967041016,
"data":{
"pool_name":"21 Coin Pool # Luckyminers.com",
"hashrate":0,
"efficiency":97.79,
"workers":0,
"currentnetworkblock":0,
"nextnetworkblock":1,
"lastblock":40544,
"networkdiff":1,
"esttime":0,
"estshares":4096,
"timesincelast":1240429,
"nethashrate":0
}
}
}
Since the data is coming from an external domain, you can't use Ajax to get the data, unless the server enabled CORS. This doesn't seem to be the case, but it seems to support JSONP:
<script>
function processResponse(data) {
console.log(data);
}
</script>
<script src="http://21.luckyminers.com/index.php?page=api&...&callback=processResponse></script>
The callback=parseResponse makes the server return JS consisting of a function call to processResponse. How to access the information you actually want is explained in Access / process (nested) objects, arrays or JSON.
You need to include JSON.js in your web page to use JSON function in javascript. Here is the URL for download
https://github.com/douglascrockford/JSON-js
And then you can use beloe code to parse the JOSN string into javascript object.
var objectJSON = JSON.parse(jsonStr);
You can alse used stringify fucntion to the viceversa.
In which way you call the JSON?
You can call it with a callback function (working example), including it as a script:
updateResult=function()
{
var s=document.createElement('script');
s.src=domain+"/index.php?page=api&callback=showResult&action=getpoolstatus&api_key="+api_key;
document.body.appendChild(s);
}
You must have the callback defined like:
showResult=function(data)
{
document.getElementById('result').innerText=data.getpoolstatus.data.networkdiff;
}
If you call it with JQuery and get the JSON object, you can define the callback in the argument like the following example, but you must have same-origin (your script must run with the same domain (21.luckyminers.com in this case):
$.getJSON(
domain+"/index.php?page=api&action=getpoolstatus&api_key="+api_key,
function(data)
{
document.getElementById('result').innerText=data.getpoolstatus.data.networkdiff;
}
);
But in any case, be careful. Where did you get the API key? If you put it on a client-side script (like JavaScript) anybody can read the key, and with that key maybe do some damageā¦ :S
I'm new to JSON/AJAX and
I've some problems with displaying data out of a JSON-object I've got from a server..
The url "http://localhost:8387/rest/resourcestatus.json" represents this object, which I would like to display via HTML/Javascript.. This object stores some monitoring information:
{"groupStatus":[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]}
Since the requested url is different from my domain I can't create a typical XMLHttpRequest.. So I found out that there's an AJAX cross-domain request which can be realised via jQuerys "getJSON()" method.
I want to display the ids and their level in a table.
Any solution to achieve this?
i think you are referring to JSONP. see jQuery.ajax Ex:
var url = 'http://localhost:8387/rest/resourcestatus.json';
$.getJSON(url+'?callback=?', function(data)
{
//data is
/*{
"groupStatus":
[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]
}*/
});
on the server side you will need to wrap the response into a JavaScript function: response = Request["callback"] +"("+ response+")";
the result will look like this:
?({"groupStatus":[{"id":"AL ....})
So the browser will actually load a valid java script code.
The callback function of $.getJSON contains the result of the AJAX call in it's argument.
$.getJSON('http://localhost:8387/rest/resourcestatus.json', function(data) {
$(data.groupStatus).each(function() {
// do something with $(this).id
});
});