Struggling to communicate with the utorrent web API - javascript

I am trying to access utorrents web api, it uses a token authentication system which is detailed here
the JavaScript on my page is
<script>
$.getJSON("http://XXX.XXX.XXX.XXX/lib/token.php", function(response) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
//script.onreadystatechange = function () {
// if (this.readyState == 'complete') utorrent();
//}
//script.onload = utorrent();
script.src = 'http://XXX.XXX.XXX.XXX:8080/gui/?list=1&token=' + response.token;
head.appendChild(script);
});
</script>
simply retrieving the token from a php file and passing it along the chain, i have confirmed that the token is being passed and is not being poisonned, my PHP document is below
<?php
header('Content-type: text/json');
$token = file_get_contents('http://[username]:[password]#XXX.XXX.XXX.XXX:8080/gui/token.html');
$token = str_replace("<html><div id='token' style='display:none;'>", "", $token);
$token = str_replace("</div></html>", "", $token);
$response = array('token' => $token);
echo json_encode($response);
?>
this gives me a confirmation of the token
Object {token: "GMt3ryaJE64YpXGN75-RhSJg-4gOW8n8XfTGYk_ajpjNLNLisR3NSc8tn1EAAAAA"}
but then i receive a 400 error code when retrieving the list
GET http://XXX.XXX.XXX.XXX:8080/gui/?list=1&token=GMt3ryaJE64YpXGN75-RhSJg-4gOW8n8XfTGYk_ajpjNLNLisR3NSc8tn1EAAAAA 400 (ERROR)
Any help/thoughts/idea's would be greatly appreciated

just adding my 2 cents.
I've been doing a similar implementation in .NET MVC - I was able to get the token as you did, but the list=1 feature didn't work for me either, getting the 400 bad request code (as you have found).
The solution for me:
In the token.html response, there is a token in the div and also a GUID in the header.
To break it down:
Call token.html with uTorrent credentials
In the response content, parse the html to get the token
in the response header, there is a value with key Set-Cookie, which looks like
Set-Cookie: GUID=<guid value>
I needed to use this value (GUID=<guid value>) in all requests being sent back, as well as the token and it worked!
I'm not sure what the implementation is in PHP to do this however :)
Also quick note, I've been trying to get values through jQuery's $.getJSON and $.Ajax method without any success, because the browser (chrome) I'm using has strict guidelines on cross domain requests, and it doesn't look like uTorrent is implementing JSONP.
Hope this helps!

The 400 Error message means you are communicating with a bad request.
The MIME media type for JSON text is application/json .

use text/plain or application/json, not text/json.
application/json sometimes causes issues on Chrome, so you might want to stick with text/plain in this case.

Have you tried changing the order of the query parameters?
eg: http://localhost:8080/gui/?token=<token_uuid>&list=1
Reference: https://github.com/bittorrent/webui/wiki/TokenSystem#examples
UPDATE
I ran into a similar problem trying to create and XMPPBot for utorrent client in python.
#m.t.bennett was correct. You need to save the session information as well.
When you receive the response from token.html, capture the cookie information as well.
Usually there are 2 params: GUID and sessions. You need to put them in the header for all your subsequent requests -- List API, Getfiles API, etc.
This should fix your problem!

Related

How to capture the headers of a 401 response or request with js o react?

How to capture the headers of a 401 response or request?
The server is returning this 401 to me since it needs a summary authentication, I need to create a hash to send it to the server from the MD5 algorithm, and I need to get the nonce from the 401 response to be able to calculate the MD5 algorithm, any ideas on how extract the headers the WWW-Authenticate nonce ? any ideas ?
I am using the JsSip.js library
work with react js or js
I leave the answer in an image that should censor some things
enter image description here
In order to retrieve the token from the header you should use Axios interceptors to and access it via req.headers,the proper header for a token is headers.authorisation:'Bearer tokenValue', docs
the same thing happens to me, I show you the configuration that I am using, can you tell me please if any information is missing? Since the 401 is not being answered automatically.
My code is:
var socket = new JsSIP.WebSocketInterface('wss://my.server.com/webrtc/')
var configuration = {
sockets: [socket],
uri: 'sip:TestUser#xxx.xx.xxx.xxx:5060',
password: 'xxxxxxx',
//contact_uri: 'sip:TestUser#xxx.xx.xxx.xxx',
}
var ua = new JsSIP.UA(configuration)
ua.start()
Thank you for your answer.

