How to make a subdomain ajax call with jQuery (without iFrames) - javascript

site.com/api/index.php is where I need the ajax request to go. From site.com/sub/ the request works perfectly but sub.site.com is sending the request to sub.site.com/api/index.php which obviously does not exist... I've Google and StackOverflowed the hell out of the question, but can't seem to find an answer that works.
Code:
var jQuery_ajax = {
url: "site.com/api/index.php",
type: "POST",
data: $.param(urlData),
dataType: "json"
}
var request = $.ajax(jQuery_ajax);
The most common answer was to set document.domain to the regular site, but that does not seem to do anything... I've also seen answers talking about iFrames, but I want to stay away from iFrames at all costs.
document.domain = "site.com";
** Note: everything is on the same server.
HACKY SOLUTION: made sub.site.com/api/index.php a file that simply reads
include_once("$path2site/api/index.php");

Once you've corrected the URL to http://site.com/api/index.php try adding the following to api/index.php:
header("Access-Control-Allow-Origin: http://sub.site.com");
e: it's possible that doing so may disallow use from site.com as well; I'm not seeing a way to provide two values, so you may need a way to tell it which site to use, like a ?sub=1 arg to index.php

Related

Ajax scraping: getElementByTagName as plaintext

I have a URL that I'd like to scrape a certain bit of information from and I'd preferably do that by obtaining the element. I'd also need to get it as plaintext, but I'm still pretty new to Ajax/jQuery and don't quite know what the correct syntax is..
My ajax call is:
$.ajax({
url: URL,
dataType: 'text',
success: function(data) {
var info = data; //How can I get a table from the data without loading the whole site extracting a small portion?
if(info != undefined) {
console.log(info); //Needs to be plaintext.
}
}
});
I hope my question is clear... I'm essentially loading a website and retrieving a table or class name as plaintext... How could I do that? Thanks.
Your options on the client-side are:
1.) First, optionally use a regular expression to isolate that tag contents, but this is usually considered rather costly.
2.) Create a node, then drop the text into it's innerHTML.
That's usually the standard way of rendering text responses to the DOM.
Neither one are all that lightweight.
If you just need to pick something out of the text, use Regular Expression. Also, as mentioned, be aware of XSS and cross-origin policy.
Additionally, you may want to handle this on the server-side.

How to return a javascript object from php using ajax

I've been on this for hours already, I've read tons of articles and still cant figure it out.
Here's the deal.
I am working with Chrome extensions and I want to do a call to my server that returns me a js object. I dont want to inject this into the page, but I want to be able to use it within my content script.
NOTE: I cannot use eval() (I have tried though) and I cannot use jsonp
I am using a framework so my headers arent set here, but they set to return application-type application/javascript utf-8;
my php side looks like this:
$refererObj = 'var refererObj = {
myFunc: function () {
console.log("hello");
}
};';
echo $refererObj;
my js looks like this
$.ajax({
url: myUrl,
crossDomain: true,
data: postData,
dataType: "json",
type: "POST",
}).done(function(data){
eval(data);
console.log(data);
console.log(refererObj);
});
The first console.log gives ["var refererObj = {↵ getProducts: function () {↵…(products);↵ console.log("hello");↵ }↵};"]
The second gives "Uncaught ReferenceError: refererObj is not defined"
I get the response as a string with the javascript object and everything is all good until I actually want to "convert" the string into a usable code.
Any help would be really great.
Thanks
You actually can use eval() if you relax the default Content Security Policy with unsafe-eval. But it's a big hammer that's best avoided.
You can use JSONP, again, if you can serve it off an https server and add it to script-src of the Content Security Policy. This is slightly less of a security risk.
I doubt there is any other solution: anything you load off an external server is to be considered tainted and if you find a way to execute it - congrats, you just bypassed CSP in Chrome and should go claim your bug bounty.
Please note that in case of simply JSON data it's all moot, you can just load it with XHR and JSON.parse it. But your example contains code.

Run (JS) function if server responded something specific

