WebWorks AJAX Cross domain request - ajax

I'm working on a playbook app with webworks sdk.
I'm trying to make an http request (method: post) by sending AND recieving data.
I can get the response from server, but the server can't get the $POST data, when I try to display $_POST['apiKey'], nothing apears, I checked my code 100 times, checked my config.xml for uri, can't find the error.
TL;DR: can't send but can receive data.
My PHP Server code:
echo "passed key is: ".$_POST["apiKey"]; // Nothing apears
echo "<br>";
if(md5($_SESSION['private_key'])===$_POST["apiKey"]){
}
else{
echo "Invalid API Key"; // Always getting this response on client app
exit();
}
?>
My JS Client code:
function httpRequest(){
var key="a984a4474cff54d8468a296edf3af65b";
document.getElementById("status").innerHTML="Reaching server...";
//////////////////////////////////////
var xdr = getXDomainRequest();
xdr.onload = function() {
document.getElementById("status").innerHTML=xdr.responseText;
}
xdr.open("POST", "http://mydomain/index.php");
xdr.send("apiKey="+key);
}
Solved:
When using POST method you should define the request header:
xdr.open("POST", "http://mydomain.com/index.php");
xdr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); // with this line
xdr.send("apiKey="+key);

Solved: When using POST method you should define the request header:
xdr.open("POST", "http://mydomain.com/index.php");
xdr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); // with this line
xdr.send("apiKey="+key);

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource - Mollie payment ajax

I'm trying to create a mollie payment with the following 2 libraries:
https://github.com/barryvdh/laravel-omnipay
https://github.com/thephpleague/omnipay-mollie
When the client fills in the form and submits an ajax request will be made to a function in my laravel application.
In my Laravel function I'm trying to do the following:
$gateway = Omnipay\Omnipay::create('Mollie');
$gateway->setApiKey('test_gSDS4xNA96AfNmmdwB3fAA47zS84KN');
$params = [
'amount' => $ticket_order['order_total'] + $ticket_order['organiser_booking_fee'],
'description' => 'Kapelhoek wijkfeesten',
'returnUrl' => URL::action('EventCheckoutController#fallback'),
];
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response); die;
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
return $response->getRedirectResponse(); die;
} else {
// payment failed: display message to customer
echo $response->getMessage(); die;
}
But I'm getting this response:
XMLHttpRequest cannot load https://www.mollie.com/payscreen/select-method/PRMtm6qnWG. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://kapelhoektickets.dev' is therefore not allowed access.
How can I fix this?
The line return $response->getRedirectResponse() is doing a redirect to the payment URL where the consumer should be sent to. However, this redirect is not allowed in an AJAX call.
Instead, your script should print this payment URL with $response->getRedirectUrl() and your webpage should redirect the consumer with javascript.
I think issue is with Api Dashboard. You have to whitelist your domain before making POST request
If you are requesting your API from a different domain, you have to implement CORS - I prefer this package https://github.com/barryvdh/laravel-cors.

Flask error after redirect from POST method

I am using a combination of Flask and Javascript. After user input from a web page I send a JSON object back to the Flask server. ie:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/completed/');
xhr.setRequestHeader('Content-Type', 'application/json');
var stringifiedObject = dataResultToJSON(data);
xhr.send(stringifiedObject);
Then in Flask:
#main_view.route('/completed/', methods=['POST'])
def completed():
if (request.headers['Content-Type'].startswith('application/json')):
#do stuff here
return redirect(url_for("main_view.home"))
#main_view.route('/')
def home():
logger.debug(">>home")
return render_template('home.html')
When flask redirects to 'home' asfter the Ajax POST I get the following console output:
DEBUG:myapp:>>home
INFO:werkzeug:127.0.0.1 - - [24/Apr/2016 20:13:15] "GET / HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [24/Apr/2016 20:13:15] "GET /%3C!DOCTYPE%20html%3E%3C!-- (... entire web page html)
The odd thing is the second INFO statement above - I don't get this line printed when I redirect to home from anywhere else - only occurs when I redirect from the 'completed' POST method. Werkzeug logs the entire home.html web page html and I get an error in the web client:
NetworkError: 404 NOT FOUND - http://127.0.0.1:5000/%3C!DOCTYPE%20html%3E%3C!-- (... entire web page html)
I also added code=307 to the redirect as per here: Make a POST request while redirecting in flask but still got the same 404 error.
I am stuck as to how to get around this.
I think your problem is that you're POSTing data as an AJAX request (i.e. not a browser navigation, but programatically from your client). It doesn't really make much sense to tell your AJAX client to redirect after the POST completes.
You're then trying to tell the client to redirect...but the redirect request is being returned to the XMLHttpRequest.
I'm not 100% sure what you want to happen, but you'd probably be better off using a regular form post if you want the client to redirect once you've posted the data.
I believe what you're trying to do is better illustrated by the answer to this question:
How to manage a redirect request after a jQuery Ajax call
I got this working following the comment and answer above. Specifically I did:
def completed():
#other code here
return url_for("main_view.home")
and in JS:
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var OK = 200;
if (xhr.status === OK) {
window.location.href = xhr.responseText;
}
else {
console.log ('Error: ' + xhr.status);
}
}
};

