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.. :)
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);
}
);
In my application I have dynamic field sets on what is otherwise the same form. I can load them from the server as javascript includes and that works OK.
However, it would be much better to be able to load them from a separate API.
$.getJSON() provides a good way to load the json but I have not found the right place to do this. Clearly it needs to be completed before the compile step begins.
I see there is a fieldTransform facility in formly. Could this be used to transform vm.fields from an empty object to whatever comes in from the API?
If so how would I do that?
Thx. Paul
There is an example on the website that does exactly what you're asking about. It uses $timeout to simulate an async operation to load the field configuration, but you could just as easily use angular's own $http to get the json from the server. It hides the form behind an ng-if and only shows the form when the fields return (when ng-if resolves to true, it compile the template).
Thx #kent
OK, so we need to replace the getFields() promise with this
function getFields() {
return $http.get('fields-demo.json', {headers:{'Cache-Control':'no-cache'}});
}
This returns data.fields so in vm.loadingData we say
vm.fields = result[0].data;
Seems to work for OK for me.
When testing I noticed that you have to make sure there is nothing wrong with your json such as using a field type you haven't defined. In that case the resulting error message is not very clear.
Furthermore you need to deal with the situation where the source of the data is unavailable. I tried this:
function getFields() {
console.log('getting',fields_url);
return $http.get(fields_url, {headers: {'Cache-Control':'no-cache'}}).
error(function() {
alert("can't get fields from server");
//return new Promise({status:'fields server access error'}); //??
});
.. which does at least throw the alert. However, I'm not sure how to replace the promise so as to propagate the error back to the caller.
Paul
I am trying to read a JSON file with Meteor. I've seen various answers on stackoverflow but cannot seem to get them to work. I have tried this one which basically says:
Create a file called private/test.json with the following contents:
[{"id":1,"text":"foo"},{"id":2,"text":"bar"}]
Read the file contents when the server starts (server/start.js):
Meteor.startup(function() {
console.log(JSON.parse(Assets.getText('test.json')));
});
However this seemingly very simple example does not log anything to the console. If I trye to store it in a variable instead on console.logging it and then displaying it client side I get
Uncaught ReferenceError: myjson is not defined
where myjson was the variable I stored it in. I have tried reading the JSON client side
Template.hello.events({
'click input': function () {
myjson = JSON.parse(Assets.getText("myfile.json"));
console.log("myjson")
});
}
Which results in:
Uncaught ReferenceError: Assets is not defined
If have tried all of the options described here: Importing a JSON file in Meteor with more or less the same outcome.
Hope someone can help me out
As per the docs, Assets.getText is only available on the server as it's designed to read data in the private directory, to which clients should not have access (thus the name).
If you want to deliver this information to the client, you have two options:
Use Assets.getText exactly as you have done, but inside a method on the server, and call this method from the client to return the results. This seems like the best option to me as you're rationing access to your data via the method, rather than making it completely public.
Put it in the public folder instead and use something like jQuery.getJSON() to read it. This isn't something I've ever done, so I can't provide any further advice, but it looks pretty straightforward.
The server method is OK, just remove the extra semi-colon(;). You need a little more in the client call. The JSON data comes from the callback.
Use this in your click event:
if (typeof console !== 'undefined'){
console.log("You're calling readit");
Meteor.call('readit',function(err,response){
console.log(response);
});
}
Meteor!
Before I used Codeigniter I had a page show certain html as long as the url had no get parameters and then have some of the html be replaced by another as soon as something like this is set in the url:
localhost/signup.php?success
Now my question is, what is the best way to do this in Codeigniter? Would I have to use one of those parameters on the controller's function (which I still can't get my head around)? And if so, how? Or if I just had php logic in the view like I used to do in plain PHP, what would I check for if not a get parameter? Thanks.
Too many ways to achieve this certain thing.
routes.php
extending controller and using constructor so you apply rules for every extended controller
flashdata
Before you start please read up on frameworks watch some video tutorials on how to make simple blog system etc. I myself wouldn't just jump in to concept, study up.
I mentioned flashdata and that is how you do things done (success, alert, warning bars).
By default, GET parameters are not enabled or useful in codeigniter, but URI segments work the same way. So...
If you had a controller called, signup.php and a function inside it called success, you could link to that with:
localhost/signup/success
then if you loaded the URL helper, which I always do in config/autoload.php or just with:
$this->load->helper('url');
You could say:
if($this->uri->segment(2) == 'success') {
//Show success message or load a view for it...
}else {
//The second URI segment is NOT 'success' so do something else...
}
But... codeigniter is just a framework for PHP. If it's possible in PHP, it's possible in codeigniter. You can simply go into the config/config.php file and enable query strings, but I would strongly suggest using URI segments and reading up on them as well as the URL helper.
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....