On one of my pages I have "tracking.php" that makes a request to another server, and if tracking is sucessful in Firebug Net panel I see the response trackingFinished();
Is there an easy way (built-in function) to accomplish something like this:
If ("tracking.php" responded "trackingFinished();") { *redirect*... }
Javascript? PHP? Anything?
The thing is, this "tracking.php" also creates browser and flash cookies (and then responds with trackingfinished(); when they're created). I had a JS that did something like this:
If ("MyCookie" is created) { *redirect*... }
It worked, but if you had MyCookie in your browser from before, it just redirected before "track.php" had the time to create new cookies, so old cookies didn't get overwritten (which I'm trying to accomplish) before the redirection...
The solution I have in mind is to redirect after trackingFinished(); was responded...
I think the better form in javascript to make request from one page to another, without leaving the first is with the ajax method, and this one jQuery make it so easy, you only have to use the ajax function, and pass a little parameters:
$.post(url, {parameter1: parameter1value, param2: param2value})
And you can concatenate some actions:
$.post().done(function(){}).fail(function(){})
And isntead of the ajax, you can use the $.post that is more easy, and use the done and fail method to evaluate the succes of the information recived
As mentioned above, AJAX is the best way to communicate between pages like this. Here's an example of an AJAX request to your track.php page. It uses the success function to see if track.php returned 'trackingFinished();'. If it did then it redirects the page 'redirect.php':
$.ajax({
url: "track.php",
dataType: "text",
success: function(data){
if(data === 'trackingFinished();'){
document.location = 'redirect.php';
}
}
});
The example uses JQuery.

IE8 XHTML returned in jQuery ajax call issue

I'm having an issue I cannot resolve through trying lots of different methods!!
Works in Chrome, FF, IE9 but not IE8 or IE7
Overview
I have a page, that Ajax's in the whole HTML from a local .aspx of which reads a photobucket XML feed puts into an HTML list and returns.
http://custommodsuk.com/Gallery.aspx
I've done it this way so the page ranking isn't penilised by Google speed rankings, as the server would be going off and making the call.
The code
$.ajax({
type: "GET",
url: ajaxURL,
dataType:'html',
success: function (feedHTML) {
var galleryList = $(feedHTML).find('#galleryList').find('.listItem');
var noItems = galleryList.length;
console.log(feedHTML.type);
galleryList.each(function (index) {
...
});
}
});
What I've tried
As you can see the console.log(),
the type is undefined, the feedHTML.length shows no. of characters. And from what I gather is generally treated as a string.
It is the JQuery not being able to turn the response into a jQuery object, and I can't traverse it. Therefore the each won't cycle.
I've seen lots of people with the same/similar issue on SO, but no answers, partly due to crap code examples.
Photobuckets RSS feed is malformed.
<p>CustomModsUK posted a photo</a></p>
This tripped up IE8. If you ever have problems like this in the future, check the validity of the HTML!!!

JQuery external Ajax call not working in IE

I have an ajax script that sends some data to an external URL. The external URL is hosted on the same server, however the domain is different than the source of the ajax call.
This is working perfectly in Firefox and Chrome. However in IE The ajax call does not go through, and the Return False function does not either work (once the ajax call fails).
Below is my code:
$.get('http://myexternaldomian.com/feedback/save.php', {
answer: $('#answer').val(),
page_url: pathname
});
// Keeps the user on the page
return false;
When I try removing the http:// from the ajax url, the return false does work.
Any help on this would be greatly appreciated. Thank You
From jQuery documentation
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
and Same Origin Policy on Wiki
I'm surprised any of them are working. Browsers generally don't allow ajax calls to a domain other than the one the current page came from.
The main exception to this rule is if you make an ajax call using jsonp (json with padding). You can do this with jQuery, here's how. Look under the dataType option.
(this is copypaste from my another similar answer). You could try enabling "jQuery.support.cors=true" flag and see how it goes. I use jQuery v1.7.2.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
you may set flag once or everytime before using jQuery ajax function
now I can read .xml document in IE and Firefox. Other browsers I did not test.
response document can be plain/text, xml, json or anything else
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
http://en.wikipedia.org/wiki/Same_origin_policy
I dont think it should work on Chrome or Firefox, unless you testing on localhost or something like that, this would be against the crossdomain policy.
What you need is to proxy it inside the same domain, use php to connect to the destination you need and call the url from the same domain.
save_cross_domain.php -> connect through server to the desired url
then ajax calls save_cross_domain.php
you should add a
callback=?
to your url and handle this on the server side.
I did this once for a java servlet, and when the callback param was included I added an extra pair of parenteses around the json response..
hope it helps!
A couple of things:
The answers/conversation for this question has gone a bit out of context. Actually from the question it was more implied how to make ajax calls in IE. [Atleast modify the question title, else the question is very localized]
A couple of solutions to this cross-domain issue:
CORS[compatible after IE7]
JSONP [ here actually the browser takes in the input thinking it is a script]
server side encoding

Categories

Resources