I'm building a Django application and am trying to integrate JSON, but I'm having some issues. Django is generating the feed, which is here: http://www.crowdpoint.org/session/1/activeCheck
Here is the JQuery I'm using to pull down the feed. The problem is that neither of the alerts fire, so I don't think the code is working.
$(document).ready(function() {
$.getJSON('http://www.crowdpoint.org/session/1/activeCheck', function(data) {
alert('Test 1')
$.each(data, function(key, val) {
alert('Test 2');
});
});
It's probably a same origin policy violation. If the JS and the JSON resource are on the same domain, you should be using a local path not a fully qualified URI. For example...
instead of this
$.getJSON('http://www.crowdpoint.org/session/1/activeCheck' ...
use this
$.getJSON('/session/1/activeCheck' ...
My guess is you're accessing the originating URL on http://crowdpoint.org/ or something else that isn't exactly http://www.crowdpoint.org/
If the script and resource are on different domains, you'll need to use JSONP which would involve some changes to the way your service responds.
you miss ; in the third line....
Related
I am building a webpage for learning. Actually doing the page is the main goal, if it works well it would only be a bonus since i will most likely be the only person using it.
That being said i am using Angular Objects that hold a lot of informations, like:
Semester - Subcategory - Question - List of answers as objects with "true"/ "false" properties for multi choice and the answer itself ect.
Since i will be doing the whole sorting / filtering with angular i wonder if i really need SQL or if a XML file would be superior.
With SQL saving is my main issue here. PHP seems to butcher arrays into a string with the value "array". If i use json_encode it saves correctly, but on GET it stops working since i have to rebuild the whole data structure with " and ' about everywhere.
With XML it really looks like angular just is not build for that. I have found some outdated tutorials that did not even have a working example.
So i guess my question here is:
Do i either go for SQL, putting up with multiple tables. Splitting my objects into several columns with optional values all over the place, while also rebuilding the whole thing on load?
Or do i use XML, since i would only use the DB to GET the whole thing anyways?
Both approaches have been tested by me and work, somewhat. Both would need quite a lot of further digging, reading and trying. I don't have the spare time to do both routes. Which one is the better one to go for in this particular use case?
This is ofcourse a personal preference but I always try to avoid XML. The JSON format is alot lean and meaner and it's way easier to work with in web applications.
In fact I would suggest to start with some static JSON files until you're finished with giving your website some structure. You can generate them manually, use some generator tools (like http://www.mockaroo.com/) or build them by using some simple javascript (JSON.stringify is your friend). You can then use this data quite easily by using the $http service:
$http.get('my-data.json')
.then(function(response) {
$scope.myData = response.data;
});
This is actually the approach my teams take when building large enterprise applications. We mock all data resources and replace them with the real thing when we (or the customer) are happy with the progress.
Using a JSON-File should be sufficient. You can store all the needed objects in it and change it easily. With the following code you can load the data within JavaScript
function loadJSON(path, success, error) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSONH.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
usage
loadJSON('data.json',//relative path
function (data) {//success function
$scope.questions = question;
$scope.$apply();
},
function (xhr) {//error function
console.error(xhr);
}
);
I've been researching this and cannot find or understand some of the solutions so i'm hoping to get some help here. I'm using Asp.net and building an application that needs to use a bible api. I like the two listed in the question. Every time I call esvapi it comes back successful, but I cannot view the data. I get an error in the console.
XMLHttpRequest cannot load http://www.esvapi.org/v2/rest`/passageQuery?key=8834092f0c58fcda&passage=James2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:59324' is therefore not allowed access.`
I've seen other with this error and I have questions.
If I'm understanding this correct I get this because the server is preventing me from seeing the data for security purposes. Maybe even the browser( this is not just a chrome issue) problem. So if I need to add a info to the response header from Angularjs to stop this how is that done. Anyone with experience?
Would I need to contact anyone to be able to prevent the server from responding this way...I doubt this, but thought I would ask. I already have valid api key.
the bible.org website api key is confusing to apply to my code. on esvapi i just add a header with key: "keypass" and I only have the CORS issue. But with bible.org I can't figure out how to implement the api key and password. see below... Do I say token:key: username. If i put the api in the browser I get a popup to add username and password. the username is my key and the password is ignored. I tried putting in username as key, but that didn't cut it. Regardless I need to fix the CORS issue and add info to response headers to see response data.
$scope.search = function() {
return $http.get("http://www.esvapi.org/v2/rest/passageQuery?&passage=" + $scope.bo + $scope.chap, {
headers: {
"key?token?orusername?": "",
///thought i saw someone do this...don't know if this is right
"Access-Control-Expose-Headers": "Content-Disposition",
}
}).success(function (data, status, headers, config) {
$scope.book = data.Book;
$scope.chapter = data.Chapter;
$scope.output = data.Output;
}).error(function (data, status, headers, config) {
$scope.message = "Oops... something went wrong";
});
Any input would be helpful. Thanks!
I actually have a bible api working...just a version that I don't like and there is not another version on that webites api.
Change the get $http.get call to $http.jsonp and hope it works. You're using cross-site scripting. Sometimes you can get away with a JSONP call in these cases and sometimes you can't.
I'm trying to get dojo to show Json data that comes from a remote web service. I need to be clear though - the web server hosting the html/dojo page I access isn't the same server as the one that's running the web service that returns the json data - the web service server just can't serve html pages reliably (don't ask!!).
As a test I move the page into the same web server as the web service and the below works. As soon as I move it back so that the html/dojo is served from Apache (//myhost.nodomain:82 say) and the web service sending the json is "{target:http://myhost.nodomain:8181}", then it stops working.
I've used FFox to look at the network & I see the web service being called ok, the json data is returned too & looks correct (I know it is from the previous test), but the fields are no longer set. I've tried this with DataGrid and the plain page below with the same effects.
Am I tripping up over something obvious???
Thanks
require([
"dojo/store/JsonRest",
"dojo/store/Memory",
"dojo/store/Cache",
"dojox/grid/DataGrid",
"dojo/data/ObjectStore",
"dojo/query",
"dojo/domReady!"
],
function(JsonRest, Memory, Cache, DataGrid, ObjectStore, query) {
var myStore, dataStore, grid;
myStore = JsonRest(
{
target: "http://localhost:8181/ws/job/definition/",
idProperty: "JOB_NAME"
}
);
myStore.query("JOB00001"
).then(function(results) {
var theJobDef = results[0];
dojo.byId("JOB_NAME").innerHTML = theJobDef.JOB_NAME;
dojo.byId("SCHEDULED_DAYS").innerHTML = theJobDef.SCHEDULED_DAYS;
});
}
);
Its true what Frans said about the cross domain restriction but dojo has this link to work around the problem.
require(["dojo/request/iframe"], function(iframe){
iframe("something.xml", {
handleAs: "json"
}).then(function(xmldoc){
// Do something with the XML document
}, function(err){
// Handle the error condition
});
// Progress events are not supported using the iframe provider
});
you can simply use this and the returned data can be inserted into a store and then into the grid.
Are you familiar with the Same Origin Policy:
http://en.wikipedia.org/wiki/Same-origin_policy
Basically it restricts websites to do AJAX requests to other domains than the html page was loaded from. Common solutions to overcome this are CORS and JSON-P. However, remember that these restrictions are made for security reasons.
I have a link which is supposed to download a file, whilst simultaneously sending data to a PHP script via Ajax to update a database. The HTML for the link is:
<a class="rel_link" href="document.docx">Download</a>
And the jquery code is:
$("#downloadtable a").click(function(){
$.ajax({
url: "download.php",
type: "POST",
data: {dlname: dlname, dlaccount: dlaccount, dlmodule: dlmodule, dlemail: dlemail, dlsub: dlsub, dlpath: dlpath},
success: function(data){
$("#die2").detach();
}
});
});
Unfortunately the two don't seem to work simultaneously. If the jQuery is disabled, the document downloads perfectly. If the jQuery is enabled and the href attribute is set to href="#"', the jQuery works and the data is written to the database. However, if jQuery is enabled and the href is set tohref="document.docx"`, the file downloads but the data does not get passed to the database. The only error message I'm getting on the console is:
Resource interpreted as Document but transferred with MIME type application/vnd.openxmlformats-officedocument.wordprocessingml.document: "http://www.mysite.org.uk/downloads/document.docx".
Can anyone shed any light on how to simultaneously download a document and write to the database via Ajax?
Many thanks
If you switch the href to point to a php, you problem might be solved.
Then you can write into database, and initiate the download with the appropriate header() calls.
Look on Example#1:
http://php.net/manual/en/function.header.php
In my wordpress plugin I need to have a JSON option to load, using jquery, info about a custom post type. This jquery call will come in a page where all users should see it.
as far as i understand from the codex I should have a function:
function my_json_returning_function(){
// get json objects here
echo $json;
die();
}
As well as the actions:
add_action('wp_ajax_my_json_action', 'my_json_returning_function');
add_action('wp_ajax_nopriv_my_json_action', 'my_json_returning_function');
All in my plugin file.
then something like:
jQuery(document).ready(function($) {
var data = {
action: 'my_json_action',
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(<?php echo admin_url('admin-ajax.php');?>, data, function(response) {
alert('Got this from the server: ' + response);
});
});
should call the function in question.
My real question is where i should place all the different parts - and if something is missing.
The php function and the actions hooks go into the plugin file. But the javascript I am more confused about. I want to put it in the plugin javascript file, but since i have to fetch the admin url using php that becomes a problem.
Also how do I make sure that the script is only called if in a certain page? Are there more hooks and filters I should be comfortable with? Or is it possible to load it using wp_enqueue_script when executing a shortcode on that page, or is that to late, as I would seem it needs to be loaded in the header.
A lot of questions, but I hope you understand the basis of my problem - I have a hard time placing the code in the right places in the wordpress structure.
EDIT:
Calling echo admin_url('admin-ajax.php'); is not, at least in my eyes the most elegant way of doing it. I'd rather have a json API, with its seperate url, and calling it in the ajax call. How would I go about setting up a page in wordpress that only returns a json object?
What you have above is partially correct.
when using the call to admin-ajax.php, you have in the comments from the wordpress codex page is
// since 2.8 ajaxurl is always defined in the admin header
// and points to admin-ajax.php
this is just it... use the javascript variable 'ajaxurl' in place of the php call..
so it would look like this
jQuery(document).ready(function($) {
var data = {
action: 'my_json_action',
};
// since 2.8 ajaxurl
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
that should be you.. just place all your functions inside your main plugin file.
when wordpress loads it will produce a variable called ajaxurl that you can then use in your scripts.. :)