PHP not receiving any data from XMLHttpRequest

I cannot seem to send any POST data to a PHP file via XMLHttpRequest. I have read many questions like this one but everyone had a different issue - none of them seem to be the case here.
I have boiled these two files down to their absolute core basics and it is still is not receiving any POST data. I have done this the exact same way in plenty of other instances before and I'm not sure how this one is any different.
index.php
...
<button id="login-button">Log in</button>
...
Javascript:
function login() {
let ajax = new XMLHttpRequest();
ajax.open('POST', 'login.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
ajax.onload = function() {
alert(this.response);
};
ajax.send({user:'hello', password:'there'});
}
document.getElementById('login-button').addEventListener('click', login)
login.php:
var_dump($_POST);
The alert message with the output, every single time, simply reads:
array(0) {
}
The JS and PHP are both in the same folder of the same website on the same server, running PHP 7 if that matters. What could I possibly be doing wrong here?
By using ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); you basically tell your request to expect url-encoded data.
Lets keep it very simple, you want to submit a username and password.
So the request should look like this ajax.send("username=hello&password=there")
In your sample code you tried to send I dont know what kind of object-notation. The go-to way to exchange data between frontend and backend is JSON.
To modify your example to work with json modify it in the following way:
ajax.setRequestHeader("Content-Type", "application/json");
let data = JSON.stringify({"username": "hello", "password": "there"});
ajax.send(data);
To get an object out of a valid JSON string you can use the json parse method
pe this helps you out :)

Can't verify CSRF token authenticity Rails 4 Ajax even when header is set

