sending data to another website and receive result - javascript

If i have a website1.com and website2.com, can I send data ( ex: value from input ) from website2.com to website1.com and receive result? with no page refresh or redirect. I'd like to use only javascript & ajax, no PHP or jQuery. If it is possible give me an example how to do it.
I thought about creating an script element ( with javascript) on website2.com with src like : website1.com?data=<value from input>, and when script element loads the src, it will show me an result, but maybe there is a better option to do this.
PS: I will have more separated datas to send.
Note: this is not XSS, just a public project for websites, which will need to update datas every x minutes and to send some data to website1.
Thanks.

Your question is not completely clear, but in general when you have to do cross-site AJAX you have to use JSONP

Since XmlHttpRequest does not work cross-domain, you have to use JSONP. Basically, this is adding a script tag dynamically as you're suggesting to do. Then, the server uses your GET datas, does whatever it wants, and usually "prints" a callback function.
When you call a file using the script tag, it will evaluate everything displayed. This is why, if, on the server side, you're doing :
<?php
echo 'alert(1);';
?>
This will be evaluated as javascript. You can then easily understand how to use a callback function (another GET parameter).
Also, in jQuery, there is an option called 'jsonp' when you call $.ajax (using "callback" as default GET parameter, but can be changed).

You could have some XSS issues but it is possible you could use ajaxgold. It is an pretty easy manner to send pretty much everything over.
Call send to website2
postDataReturnText( 'http://website2.com', 'data=bla', getResult );
Return the result
function getResult( text ) {}

Related

How to Run an XMLHttpRequest, Put Result in Session Before Page Loads

