The following script queries information from an API and outputs it into the HTML, using simple AJAX and Javascript.
The TOKEN for the API is exposed in the Javascript. In my opinion this is not safe because anybody who can access the page can see the token. IF this method is not safe, is there some additional method to hide the token? Ideally I would like to use Javascript, HTML, and PHP if needed. The existing script is very simple and so I'm wondering if there is a relatively simple way to protect the token.. rather than having to add a lot of additional new code or methods.
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.eventbriteapi.com/v3/events/eventid/?
token=TOKEN",
"method": "GET",
"headers": {}
}
$.ajax(settings).done(function (data) {
console.log(data);
var content = "<h2>" + data.name.text + "</h2>" + data.description.html +
data.start.utc;
$("#eventbrite").append(content);
});
</script>
<div id="eventbrite"></div>
</body>
</html>
You can make a simple proxy script on your server using PHP!
Your JavaScript will then call this script, including the event ID and nothing else in the GET parameter, so calling your PHP Proxy would be something like /proxy.php?eventid=123
To further fancify this example you could utilize $_SESSION etc to make sure your user has visiter the page before visit and only allow 1 request per pageload or something similar.
I have prepared a sample, but you have to modify it to fit your needs!
<?php
//Get event ID you want to request:
$eventID = isset($_GET['eventid']) ? $_GET['eventid'] : FALSE;
//Exit if no ID provided:
if (!$eventID) {
exit('No ID Provided.');
}
//Set your token:
$token = '<YOUR_TOKEN_HERE>';
//Set url, %s will be replaced later:
$url = 'https://www.eventbriteapi.com/v3/events/%s/?token=%s';
//Set url, pass in params:
$request_uri = sprintf($url, $eventID, $token);
//Try to fetch:
$response = file_get_contents($request_uri);
//Set content-type to application/json for the client to expect a JSON response:
header('Content-type: application/json');
//Output the response and kill the scipt:
exit($response);
Resources:
What is a Proxy (Wikipedia)
Update:
JavaScript:
$.getJSON('/proxy.php', {eventid: '<id_here>'}, function(response){
console.log(response);
var content = "<h2>" + data.name.text + "</h2>" + data.description.html +
data.start.utc;
$("#eventbrite").append(content);
});
You probably should not store the API key client-side, why not store it in the PHP scripts that the JS calls to?
If you really insist on storing it client-side you'll definitely want to encrypt it but I wouldn't want to rely on that.
Store your API key one the sever and make requests to it when you need it. To make it even more secure on your server side only return the API key if a token (which you've set) is passed and validated to prevent spoof AJAX requests.
For example:
PHP
/** Change $_POST respectively to what you need. **/
if (isset($_POST['request_api_key_token']) && $_POST['request_api_key_token'] == 'your_value') {
/** Return your API key. **/
} else {
exit(header('HTTP/1.0 403 Forbidden'));
}
Related
I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.
I have a .js file hosted on domain1.com, but for this to work correctly I need to add a PHP code at the beginning. The reason for this is to bypass some restriction on Safari for my script and it requires me to create a session. The PHP code creates a session through a url to domain2.com. There is no browser redirection or anything, the user stays in the domain1.com. I want to have a single .js file in domain1.com so maybe an AJAX solution is what I need. Here it is:
<?php
session_start();
if (!isset($_SESSION['isIFrameSessionStarted']))
{
$_SESSION['isIFrameSessionStarted'] = 1;
$redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
header('Location: domain2.com/start-session.php?redirect=' . $redirect);
exit;
}
?>
The start-session.php file is hosted on domain2.com does not need any changes, it contains this:
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);
header('Location: ' . $redirect); // redirect back to domain
exit;
?>
Let me combine what you requested in comments:
I have a .js file hosted on domain1 ... I want to have a single js file and I can't put PHP into that ... the whole purpose of this is for domain1 to not have any php code or php file. ... The reason is because I want it cross-domain and the session to be created from domain2.
It sounds like your issue might be related to the Safari iFrame session cookie problem, especially because you have if (!isset($_SESSION['isIFrameSessionStarted'])) in one of your code blocks. I will continue with this assumption.
Summary of the problem for other readers:
Upon embeding an IFrame from one domain into a website of a different domain, you will quickly realise that Internet Explorer and Safari are blocking the cookies (and thus the session variables) of the website inside the IFrame (ref).
Attempted solutions that didn't pan out:
Safari 3rd party cookie iframe trick no longer working?
Internet Explorer & Safari: IFrame Session Cookie Problem
IFrame must die
Safari: Setting third party iframe cookies
PHP Session in iFrame in Safari and other browsers
My solution:
Essentially, PHP session "hijacking". It works surprisingly well where the above solutions failed. This is the essential solution. Please do any security enhancements* and URL-prettifying you like. Basically, we retrieve the PHP session ID through redirects and pass this to the iframe. Instructions are in the comments.
In your domainA.com head place this:
<script src="session.js"></script>
session.js (on domainA.com):
// Location of the domain B session starter
var sessionScriptURL = "http://domainB.com/start-session.php";
var refQSparam = "phpsessionid";
// Check if we have the phpsessionid in the query string
var phpsessionid = getParameterByName(refQSparam);
if(phpsessionid === null) {
// Not in the query string, so check if we have it in session storage
var sessionStore = sessionStorage.getItem(refQSparam);
if(sessionStore === null) {
// We have no session storage of the PHP session ID either, redirect to get it
top.location = sessionScriptURL + "?redirect=" + encodeURIComponent(self.location.href);
} else {
// phpsessionid was found in session storage. Retrive it
phpsessionid = sessionStore;
}
} else {
// Save the phpsessionid to session storage for browser refresh
sessionStorage.setItem(refQSparam, phpsessionid);
// Optional: Redirect again to remove the extra query string data
}
// Helper to get QS values
function getParameterByName(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
session-starter.php (on domainB.com):
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);
// redirect back with the php session ID
// Optional: encode this information
$href = $redirect . '?phpsessionid=' . session_id();
header('Location: ' . $href);
exit;
HTML (in the body, on domainA.com):
Append PHP session information to the iframe src.
<script>
document.write('<iframe src="http://domainB.com/embedded-script.php?phpsessionid='+phpsessionid+'"></iframe>');
</script>
embedded-script.php (on domainB.com, in an iframe):
<?php
// Use the phpsessionid passed in
$phpsessionid = rawurldecode($_GET['phpsessionid']);
// REF: http://php.net/manual/en/function.session-id.php
function session_valid_id($session_id) {
return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}
// Check that this is potentially a valid session ID
if(session_valid_id($phpsessionid)) {
// Set the session to the one obtained in session-start.php
session_id($phpsessionid);
}
session_start(); // Only call this after session_id()!
// Rest of your code
*Considerations:
Don't actually use document.write, use jQuery or document selectors.
Encode the PHP session ID
Perform another redirect back to the base URL of domainA.com to remove the ?phpsessionid= in the URL for a cleaner look.
If you decide to call session-starter.php with AJAX instead, you will get a new PHP session ID every time for the same reason. The iframe will successfully use this session ID, but if you open a new page to domainB.com, the session will yet again be different.
If you want to run PHP within a file extended with .js, you can do this by telling your apache web server. Add the following directive to the .htaccess or directly to the apache config:
AddType application/x-httpd-php .js
After this is done, your server will run the included PHP code as soon as the file is requested from the server.
Update:
If you want to use sessions with JavaScript, you can do this with an AJAX solution. For this implement a web service on the server which should store the session values. Programming language for implementation can be PHP or another one which can be run by the web server. Request the web service with JavaScript. Here is an answer with an example.
If you want to redirect in Javascript, you can't use a PHP redirect which you have called from AJAX. You can pass the URL you create in PHP and send it back to JavaScript and do the redirect from there. You can do something like:
PHP:
session_start();
if (!isset($_SESSION['isIFrameSessionStarted'])) {
$_SESSION['isIFrameSessionStarted'] = 1;
$redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
echo json_encode(array('url' => $redirect));
}
JavaScript:
$.get('phpfile', function(result) {
if (!result) return;
var data = JSON.parse(result);
window.location.href = decodeURIComponent(data.url);
});
Don't know what you're trying to achieve exactly but let's say you want to go from php to js and back to php you could trying something like this:
Solution 1: Using XMLHttpRequest
In PHP (domain1.com):
<?php
$parameter = ""; //If you'll like to add a parameter here
echo "<script type='text/javascript'>window.addEventListener('DOMContentLoaded',". "function () { goToJS('$paramter');});</script>";
?>
In JS:
window.goToJS = function (parameter) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
//You can redirect back to a php file here
document.location.href = "domain1.com";
//You can view feedback from that php file you sent the stuff to here - just for testing
alert("feedback" + xmlhttp.responseText);
}
}
xmlhttp.open('GET', 'http://domain2.com/start-session.php?q=' + parameter, true);
xmlhttp.send();
}
Not sure about your redirect links and stuff but yeah this should pretty much work. Did something similar a while back
Solution 2: Using ajax
Using ajax you could have a JS script as follows. (type could be POST or GET, Used an example where you sent some json to the php file. Can change the data sent if you properly describe to me what you wish to send. Alternatively could be null also
In JS:
function init_() {
$.ajax({
type: 'POST',
url: 'http://domain2.com/start-session.php',
data: {json: JSON.stringify(selectedEvent)},
dataType: 'json'
}).done(function (data) {
console.log('done');
console.log(data);
}).fail(function (data) {
console.log('fail');
console.log(data);
});
}
In PHP:
Let's say you sent a javascript json to PHP. You could use it in PHP as follows:
<?php
$status_header = 'HTTP/1.1 ' . 200 . ' ' . 'OK';
header($status_header);
header('Content-type: text/javascript');
$json = json_decode($_POST['json']); //Do whatever you want with the json or data sent
echo "This is the returned data"; //Echo returned data back to JS or wherever
?>
why don't just use script directly (if you put this script on top of file it will wait the script to finish creating session in domain2 anyway. (I guess you have iframe in domain1 that call to domain2?)
<script src="http://domain2.com/start-session.php"></script>
USe jquery and jqxhr object for this request, no need send browser to second server, from domain1 you can request to browser load page to init session, and your client never see that.
//include jquery min library and do next code
$(document).ready(function (){
var jqxhr = $.get( "http://domain2.com/start-session.php", function() {
alert( "success" ); //some action for success
})
.done(function() {
alert( "second success" ); //when all is done (success done)
})
.fail(function() {
alert( "error" ); //some action for error
})
.always(function() {
alert( "finished" ); //some end action for anycase
});
});
you can delete .done function, .fail function, and always function as you wish.
NOTE: ready function is to make sure, that domain1 page completely load, and then run script.
reference https://api.jquery.com/jquery.get/
Im having issues using trying to pull the first 15 words out of the file from the API. I have tried both as an XML and JSON and still seem to be getting this error:
XMLHttpRequest cannot load
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Im using the We feel fine API.
Here is my code:
<script type="text/javascript">
(function() {
var WeFeelAPI = "http://api.wefeelfine.org:8080/ShowFeelings?display=json&returnfields=feeling,conditions&limit=15";
$.getJSON( WeFeelAPI,function (json){
var feel = json.results[15];
console.log('Our feelings : ', feel);
});
})();
</script>
Any help would be appreciated i'm very new to all this, thanks
Reading up on the We Feel Fine APIs, it doesn't seem like they support JSONP, or even JSON from what I can see.
The issue preventing you from calling it is known as the Same Origin Policy. It prevents a domain from making an illegal request to another domain because of the security concerns it poses. You can read on it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript
JSONP (JSON with Padding) is a way for sites to work around it by loading the response a an external script that then triggers a callback function to validate the response content. This actual provides good info on SOP and JSONP: http://www.codeproject.com/Articles/42641/JSON-to-JSONP-Bypass-Same-Origin-Policy.
Unfortunately, the API you're using doesn't look to support JSONP so it would require the proxy approach. There is a clever/creative/maybe hackish(opinion) approach using something called Yahoo Query Language (YQL). YQL allows you to perform a x-domain request by using Yahoo's query service as the "proxy." You pass a request with a SQL-like query to it and Yahoo handles the JSONP approach. You can read about that here: http://developer.yahoo.com/yql/ (sorry for all the reading.)
And now for some code to demonstrate this. Note the QUERY being used to retrieve your XML and the fact that it must be encoded for URI use:
(function () {
var url = 'http://api.wefeelfine.org:8080/ShowFeelings?display=xml&returnfields=feeling,conditions&limit=15'
// using yahoo query
var query = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + url + '"') +
'&format=json&callback=?';
// make request via YQL and show data
$.getJSON( query, function(data) {
console.log(data);
// yql returns "results" in "query" from data
console.log(data.query.results);
});
})();
Play with the fiddle: http://jsfiddle.net/Ty3y2/
This same approach can actually be used to load HTML, and in fact is probably used for that more. The key is "select * from xml where..." which tells it to select everything inside the XML element found at the requested URL. Remember that XML data has a XML element at the root. Most times you will see this as "select * from html where..." because a typical web request returns HTML which is a HTML element at the root.
I have used this approach for a couple projects, though most of mine use a proxy via PHP or C#. However, I have had good success with this and it's useful when you don't want/need to put together a proxy for it.
Here's a simple PHP proxy you can run along-side your page with the JavaScript
<?php
// Saved as ShowFeelings-proxy.php
$options = array_merge($_GET, ['display' => 'xml']);
// if you don't have PHP 5.4+, you need to use the legacy array literal syntax, eg
// array('display' => 'xml')
$uri = 'http://api.wefeelfine.org:8080/ShowFeelings?' . http_build_query($options);
$xml = simplexml_load_file($uri);
// assuming you'd rather work with JSON (I know I would)
$data = [];
foreach ($xml->feeling as $feeling) {
$entry = [];
foreach ($feeling->attributes() as $attr => $val) {
$entry[$attr] = (string) $val;
}
$data[] = (object) $entry;
}
header('Content-type: application/json');
echo json_encode($data);
exit;
Then in your JavaScript...
+function($) {
var url = 'ShowFeelings-proxy.php',
options = {
'returnfields': 'feeling,conditions',
'limit': 15
};
$.getJSON(url, options, function(data) {
var feeling = data[14]; // array is zero-based
console.log(feeling);
});
}(jQuery);
I need to get the text behind the hashtag in the url (http://www.example.com/#TEXT) so i can use it in a php script. I know that I have to gather the text using javascript then save it as a cookie or something like that. The only problem is that I'm not good at javascript and I have tried but failed.
How can i do this the easiest way?
Here is one thing i have tried:
<script>
var query = window.location.hash;
document.cookies = 'anchor=' + query[1];
<?php if (!$_COOKIE['anchor']) : ?>
window.location.reload();
<?php endif; ?>
<?php
echo $_COOKIE['anchor'];
?>
Most sites that use the fragment like this (such as Facebook) will use JavaScript AJAX calls, depending on location.hash, to send its request to the server. Try that!
var xhr = new XMLHttpRequest();
xhr.open("GET","something.php?hash="+location.hash.substr(1),true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
// do something with this.responseText
}
};
xhr.send();
The hash part of the URL is not sent to the server, so you need to do so yourself.
The cookies set by the client too are not sent to the server either; the client just remembers them when it talks to the server.
This means that you have to retrieve in Javascript, as you already did, and make an explicit call.
// Example in jQuery
jQuery.ajax({
type: "POST",
url: "/path/to/php/script.php",
data: {
hash: window.location.hash
}
});
Then in the script.php you receive a $_POST['hash'] variable and can store it in the session. But remember that when you do, the sending page has already been loaded and is "stopped". If you want to trigger a reload, you need to send back some kind of response and react to it in jQuery's return function.
You can't. hashtags don't fly to the server. that's why MEGA site is still alive. hashes live only in the browser.
jQuery has the $.getJSON() function that I use to load json files from other domains like so:
$.getJSON('http://somesite.com/file.js', function(output) {
// do stuff with the json data
});
I was wondering if I can do the same with xml files from other domains or do I have to use a server side language for that?
This is the xml document I would like to load:
http://google.com/complete/search?output=toolbar&q=microsoft
I agree with #viyancs , simply speaking if you want to get xml of other domain, there is a cross-domain-restriction, the way to solve this is create a proxy, so the request process is:
1. use $.ajax to request your proxy(with the real xml url you want to access).
2. your proxy retrive the xml url content.
3. your proxy returns the content to your $.ajax call.
For more detail have a look at: http://developer.yahoo.com/javascript/howto-proxy.html
BTW: why you dont have to do this for JSON? it is a technique called JSONP.
you can try this
$.ajax({
type: "GET",
dataType: "xml",
url:"localhost/grab.php",
success: function(){
//to do when success
}
});
1) make service as proxy to get content from url
example in grab.php code:
<?php
$url = 'http://google.com/complete/search?output=toolbar&q=microsoft';
$parsing = parse_url($url);
$scheme = $parsing[scheme];
$baseurl = basename($url);
$strbase =$baseurl;
$finalUri = $scheme .'://' .$strbase;
$handle = fopen($finalUri, "r",true);
// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
If you really don't have the ability to use a proxy with a cache (which is proper etiquette), you can use something like YQL as a JSONP proxy service. You'll eventually hit a limit without an API key.
// query: select * from xml where url='http://google.com/complete/search?output=toolbar&q=microsoft'
var xml_url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fgoogle.com%2Fcomplete%2Fsearch%3Foutput%3Dtoolbar%26q%3Dmicrosoft'&diagnostics=true"
$.get(xml_url,function(xml){ console.log(xml); });