I'm really having trouble with this, and in this instance, I neither want to skip the verify_authenticity_token filter, nor change to protect_from_forgery with: :null_session.
In my request method, I am setting a header with the csrf token as follows:
var token = document.querySelector("meta[name='csrf-token']").content;
xhr.setRequestHeader("X-CSRF-Token", token);
And by inserting a breakpoint in my controller like so:
def verify_authenticity_token
binding.pry
super
end
I have verified that the header is set:
[1] pry(#<MyController>)> request.headers
=> #<ActionDispatch::Http::Headers:0x007fb227cbf490
#env=
{"CONTENT_LENGTH"=>"202",
.
.
.
# omitted headers
.
.
.
"HTTP_X_CSRF_TOKEN"=>"the-correct-token-from-meta-tag",
.
.
.
}
I have also tried passing the token as a param with the key authenticity_token (as is done with Rails forms), and set the X-CSRF-Param tag to match (from meta[name="csrf-param"]).
Yet I am still getting:
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 14638ms
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken
Anyone seen this before? Any thoughts on what might cause this?
Thanks in advance!
EDIT:
Following discussion in the comments of marflar's answer, it looks like the token has expired when the request is made (tested by comparing to form_authenticity_token). This is confusing me further, as the token set in <%= csrf_meta_tags %> is expired when the next request comes in. Any thoughts?
EDIT2: Following marflar's advice below, I added the following after_filter to my app controller:
def set_csrf_headers
response.headers['X-CSRF-Param'] = request_forgery_protection_token.to_s
response.headers['X-CSRF-Token'] = form_authenticity_token
end
And I updated xhr.onload in my request method as follows:
namespace.request = = function (type, url, opts, callback) {
// code omitted
xhr.onload = function () {
setCSRFHeaders(xhr);
var res = {data: JSON.parse(xhr.response), status: xhr.status};
return callback.call(xhr, null, res);
};
// code omitted
}
function setCSRFHeaders ( xhr ) {
var csrf_param = xhr.getResponseHeader('X-CSRF-Param');
var csrf_token = xhr.getResponseHeader('X-CSRF-Token');
if (csrf_param) {
document.querySelector("meta[name='csrf-param']").content = csrf_param;
}
if (csrf_token) {
document.querySelector("meta[name='csrf-token']").content = csrf_token;
}
}
I verified that the response headers, and then the meta tags are getting reset properly, however, by the time the next request comes in, this new token is expired again. Thoughts?
I have the same problem. I inspected Rails source code and concluded next:
authenticity_token not expired by itself, so no need to update it after each ajax request to server
don't need to send both params[:authenticity_token] and header['x-csrf-token'], just one of them, rails will check params first, than header
on page refresh, authenticity_token will be different, but it doesn't matter, because it's generated each time with one time pad and real csrf token (on the server) is time independent
real csrf token saved in session[:_csrf_token]
As you can see token is kept in session and my problem was that my session was expired after 24h (probably user stays on page for day without refresh)
If user is logged in by cookie or some other token params, anyway he gets new session and with it new CSRF token will be generated and any request with old authenticity_token will be invalid.
So, the main problem is with session, it's expired or reset.
My guess is that Rails might expect the token to be in the HTML, not the header. Can you try that?
Hope it helps.
Actually I think you might be using a stale CRSF token because you're copying it from your template.
I normally set it like so in my controller action:
response.headers['X-CSRF-Param'] = "#{request_forgery_protection_token}"
response.headers['X-CSRF-Token'] = "#{form_authenticity_token}"
Does the token in your page match the one returned by calling form_authenticity_token?
UPDATE
In response to your comment (quoted below):
I just checked and you are right about it being a stale token, which unfortunately leaves me even more confused. The meta tags with the CSRF data are set on the initial page load, at which time they match form_authenticity_token, yet the token is stale by the time the first ajax request is made. So it won't matter whether I set them in the HTML or as headers, as this would occur at the same time, and thus run into the same issue with the token expiring before the next request is made. Thanks for your help so far -- any ideas here?
I ran into this sort of problem when implementing AJAX login. I found I was unable to make POST requests of any kind after logging in, and that I needed the following code to refresh my token:
var update_csrf_token_and_param_after_ajax_login = function() {
$(document).on("ajaxComplete", function(event, xhr, settings) {
var csrf_param = xhr.getResponseHeader('X-CSRF-Param');
var csrf_token = xhr.getResponseHeader('X-CSRF-Token');
if (csrf_param) {
$('meta[name="csrf-param"]').attr('content', csrf_param);
}
if (csrf_token) {
$('meta[name="csrf-token"]').attr('content', csrf_token);
}
});
}
I think you probably just need to write a fresh token into your page before doing the POST...

jQuery Get Request on HTTP URL

i've recently tried to get some Response from an URL using jQuery. Therefore I copied a get request sample of jQuery API Get Request Tutorial into my project and tried to run it, but my debugging messages showed me, that it can't go further. I tried the javascript Ajax Library using a simple request, but it didn't work.
So i'm asking you, if you could help me somehow.
And this is all what i do, but there is no response.
var url = "http://www.google.com";
$.get(url, function(data){
alert("Data Loaded: " + data);
});
Did i probably forgot to include a ajax or jQuery library. For a better understanding, i have c and obj-c experince, this is why i think, that a library is missing.
In each sample there is just a short url like "test.php". Is my complete HTTP url wrong?
Thanks for your answers in advanced.
Br
Nic
I have provided an example scenario to help get you started:
<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script
This is probably best to include inside of an external JS file:
//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
$.ajax({
//The URL to process the request
'url' : 'page.php',
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type' : 'GET',
//Any post-data/get-data parameters
//This is optional
'data' : {
'paramater1' : 'value',
'parameter2' : 'another value'
},
//The response from the server
'success' : function(data) {
//You can use any jQuery/JavaScript here!!!
if (data == "success") {
alert('request sent!');
}
}
});
});
You're hitting the Same Origin Policy with regard to ajax requests.
In a nutshell, JS/Ajax is by default only allowed to fire requests on the same domain as where the HTML page is been served from. If you intend to fire requests on other domains, it has to support JSONP and/or to set the Access-Control headers in order to get it to work. If that is not an option, then you have to create some proxy on the server side and use it instead (be careful since you can be banned for leeching too much from other sites using a robot).
As others have said you can't access files on another server. There is a hack tho. If you are using a server side language (as i assume you are) you can simply do something like:
http://myserver.com/google.php:
<?php
echo get_file_contents('http://www.google.com');
?>
http://myserver.com/myscript.js
$.get('google.php',function(data){ console.log(data) });
That should work!
you just can access pages from your domain/server