I want to run an XMLHttpRequest to grab information from an API and then use it to populate variables in PHP code that gets executed (without jQuery). While I would like to inject the information after the page loads, that's not possible in this case for various reasons. In essence, we're populating non-HTML PHP code with no CSS ID to select.
I tried creating a Promise and using then to inject the results of the API call into session variables, but I discovered that XMLHttpRequest deprecated synchronous requests on the main thread (e.g. you can no longer use false for the last parameter in the open function.
E.g.
xhr.open("GET", "https://www.myapi.com/api/v1/objects/1.json", false);
So, how would I go about setting these variables from XMLHttpRequest before the page is rendered? Is there a good way to do that or is it deprecated for a reason and we need to consider a deeper change?
Thanks in advance for any help!
Using synchronous calls was deprecated because is almost always possible to circumvent and it slows page loading and user's experience. Is it really necessary to do it before the page rendering? You can place a loader until the request is done and the callback has the data and then remove it.
Or even better if this happens only on page load PHP can just put the result in the output HTML, if you need to store it for JavaScript use you can echo something like:
<script type="text/javascript">
var globalVar = ['stuff'];
</script>
You can use it from other scripts, and also use window.globalVar to get the value because it is global.
If it is an api with a private key then it MUST be called by PHP rather than JavaScript, otherwise whoever analyzes the code could gather the API KEY, else if it is public and you don't want to overload the server with this requests the callback method is the way to go: place a loader with an overlay on the rest of the page, when the request is completed, do your calculations and delete or hide loader and overlay elements.

Block direct access to php file called by ajax function [duplicate]

I wish to have a webpage that uses AJAX to access a PHP file in ./ajax/file.ajax.php
Trouble is, I don't want people to be able to type the address in their browser to access that PHP file directly.
Is there a way I can make it so that only AJAX requests can access the file?
Is there something I can check for in the PHP file to achieve this?
If you're using jQuery to make the XHR, it will set a custom header X-Requested-With. You can check for that and determine how to serve your response.
$isXhr = isset($_SERVER["HTTP_X_REQUESTED_WITH"])
AND strotlower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest";
However, this is trivial to spoof. In the past, I've used this to decide whether to render a whole page (if not set) or a page fragment (if set, to be injected into current page).
If you're not using jQuery or you are not interested/you can't use custom headers (to go with what alex has offered), you may just simple POST some data with your Ajax request, and in that specific file check if that data has sent or not. If you send by GET it would be visible on the address bar, that's why I suggest POST.
<?php
if (empty($_POST['valid_ajax']))
header('Location: /');
?>
It's not solid as you can fool that with providing handmade data, however that's better than nothing if your problem is not that critical.

How to get data from remote website?

Lets say there is a url out there e.g. www.website.com/data.jsp
the link has the following JSON data
{"successful":"true","rows":[{"zip":"65472","user_id":"10843","name":"Rufio"}]}
I just want to be able to extract this data at runtime however I am having a hard time getting it using getJSON
$.getJSON("test2.jsp",function(result){
$("div").append(result.rows[0].user_id + " ");
});
Now if I run it using a local file with the data residing in test2.jsp as shown above it appends the user_id. However when I try to access "www.website.com/data.jsp" instead nothing happens. I don't believe the website is configured to work with JSONP either.
I need a way to figure out how to pull this data from the website at run time. Does anyone have any solutions or workarounds?
p.s. Is this something that might need to be sorted out on the other end? The people who own the website set this scenario up to be like a fake api call like typically you would pass in parameters to get back the specific information that you would need. In the case of this endpoint or url it just returns a single record or the file just contains the data listed above. They would like me to extract the data from their url at runtime.
You can't make a normal ajax call to to this other domain due to same origin policy.
You can use JSONP to load the remote page, but looking at that example output you wouldn't be able to access the data unless the remote site is setup for JSONP (assigning the JSON to a variable, calling a callback function, etc).
You could create a server-side passthrough script of your own. You don't mention what server-side technology you have available, but if you can use PHP, you do a passthrough like this:
<?php
echo file_get_contents("http://www.website.com/data.jsp");
?>
PHP (or any other server-side language) can fetch the remote data, and now you can use ajax to call your own script (which works since you're on the same domain).

When is a postback not a postback? (according to ASP.net)

Is there a difference between me using Javascript to redirect to URL + "?Querystring=value" versus using whatever mechanism ASP.NET uses?
If there is a difference, how can I make the rendered ASP.NET page be submitted to the same URL with a different query string by javascript?
If you want to do a post back just like a asp control like a asp:Button you can use the javascript functions included by the framework to do so:
__doPostBack('ControlIDOfEventYouWantToRaise','');
You can read more about the __doPostBack in this article:
Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net
Just doing a form.submit() will not be exactly the same as using __doPostBack.
To answer the first part of your question there is no difference doing a redirect if you are just doing a Response.Redirect as the will both do a GET. The difference is if you use a asp:Button control for instance, it will access your page first to handle the button (a post back) and then do a GET on the redirected page.
If you want to submit to the same URL (eg post your data) then you should use the __doPostBack method. If you don't require the data to be posted, then just do a redirect in javascript to the same URL with a modified query string (which will just do a basic GET) but your data will not be posted.
The only potential difference is that a querystring parameter is sent via GET, a form is (usually) sent by POST.
GET has a much smaller data limit as browsers have a max URL length (it varies)
You could use javascript to do a form.submit() which shoul emulate what ASP.Net does
I somewhat disagree with Basiclife's answer; if you have any code inside something like
if (IsPostBack) {
it's not going to be equivalent, ie the code is going to be executed if you're just setting the URL. Also, controls keep their state across postbacks but are freshly initialized if you're calling the URL again. This is due to ASP.NET trying to emulate a "normal" application, so the way to make sure a normal call and a postback have the same effect might result in "de-ASP.NET-ing" the entire page.
I'm not sure if what you want works. There probably is a way. But I heavily suspect there's a better way of doing this. If you get a postback for free, and can transmit data, why is it crucial that the data shows up in the URL, instead of being comfortably posted? I can see how you want a page to respond to a URL parameter, and how you might want to change the same parameter later on based on what's happening on that page, but since you always know you're posting back, you can eg override that URL parameter in that case, by something you're posting back. This doesn't sound so nice, but it might actually be less messy. Particularly since you seem to have a reason to not abandon the postback at all (otherwise you could just use a link, right?).

Call from JavaScript to server-side code in JSF

I'm looking for an easy way to call a bean's method that will take no parameters and return a string in JSF. The thing that I don't really need is that the method returns an action result and then uses the whole JSF life-cycle to do get me to another view. I need to do that from JavaScript so that I can put together some client-side parts of the application and going over the A4J part of RichFaces has brought me nothing so far.
So here's the scenario again in a step-by-step form:
from JS issue a GET on some address
on the server process that GET and return JSON or HTML (basically a string)
once the request is sent back to the client I want to be able to process it further with JS.
Thanks!
Use a4j:jsFunction and the data attribute.
So roughly you want something like:
<button onclick="callBackend();">Go</button>
<a4j:jsFunction name="callBackend" action="#{myBean.someMethod}" data="#{myBean.someString}" oncomplete="handleResponse(data);"/>
<script>
function handleResponse(response) {
alert(response);
}
</script>
Damo: can you explain why it might only work for the first time the method callBackend is executed? I'm experiencing a strange behavior that the first call succeeds and the next calls are just blocked. I see the server-side code being executed but some strange result is being sent back to the browser (something like the _viewstate and those kind of things).

Categories

Resources