Cannot access error response body from client when using nginx + lua

I'm using the following lua script to forward all server responses that are served from Node. My error handling for a /signup route works as follows:
if authenticationResult.status ~= 201 then
...
ngx.status = authenticationResult.status
ngx.say(authenticationResult.body)
ngx.exit(401)
return
end
From the client I send a typical signup request like so, using the superagent-promise library:
request
.post(url)
.type('form')
.send(data)
.end()
.then((response) => {
console.log('the response', response)
})
.catch((error) => {
console.log('the error', error)
})
When I send a valid post request from the client, the response variable in the .then successfully contains the response body.
However, when I sent an improper post request with invalid credentials, neither the .then nor the .catch executes. Instead, the Chrome console immediately displays POST http://api.dockerhost/signup 401 (Unauthorized).
I would like to know what I can do differently to successfully access the server's error response and its contents, outside of just its status code.
Per the manual, you need to use ngx.HTTP_OK as the return if you want nginx to return content as part of the page. Otherwise it will simply return a 401.
ngx.status = authenticationResult.status
ngx.say(authenticationResult.body)
ngx.exit(ngx.HTTP_OK)
return

Download file with AJAX using Dart

Is it at all possible to download a file upon an ajax request?
Does it matter if it's same domain / cross domain?
I know it can be done upon redirecting the browser to a URL and setting relevant headers, but was wondering if it can be done when doing an ajax request.
I'm POSTing JSON as the Request Payload to a URL and based on the content of the JSON, I want to send back a specific file.
client.post(url, body: request, headers:{"Content-Type":"application/json"}).then((res) {
if (res.statusCode == 200) {
if ("application/json" == res.headers["content-type"]) {
// parse JSON here
} else {
// download the content if Content-Disposition is set
}
}
}).whenComplete(() {
client.close();
}).catchError((exception, stacktrace) {
print(exception);
print(stacktrace);
showErrorMessage("An Error Occurred");
});
I can see the the correct headers coming back for downloading a PDF, but it's not doing anything if I receive these headers via an AJAX response.
Update - clarifying:
If you click this link, it will do a GET request to Github and download the file: https://github.com/dartsim/dart/archive/master.zip
I'm trying to download the file using a POST request via Dart's BrowserClient.post.

SoundCloud API 401 error in Codeigniter

I'm trying to get Soundcloud to return a track ID, but can't get it to work. Documentation here (PHP tab): https://developers.soundcloud.com/docs/api/guide#errors
I've triple checked my credentials from soundcloud that I'm adding as args.
Function in my controller:
function formprocessor()
{
require_once (APPPATH.'third_party/Services/Soundcloud.php');
// create a client object with your app credentials
$client = new Services_Soundcloud('my client id', 'my client secret', 'http://127.0.0.1:8888/index.php/welcome/');
try {
$me = json_decode($client->get('me'), true);
}
catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
}
What would cause this to fail? I keep getting a 401
Here's a reference to the API: https://developers.soundcloud.com/docs/api/reference
you need to authenticate by sending the user (even if thats you) to "authorizeurl":
$authURL = $client->getAuthorizeUrl();
then set the access token with:
$accessToken = $client->accessToken($_GET['code']);
$client->setAccessToken($_SESSION['token']); //if you saved token in a session
Then you should at least be able to "get me" this part is working for me however i cannot access things such as /me/tracks/ or /me/followings/ at the moment.

Resources