drupal 7 CORS localhost ajax request - html

im trying to pull data from drupal 7 website from a local files inside
http://example.com:8888/test/test.html
im using this Ajax code with html request since i have tried json and also the website prevents me from pulling even i have added
<?php
header('Access-Control-Allow-Origin: *');
?>
code to pull the data , but no result:
$.ajax(
{
// The link we are accessing.
url: "http://horizon-websolutions.com",
// The type of request.
type: "get",
// The type of data that is getting returned.
dataType: "html",
error: function(){
alert("error");
// Load the content in to the page.
$("#output").html( "<p>Page Not Found!!</p>" );
},
beforeSend: function(){
alert("not yet"); },
complete: function(){
alert("done"); },
success: function( strData ){
alert("success");
// Load the content in to the page.
$("#output").html( strData );
}
}
);
// Prevent default click.
return( false );
please help my telling the website accept my localhost request to pull data from the server . the same code tested on a pure php page and its working fine .

Not sure how secure this would be but one way to solve it is to enable CORS.
For Drupal 7 (would be analogous to Drupal 6) so you need to download and install the CORS module,
enable the module under Modules,
go to the Drupal config (Configuration on Drupal 7 main dashboard top navigator),
search for CORS. Click,
give the path for the links you wish to access. Examples are given on that page of how to put in new links.
Hope this helps.

Related

Unable to get data from json file on local server (port: 3000)

I am hosting an html page on localhost:8888 with a MAMP Server and I am trying to get some data from a JSON file which I am hosting on localhost:3000 on the 'categories' route. Firstly, I wanted to know is this possible ?
If it is not possible, is it possible for me to route the JSON data to another site. If it is possible, here is the script I have embedded in my HTML
<script>
$(document).ready(function(){
setInterval(test,500);
console.log("document ready");
alert('page ready');
});
function test() {
$.ajax({
url:"HTTP://localhost:3000/categories",
dataType: 'jsonp',
success: function(json){
$("#Address1").html(json[0]["id"]);;
}
});
}
</script>
Here is the JSON file :
[{"_id":"5624711f1a530785d511e747","__v":0,"name":"Beverages","description":"Soft drinks, coffees, teas, beers, and ales","created":"2015-10-19T04:27:11.649Z"}]
Currently, It doesn't display any data. I have tried pure JS instead of jquery but it doesn't help.
This is what I got in the Chrome Console : GET localhost:3000/categories?callback=jQuery1113012827125121839345_1445236000644&_=‌​1445236000645 net::ERR_UNKNOWN_URL_SCHEME
Added http:// - does not make a difference

Uploading an HTML file via HTML5

I have this weird issue that Im not sure if its normal or not.. Im sure its not
I have a drag and drop area that I can upload any file and it works like a charm.
EXCEPT...
I cant upload any .html or .htm files with it. I can take an html file and rename it to .jpg and it works.
This is my piece of code:
xhr = new XMLHttpRequest()
xhr.open 'PUT', "#{tvr.api.url}/transfer/#{userprofile.UserLink.LinkID}/#{userprofile.UserLink.UserName}/#{channelid}/#{filename}"
xhr.upload.addEventListener "progress", (event, filename) =>
window.Appbusy = true
$($(".file-status-#{uid}").find("span")).text("(#{((event.loaded/event.totalSize)*100).toFixed(2)}%)")
,false
xhr.onreadystatechange = (aEvt) ->
if xhr.readyState is 4
if xhr.status is not 200
$(".notification").remove()
notification("The server returned an error uploading the file. Please try again.", 'error')
It even shows that upload progress then at 100% when it needs to push it the server it just fails with Bad Request. (the server never gets any request)
It works if the HTML file has 0 content! Why I do not know
UPDATE:
After some playing around I see that the request works when setting the Content-Type to text/plain:
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
As soon as I change to text/html it does not work if the file has any content:
xhr.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
Could this be a bug?
I sent this as a possible XML bug
Use jQuery .ajax() instead. Specify type:'PUT' for an upload. For example, using your URL:
$.ajax({
type:"PUT"
url:"#{tvr.api.url}/transfer/#{userprofile.UserLink.LinkID}/#{userprofile.UserLink.UserName}/#{channelid}/#{filename}"
success: function(){
alert('success');
}
});

Jquery mobile page List-view content not getting updated