How do I send a cross-domain POST request via JavaScript?

How do I send a cross-domain POST request via JavaScript?
Notes - it shouldn't refresh the page, and I need to grab and parse the response afterwards.
Update: Before continuing everyone should read and understand the web.dev tutorial on CORS. It is easy to understand and very clear.
If you control the server being POSTed, simply leverage the "Cross-Origin Resource Sharing standard" by setting response headers on the server. This answer is discussed in other answers in this thread, but not very clearly in my opinion.
In short here is how you accomplish the cross domain POST from from.com/1.html to to.com/postHere.php (using PHP as an example). Note: you only need to set Access-Control-Allow-Origin for NON OPTIONS requests - this example always sets all headers for a smaller code snippet.
In postHere.php setup the following:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://from.com': case 'https://from.com':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
This allows your script to make cross domain POST, GET and OPTIONS. This will become clear as you continue to read...
Setup your cross domain POST from JS (jQuery example):
$.ajax({
type: 'POST',
url: 'https://to.com/postHere.php',
crossDomain: true,
data: '{"some":"json"}',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
When you do the POST in step 2, your browser will send a "OPTIONS" method to the server. This is a "sniff" by the browser to see if the server is cool with you POSTing to it. The server responds with an "Access-Control-Allow-Origin" telling the browser its OK to POST|GET|ORIGIN if request originated from "http://from.com" or "https://from.com". Since the server is OK with it, the browser will make a 2nd request (this time a POST). It is good practice to have your client set the content type it is sending - so you'll need to allow that as well.
MDN has a great write-up about HTTP access control, that goes into detail of how the entire flow works. According to their docs, it should "work in browsers that support cross-site XMLHttpRequest". This is a bit misleading however, as I THINK only modern browsers allow cross domain POST. I have only verified this works with safari,chrome,FF 3.6.
Keep in mind the following if you do this:
Your server will have to handle 2 requests per operation
You will have to think about the security implications. Be careful before doing something like 'Access-Control-Allow-Origin: *'
This wont work on mobile browsers. In my experience they do not allow cross domain POST at all. I've tested android, iPad, iPhone
There is a pretty big bug in FF < 3.6 where if the server returns a non 400 response code AND there is a response body (validation errors for example), FF 3.6 wont get the response body. This is a huge pain in the ass, since you cant use good REST practices. See bug here (its filed under jQuery, but my guess is its a FF bug - seems to be fixed in FF4).
Always return the headers above, not just on OPTION requests. FF needs it in the response from the POST.
If you control the remote server, you should probably use CORS, as described in this answer; it's supported in IE8 and up, and all recent versions of FF, GC, and Safari. (But in IE8 and 9, CORS won't allow you to send cookies in the request.)
So, if you don't control the remote server, or if you have to support IE7, or if you need cookies and you have to support IE8/9, you'll probably want to use an iframe technique.
Create an iframe with a unique name. (iframes use a global namespace for the entire browser, so pick a name that no other website will use.)
Construct a form with hidden inputs, targeting the iframe.
Submit the form.
Here's sample code; I tested it on IE6, IE7, IE8, IE9, FF4, GC11, S5.
function crossDomainPost() {
// Add the iframe with a unique name
var iframe = document.createElement("iframe");
var uniqueString = "CHANGE_THIS_TO_SOME_UNIQUE_STRING";
document.body.appendChild(iframe);
iframe.style.display = "none";
iframe.contentWindow.name = uniqueString;
// construct a form with hidden inputs, targeting the iframe
var form = document.createElement("form");
form.target = uniqueString;
form.action = "http://INSERT_YOUR_URL_HERE";
form.method = "POST";
// repeat for each parameter
var input = document.createElement("input");
input.type = "hidden";
input.name = "INSERT_YOUR_PARAMETER_NAME_HERE";
input.value = "INSERT_YOUR_PARAMETER_VALUE_HERE";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
Beware! You won't be able to directly read the response of the POST, since the iframe exists on a separate domain. Frames aren't allowed to communicate with each other from different domains; this is the same-origin policy.
If you control the remote server but you can't use CORS (e.g. because you're on IE8/IE9 and you need to use cookies), there are ways to work around the same-origin policy, for example by using window.postMessage and/or one of a number of libraries allowing you to send cross-domain cross-frame messages in older browsers:
Porthole
XSSInterface
EasyXDM
jQuery PostMessage Plugin
If you don't control the remote server, then you can't read the response of the POST, period. It would cause security problems otherwise.
Create an iFrame,
put a form in it with Hidden inputs,
set the form's action to the URL,
Add iframe to document
submit the form
Pseudocode
var ifr = document.createElement('iframe');
var frm = document.createElement('form');
frm.setAttribute("action", "yoururl");
frm.setAttribute("method", "post");
// create hidden inputs, add them
// not shown, but similar (create, setAttribute, appendChild)
ifr.appendChild(frm);
document.body.appendChild(ifr);
frm.submit();
You probably want to style the iframe, to be hidden and absolutely positioned. Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.
Keep it simple:
cross-domain POST:
use crossDomain: true,
shouldn't refresh the page:
No, it will not refresh the page as the success or error async callback will be called when the server send back the response.
Example script:
$.ajax({
type: "POST",
url: "http://www.yoururl.com/",
crossDomain: true,
data: 'param1=value1&param2=value2',
success: function (data) {
// do something with server response data
},
error: function (err) {
// handle your error logic here
}
});
If you have access to all servers involved, put the following in the header of the reply for the page being requested in the other domain:
PHP:
header('Access-Control-Allow-Origin: *');
For example, in Drupal's xmlrpc.php code you would do this:
function xmlrpc_server_output($xml) {
$xml = '<?xml version="1.0"?>'."\n". $xml;
header('Connection: close');
header('Content-Length: '. strlen($xml));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Date: '. date('r'));
// $xml = str_replace("\n", " ", $xml);
echo $xml;
exit;
}
This probably creates a security problem, and you should make sure that you take the appropriate measures to verify the request.
Check the post_method function in http://taiyolab.com/mbtweet/scripts/twitterapi_call.js - a good example for the iframe method described above.
Create two hidden iframes (add "display: none;" to the css style). Make your second iframe point to something on your own domain.
Create a hidden form, set its method to "post" with target = your first iframe, and optionally set enctype to "multipart/form-data" (I'm thinking you want to do POST because you want to send multipart data like pictures?)
When ready, make the form submit() the POST.
If you can get the other domain to return javascript that will do Cross-Domain Communication With Iframes (http://softwareas.com/cross-domain-communication-with-iframes) then you are in luck, and you can capture the response as well.
Of course, if you want to use your server as a proxy, you can avoid all this. Simply submit the form to your own server, which will proxy the request to the other server (assuming the other server isn't set up to notice IP discrepancies), get the response, and return whatever you like.
One more important thing to note!!!
In example above it's described how to use
$.ajax({
type : 'POST',
dataType : 'json',
url : 'another-remote-server',
...
});
JQuery 1.6 and lower has a bug with cross-domain XHR.
According to Firebug no requests except OPTIONS were sent. No POST. At all.
Spent 5 hours testing/tuning my code. Adding a lot of headers on the remote server (script). Without any effect.
But later, I've updated JQuery lib to 1.6.4, and everything works like a charm.
If you want to do this in ASP.net MVC environment with JQuery AJAX, follow these steps:
(this is a summary of the solution offered at this thread)
Assume that "caller.com"(can be any website) needs to post to "server.com"(an ASP.net MVC application)
On the "server.com" app's Web.config add the following section:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
</customHeaders>
</httpProtocol>
On the "server.com", we'll have the following action on the controller(called "Home") to which we will be posting:
[HttpPost]
public JsonResult Save()
{
//Handle the post data...
return Json(
new
{
IsSuccess = true
});
}
Then from the "caller.com", post data from a form(with the html id "formId") to "server.com" as follow:
$.ajax({
type: "POST",
url: "http://www.server.com/home/save",
dataType: 'json',
crossDomain: true,
data: $(formId).serialize(),
success: function (jsonResult) {
//do what ever with the reply
},
error: function (jqXHR, textStatus) {
//handle error
}
});
There is one more way (using html5 feature). You can use proxy iframe hosted on that other domain, you send message using postMessage to that iframe, then that iframe can do POST request (on same domain) and postMessage back with reposnse to the parent window.
parent on sender.com
var win = $('iframe')[0].contentWindow
function get(event) {
if (event.origin === "http://reciver.com") {
// event.data is response from POST
}
}
if (window.addEventListener){
addEventListener("message", get, false)
} else {
attachEvent("onmessage", get)
}
win.postMessage(JSON.stringify({url: "URL", data: {}}),"http://reciver.com");
iframe on reciver.com
function listener(event) {
if (event.origin === "http://sender.com") {
var data = JSON.parse(event.data);
$.post(data.url, data.data, function(reponse) {
window.parent.postMessage(reponse, "*");
});
}
}
// don't know if we can use jQuery here
if (window.addEventListener){
addEventListener("message", listener, false)
} else {
attachEvent("onmessage", listener)
}
High level.... You need to have a cname setup on your server so that other-serve.your-server.com points to other-server.com.
Your page dynamically creates an invisible iframe, which acts as your transport to other-server.com. You then have to communicate via JS from your page to the other-server.com and have call backs that return the data back to your page.
Possible but requires coordination from your-server.com and other-server.com
I think the best way is to use XMLHttpRequest (e.g. $.ajax(), $.post() in jQuery) with one of Cross-Origin Resource Sharing polyfills https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-CORS
This is an old question, but some new technology might help someone out.
If you have administrative access to the other server then you can use the opensource Forge project to accomplish your cross-domain POST. Forge provides a cross-domain JavaScript XmlHttpRequest wrapper that takes advantage of Flash's raw socket API. The POST can even be done over TLS.
The reason you need administrative access to the server you are POSTing to is because you must provide a cross-domain policy that permits access from your domain.
http://github.com/digitalbazaar/forge
I know this is an old question, but I wanted to share my approach. I use cURL as a proxy, very easy and consistent. Create a php page called submit.php, and add the following code:
<?
function post($url, $data) {
$header = array("User-Agent: " . $_SERVER["HTTP_USER_AGENT"], "Content-Type: application/x-www-form-urlencoded");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
$url = "your cross domain request here";
$data = $_SERVER["QUERY_STRING"];
echo(post($url, $data));
Then, in your js (jQuery here):
$.ajax({
type: 'POST',
url: 'submit.php',
crossDomain: true,
data: '{"some":"json"}',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
Should be possible with a YQL custom table + JS XHR, take a look at:
http://developer.yahoo.com/yql/guide/index.html
I use it to do some client side (js) html scraping, works fine
(I have a full audio player, with search on internet/playlists/lyrics/last fm informations, all client js + YQL)
CORS is for you.
CORS is "Cross Origin Resource Sharing", is a way to send cross domain request.Now the XMLHttpRequest2 and Fetch API both support CORS, and it can send both POST and GET request
But it has its limits.Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.
And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*')
For lots of request way if you don't know how to choice, I think you need a full functional component to do that.Let me introduce a simple component https://github.com/Joker-Jelly/catta
If you are using modern browser (> IE9, Chrome, FF, Edge, etc.), Very Recommend you to use a simple but beauty component https://github.com/Joker-Jelly/catta.It have no dependence, Less than 3KB, and it support Fetch, AJAX and JSONP with same deadly sample syntax and options.
catta('./data/simple.json').then(function (res) {
console.log(res);
});
It also it support all the way to import to your project, like ES6 module, CommonJS and even <script> in HTML.
If you have access to the cross domain server and don't want to make any code changes on server side, you can use a library called - 'xdomain'.
How it works:
Step 1:
server 1: include the xdomain library and configure the cross domain as a slave:
<script src="js/xdomain.min.js" slave="https://crossdomain_server/proxy.html"></script>
Step 2:
on cross domain server, create a proxy.html file and include server 1 as a master:
proxy.html:
<!DOCTYPE HTML>
<script src="js/xdomain.min.js"></script>
<script>
xdomain.masters({
"https://server1" : '*'
});
</script>
Step 3:
Now, you can make an AJAX call to the proxy.html as endpoint from server1. This is bypass the CORS request. The library internally uses iframe solution which works with Credentials and all possible methods: GET, POST etc.
Query ajax code:
$.ajax({
url: 'https://crossdomain_server/proxy.html',
type: "POST",
data: JSON.stringify(_data),
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.done(_success)
.fail(_failed)

Categories

Resources