I am developing a simple Mobile App that displays currency rates from an XML file. Now, the problem is that I read the XML from my server so I have to put the full URL in .ajax but it dosen't seem to work with external URLs. Can someone tell me how can I fix this or how to replace the code so it will work?
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.domain.com/currencies.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Currency').each(function(){
var Name = $(this).find('Name').text();
var ValueUSD = $(this).find('ValueUSD').text();
var ValueEUR = $(this).find('ValueEUR').text();
var ExValueUSD = $(this).find('ExValueUSD').text();
var ExValueEUR = $(this).find('ExValueEUR').text();
$('#content').append('<div class="currencyBox"><div class="currency">'+Name+'</div><div class="tab1"><div class="half">'+ValueUSD+'</div><div class="half">'+ValueEUR+'</div></div><div class="tab2"><div class="half">'+ExValueUSD+'</div><div class="half">'+ExValueEUR+'</div></div></div>');
});
}
});
});
</script>
Look at jquery doc about jsonp. There is possibility to do cross site request in html5 especially, however most tools (firebug, noscript, adblock) and some browsers on default are bloking such requests. So I would stick to jsonp as most reliable source.
Ajax Doesnot work with Cross-Domain due to same origin policy. Try JSONP in such case.
Related
I am new to jQuery and JavaScript. I am trying to read the content of a .doc file and display it in a textarea.
var url = "D:\\way2Jobs\\way2jobz\\WebContent\\pages\\Resumes\\";
var firstName = $("#first").val();
var extn=".doc";
jQuery.ajax({
url : url+firstName+extn,
dataType : "doc",
success : function(data){
alert(firstName);
document.getElementById("candResume").innerHTML = data;
}
});
You just can't (thanks god) make an ajax request to your local filesystem. It's a safety restriction and you can't bypass this.
1 - You have to at least use a webserver like apache
2 - You never will sucessfuly make a request to D:\
3 - You CAN request a DOC file and process it using javascript. But it's not that easy because DOC file isn't a plain text and javascript was not made for it. Maybe it's easier for you to do it using a server side language such as PHP or JAVA or even NodeJS if you are familiar with javascript.
I have a js file in domain1 that is working fine in domain1. But if I connect the js (from domain1) to domain2, it is not working.
The js file is a connection to a PHP file in domain1 to output some results. How can i make it work in domain2?
[I want to make the js work from the domain1 itself]
Here the js file in domain1,
function sendQuery() {
var container = $('#DisplayDiv');
$(container).html('<img src="http://www.domain1.com/loading.gif">');
var newhtml = '';
$.ajax({
type: 'POST',
url: 'http://www.www.domain1.com/data.php',
data: $('#SubmitForm').serialize(),
success: function (response) {
$('#DisplayDiv').html(response);
}
});
return false;
}
It is working till loading.gif file, but no data is output from the external output.php file from domain2.
[Here domain1 & domain2 are used only as examples]
WORKING FINE NOW!!
Thanks to #Ohgodwhy, Header set Access-Control-Allow-Origin "*" in .htaccess in domain1.
It is not clear what you want Exactly .. If you past Your code Here it will be Excellent ..
But i think if you want to Connect any 'js' file from any domain to your domain you can use the ordinary deceleration for it :
in HTML:
<script type = "text/javascript" src="https://googledrive.com/host/0B248VFEZkAAiNjhxaDNUZVpsVHM" charset="utf-8"></script>
in PHP :
echo '<script type = "text/javascript" src="https://googledrive.com/host/0B248VFEZkAAiNjhxaDNUZVpsVHM" charset="utf-8"></script>';
Very important note :
1- You must take care of Script order for dependent script.
2- The element which you call must be attend and visible during cal time.
Javascript don't allow cross domain AJAX call.
There ae some options available to do that like JSONP
See this link for more options : link
This is mostly an ivory tower question, since I can easily just make a new URL endpoint. But basically, I'd like to be able to serve up CSV when the user has the Accept header configured to include text/csv. That's trivial on the server side, but on the client side I don't know how to set the Accept header unless I'm using XHR or some other "non-browser" client. Is there a way in HTML to set the Accept header in a link or in JS to set the Accept header when using window.location?
I figure I might as well put this here for the next thousand people looking at the post. You cannot do it.
Update:
I will leave my original answer below for posterity, but I now see that I didn't really answer the question. There isn't a way to do this "natively", the best approach I can think of would be to use a data uri (http://en.wikipedia.org/wiki/Data_URI_scheme) and have AJAX do the work for you:
// aware that you didn't mention jQuery, but you can do this with or without
var download = function(){
var mime = this.getAttribute('data-mime-type');
$.ajax({
accepts: mime,
success: function(data){
var uri = 'data:'+mime+';charset=UTF-8,' + encodeURIComponent(data);
window.location = uri;
}
})
return false;
}
With the same idea used in the example below:
Download CSV
document.querySelectorAll('a[data-mime-type]').onclick = download;
Original Answer
There is no built-in way to force an 'Accept' header on a link (via HTML or Javascript). I think you could pull this off fairly easily using a very small amount of server & client-side code though. Should be easy in any language, my example is PHP:
function get_accepted_headers() {
$headers = apache_request_headers();
if(array_key_exists('Accept', $headers)) {
$accepted = explode(',', $headers['Accept']);
return $accepted;
}
return array();
}
Add a data-accept attribute to your download links:
Download CSV
Then attach a click event handler to ensure that the user accepts the specified content type:
// will end up with something like: ["text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"]
var user_headers = <?=stripslashes(json_encode(get_accepted_headers()))?>;
var click_header_check = function() {
var accept = this.getAttribute('data-accept');
if(user_headers.indexOf(accept) == -1) {
console.log('User does not explicitly accept content-type: %s', accept);
return false;
}
window.location = this.href;
return;
}
// attach the event listener
document.querySelector('a[data-accept]').onclick = click_header_check;
Not sure if this is what you were looking for, but hope that it helps.
For those still interested, there is a way to do this in pure javascript.
The following code uses JQuery (https://jquery.com/) and FileSaver.js (http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js) though you could write the respective parts yourself:
//in case of non binary data use:
var type = 'text/xml';
var url = 'http://your_url_here/'
$.ajax({accepts:{text:type},
url:url,
processData:false,
dataType:'text',
success:function(data){
saveAs(new Blob([data], {type: type}),'filename.txt');
},
error: function(){
// Handle errors here
}
});
I have some images in a folder with the .JPG extension. I want to change the image extension to .PNG programmatically. My earlier post is here: https://stackoverflow.com/questions/15428521/read-a-file-extension-and-change-that-extension.
$.ajax({
type: "GET",
url: "aa.jpg",
dataType: "snapshot",
success: function (snapshot)
{
try
{
var src = $(this).attr("url");
$(src).attr('src',$(this).attr('url').replace('.jpg','png'));
}
catch(ex)
{
alert(ex);
}
}
});
After reading both your question I realise that you want to rename files on the client.
This cannot be done using jQuery alone. Normal javascript engines do not allow access to filesystems on client side.
You need something a little more powerful - on windows that would be an ActiveX object. If you're on another OS, or a browser which does not support ActiveX, I don't know how to help you.
Here you can find an example.
<script>
function jsonfunc(){
var data ="publick="+document.getElementById("publickeyval").value+"&privatek="+document.getElementById("privatekeyval").value;
var url="http://www.remoteapiserver.com/example_api/example_adcpatchaapi.php?"+data;
alert(url);
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
if (http_request.readyState == 4){
alert(http_request.responseText+"#"); // showing only # //
my_JSON_object = JSON.parse( http_request.responseText );
}
};
http_request.send(null);
}
</script>
I was as asked my question as per comment i read Json and writing above code in my php page.But still this is giving problem.I am not getting fetched dada from remote server.I am getting only "#" in alert box.
I highly recommend a JavaScript Framework like jQuery for this kind of stuff. It definitely makes this a lot easier. jQuery lets you do cross-domain requests, if you use JSONP (take a look at the docs). The code would look something like this:
$.getJSON(yourUrlGoesHere, function(data) { // ready callback
// data is an object; no need to parse it manually.
});
Sometimes it't better use some library:
JQuery or Moootools: http://mootools.net/docs/core/Request/Request.JSON
Implement this in native JS is difficulty if we want use it in all browsers ;)