I am new to phonegap jquery mobile app. In my app i have some pages and each page gets its content as a list-view using json. Now content will load only once i.e when we click on the page for the first time and that's the same case for every other page. Later even if the json gets updated it won't be shown in the list. I can notice the updated list-view only after i logout from the app. and then again i login to the app. i.e content will get updated only after i restart the session!
Take a look at this examples, one example uses xml to create a listview and other one uses a JSON file:
XML: http://jsfiddle.net/Gajotres/AzXdT/
JSON: http://jsfiddle.net/Gajotres/8uac7/
You are probably loading it in a wrong page event, if possible always use pagebeforeshow like this:
$('#index').live('pagebeforeshow',function(e,data){
$.ajax({url: "http://api.themoviedb.org/2.1/Movie.search/en/json/23afca60ebf72f8d88cdcae2c4f31866/The Goonies",
dataType: "jsonp",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
});
Also take a look at my other article, it will give you a better understanding of jQM page events flow: https://stackoverflow.com/a/14010308/1848600

How to show html files with modal.open using jquery?

Currently i use a fine working code for opening a modal with Jquery :
$(document).ready(function(){
$("span.ico-detail").click(function(){
modal.open({content: "View detail of " + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
And now the problem is : How can I use modal.open to open a HTML file named "view.html", which contaning the string of "View detail of "?
What should I change the content : "xxx" with, so I can open the HTML file (view.html) and join it with other text ?
Thanks before.
If the view.html is stored on a server and its content is static, then you can choose to preload the content of the file using ajax.
$(function () {
window.myAppNs = {
viewContent: null;
};
$.ajax({
url: 'view.html',
dataType: 'html',
type: 'GET'
}).done(function (resp) {
myAppNs.viewContent = resp;
});
$("span.ico-detail").click(function(){
modal.open({content: myAppNs.viewContent + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
I am creating a global variable myAppNs. This will hold all app related variables. The idea is not pollute the global namespace with unnecessary variables. There are better and safer ways to create a namespace. If that interests you, you can google for the same.
The ajax call preloads the content of the view.html and stores it in myAppNs.viewContent. The click handler reads that content from the variable.
There is a slight chance that the user can click the element before the ajax response is returned. If that's an issue, you can always move the namespace creation and ajax call out of document.ready and place it in the head section, immediately after referencing jquery. That ought to give the browser enough time to fetch the content before the dom is ready, but there is still that small possibility that the response might be delayed. If you need to ensure the user can click only if the data has been fetched, then bind the click handler inside the done callback of the ajax call.

Using jQuery.getJSON in Chrome Extension

I need to do a cross-domain request in a chrome extension. I know I can it via message passing but I'd rather stick to just jQuery idioms (so my javascript can also work as a <script src="">).
I do the normal:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
but in the error console I see:
Uncaught ReferenceError: jsonp1271044791817 is not defined
Is jQuery not inserting the callback function correctly into the document? What can I do to make this work?
(If I paste the code into a chrome console, it works fine, but if I put it as the page.js in an extension is when the problem appears.)
Alas, none of these worked, so I ended up doing the communication via the background.html.
background.html
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script>
function onRequest(request, sender, callback) {
if (request.action == 'getJSON') {
$.getJSON(request.url, callback);
}
}
chrome.extension.onRequest.addListener(onRequest);
</script>
javascripts/page.js
chrome_getJSON = function(url, callback) {
console.log("sending RPC");
chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}
$(function(){
// use chrome_getJSON instead of $.getJSON
});
If you specify "api.flickr.com" in your manifest.json file you will not need to use the JSONP callback, script injection style of cross domain request.
For example:
"permissions": ["http://api.flickr.com"],
This should work beautifully in you code. I would remove the querystring parameter "&jsoncallback" as there is no JSONP work needed.
The reason why your current code is not working is your code is injecting into pages DOM, content scripts have access to the DOM but no access to javascript context, so there is no method to call on callback.
My impressions it that this fails because the jQuery callback function is being created within the 'isolated world' of the Chrome extension and is inaccessible when the response comes back:
http://code.google.com/chrome/extensions/content_scripts.html#execution-environment
I'm using Prototype and jQuery for various reasons, but my quick fix should be easy to parse:
// Add the callback function to the page
s = new Element('script').update("function boom(e){console.log(e);}");
$$('body')[0].insert(s);
// Tell jQuery which method to call in the response
function shrink_link(oldLink, callback){
jQuery.ajax({
type: "POST",
url: "http://api.awe.sm/url.json",
data: {
v: 3,
url: oldLink,
key: "5c8b1a212434c2153c2f2c2f2c765a36140add243bf6eae876345f8fd11045d9",
tool: "mKU7uN",
channel: "twitter"
},
dataType: "jsonp",
jsonpCallback: callback
});
}
// And make it so.
shrink_link('http://www.google.com', "boom");
Alternatively you can try using the extension XHR capability:
http://code.google.com/chrome/extensions/xhr.html
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
}
}
xhr.send();
The syntax is a little off. There's no need for the callback( bit. This works flawlessly. Tested in the javascript console of Chrome on this StackOverflow page (which includes jQuery):
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
As many of you will know, Google Chrome doesn't support any of the handy GM_ functions at the moment.
As such, it is impossible to do cross site AJAX requests due to various sandbox restrictions (even using great tools like James Padolsey's Cross Domain Request Script)
I needed a way for users to know when my Greasemonkey script had been updated in Chrome (since Chrome doesn't do that either...). I came up with a solution which is documented here (and in use in my Lighthouse++ script) and worth a read for those of you wanting to version check your scripts:
http://blog.bandit.co.nz/post/1048347342/version-check-chrome-greasemonkey-script