I have a class, and an interface in a plugin that I’m building, this interface needs access to functions to list the worpress categories. How to include the files needed to use native wordpress functions. Since the request is made to this interface by ajax. Any Ideas?
this.RequestVideos = function(){
var dados = {};
dados.KeywordUrl = escape($('#termo_pesquisa').val());
dados.categoria = $('#categorias').val();
dados.ordenacao = 'sponsor';
dados.host = Importer.GetSponsors();
dados.duracao = $('#duracao').val();
$.get('/wp-content/plugins/mega-importer/class/Importer.interface.php',dados,function(resposta, status){
Importer.EsconderPainelImportacao();
$('#videos_search').html(resposta);
$('.duracao').mask('00:00:00');
});
}
I need to have access within my Importer.interface.php the native functions of wordpress to be able to retrieve from the database a list of available categories
Thank you any advanced!
Update, Plano B (get all categories e ids the option select existent in my page e send to importer.interface.php)
Wordpress causes me an absurd frustration. Why not to any separation between html, javascript, php, and database. Everything is totally mixed up like a big trash. I spent 20 years of my time as a programmer and a lot of them getting away from writing wordpress plugins. At the end if you still want a documentation with examples of functioning, you will encounter text all in English where the language barrier will disrupt the total understanding and the worst without any functional example that clarifies your doubt. Thank you for your work but I'm going to Plan B creative.
this.GetAllCategorias = function(){
var obj = [];
var ids = new Array();
var labels = new Array();
$("#categorias option").each(function(){
ids.push($(this).val());
labels.push($(this).text());
});
obj.push(ids.join());
obj.push(labels.join());
return JSON.stringify(obj);
}
Related
I am becoming more and more familiar with jQuery, however, I haven't been able to figure this out.
I have a page which collects the data and sends the data to a processing file through jQuery. Here is the Code...
$( "#start_it" ).click(function(){
var url = 'grunt/process.php';
var keywords = $("#keywords").val();
var providers = $('input[name="providers"]:checked').map(function (){return this.value;}).get().join(",");
var networks = $('input[name="networks"]:checked').map(function (){return this.value;}).get().join(",");
var ex_ct = $("#ex_ct").val();
var list_type = $("#list_type").val();
var shuffle = $("#shuffle").val();
var postit = $.post( url, {
keywords:keywords,
providers:providers,
networks:networks,
ex_ct:ex_ct,
list_type:list_type,
shuffle:shuffle
});
postit.done(function( data ) {alert(data);});
});
On the process.php it loops through each provider and within the provider loop it loops through each network. What I would like to do is to be able to show progress being made to the user who is on the collection page while process.php is processing behind the scene at the start of every loop. here is the code:
foreach($providers as $provider){
$pros = explode(',',$provider); foreach($pros as $pro){
// I WANT TO BE ABLE TO UPDATE A DIV ON THE
// COLLECTION PAGE TO TELL THEM WHICH PROVIDER
// THE SCRIPT IS PROCESSING HERE
foreach($networks as $network){
$nets = explode(',',$network); foreach($nets as $net){
// I WANT TO BE ABLE TO UPDATE A DIV ON THE
// COLLECTION PAGE TO TELL THEM WHICH NETWORK
// THE SCRIPT IS PROCESSING HERE
} # $nets as $net
} # $networks as $network
} # $pros as $pro
} # $providers as $provider
I have search both the internet and Stack but I guess my queries have not been clear as the returns have been far different from the desired information.
Any assistance would be greatly appreciated.
Thanks in advance, Pete
In order to indicate progress, you would need a server response updating you incrementally.
It's not impossible but depending on the data you're sending, it's not worth it. Server calls and responses are costly and you should want to minimise them so unless you are uploading a lot of data (like a video or perhaps audio file) it's better not to keep hitting the server.
To solve this people typically use spinners (which indicate indefinite progress).
So I've finally made some progress on my gallery site through a lot of help from everyone here, so thanks. Now I have one last, hopefully very easy question. To begin, here's the scenario:
Since I'm new to Javascript I'm trying to learn javascript BRFORE I delve into jquery so I'm trying to do everything in (I believe the term is) vanilla javascript. Without going into all the code, I've made a gallery for my artwork that has a thumb slider at the top of the page and a field where the selected artwork (including additional views, description, title, etc) will display. Rather than take on multi arrays right now I've built a page called 'gallery/php' that house all of the prebuilt divs that will be called into the field (titled 'generic'). Using innerHTML, I am making a simple call so that when the desired thumbnail is selected it calls the corresponding div by id and writes it in place of the 'generic' div.
Simple enough...
The problem is that I have about 40 of these and if I do a php include and hide the include in a hidden div while the artwork doesn't display it takes FOREVER to load the page and this seems like a very bad idea. What I would like to do is modify the function I am using right now so that instead of calling the id on the current page it will know which external page to reference and which div (based on id) to pull and populate the 'generic' div with. The script currently looks like this:
function changeDiv(art) {
viewer = document.getElementById('generic'),
targetInfo = document.getElementById(art);
viewer.innerHTML = targetInfo.innerHTML;
}
What I would like to do is (disregarding syntax):
function changeDiv(art) {
viewer = document.getElementById('generic'),
targetInfo = ***src = gallery.php, #(art);***
viewer.innerHTML = targetInfo.innerHTML;
}
The only thing I've seen that is similar to what I want to do is .load() in jquery but I don't know how to translate that back to javascript.
Ok! Here goes my attempt. Please note that while this should probably be vetted through an AJAX library (like jQuery), that's not what the OP asked for.
**Also, I didn't know the gallery.php set up so I went for my best attempt.
**Also I know that this is horrible and has no validation or anything else good about it, but this is more of a proof of concept. (Tracer code for those Pragmatic Programmers)
Assuming you have a gallery.php set up as the following:
<?php
$pull = $_GET["pull"];
$gallery[0] = "<div>Your art work img tags here</div>";
$gallery[1] = "<div>Some more art work</div>";
//Pull from the changeDiv parameter in the JavaScript below.
echo $gallery[$pull];
?>
We'll go with some JavaScript like the following:
var changeDiv = function(pull) {
//Pull parameter indicates an array
//index within the gallery.php $gallery array
var ajaxObj;
//Our AJAX objet shall be declared
if(window.XMLHttpRequest) {
ajaxObj = new XMLHttpRequest();
}
else {
ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
}
//When the ajaxObj changes it's ready
//state, do this stuff below
ajaxObj.onreadystatechange = function() {
//But only if the ready state is
//really ready and the status is good to go
if(ajaxObj.readyState==4 && ajaxObj.status==200) {
var response = this.responseText;
document.getElementById("viewer").innerHTML=response;
}
}
//Open the async connection to
//gallery.php and send your GET
//global (pull)
ajaxObj.open("GET","gallery.php?pull="+pull,true);
//Send it and pray
ajaxObj.send();
}
http://www.smashingmagazine.com/2008/10/16/50-excellent-ajax-tutorials/ - Some tutorial listings for AJAX
I am using AngularJS 1.0, PHP, and mysql with localhost on my Mac.
I have a very simple mysql database: "cats". It has one table called "kittens". The table has two columns, "id" and "name". There are three kittens in the database with names Larry, Curly, and Moe.
Now, I have some simple PHP code which opens the dbase, gets the three records, and returns them in JSON like this:
[{"id":"1","name":"Larry"},{"id":"2","name":"Curly"},{"id":"3","name":"Moe"}]
I used the latest angular-seed and set up a project in Eclipse. In app.js I wrote this:
'use strict';
angular.module('Cats', ['ngResource','Cats.filters', 'Cats.services', 'Cats.directives'])
I put my PHP code in the services folder and named it "index.php". If I navigate to that services/index.php in my browser using localhost on the Mac, I get back the JSON above. So far everything is cool.
Now - ALL I WANT TO DO (!famous last words ;) is connect to the PHP service I have and display the contents of that Cats table on my main index page using my AngularJS project. Plain old text, no tables, just bind to the available resource and display it.
I have tried all manner of demos online (many are out of date). Can anyone show me one simple, current way to do this? For the life of me I have all kinds of AngularJS demos working but none of them does this simple task in a way I can understand.
Thank you in advance.
This should also work. It's significantly fewer lines of code, but note that any error handling has been removed:
function FetchCtrl($scope, $resource) {
var services = $resource('../services/index.php');
$scope.data = services.query();
}
FetchCtrl.$inject = ['$scope', '$resource'];
Normally I would have used the built in .get() method on the $resouce but your response is in the form of an Array, which .query() supports by default.
You can find the documentation on $resource here
OK. Solved it. First, copied and added a controller I found in one of the examples:
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url='../services/index.php';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
Then, I added a route controller to my module:
var module = angular.module('Cats', ['ngResource','Cats.filters', 'Cats.services', 'Cats.directives'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/main', {templateUrl: 'partials/partial1.html', controller: MyCtrl1});
Finally, on that partial1.htm page, I added this:
<div ng-init="fetch()">
{{data}}
</div>
Now when I go to that page in the browser, I can see the entire database dumped out in JSON. Ahhhh. Clearly there are many more sophisticated things to try, etc etc but I needed this simple result so I could be certain that I did in fact have a model arriving when summoned. Angular dies silently in many cases, so a visible result was quite helpful.
One gotcha: be careful that the php file is executable by more than yourself as user. I don't know the name of the user that AngularJS implements but I had to chmod 644 index.php so the app could use it.
I hope that helps someone.
Hello stackoverflow developer,
First of all, sorry if I couldn't find a solution, but I've been trying for a while now.
I'm not sure if my approach is the best one, so, if there's an alternative to AJAX and/JSON, please feel free to suggest it.
I'm creating a tourist guide website where registered users will include their resorts, restaurants and tourist attractions according to region and state. I'm using Joomla! and Seblod for this (with some custom PHP, MySQL, Javascript and AJAX). Since I don't want to manually create 27 dynamic selects, I've been trying selecting the list of registered beaches (to which resorts and tourist attractions must be related to) with PHP/AJAX/JSON/JQuery.
Everything works except populating the beach list, and I don't know what the problem is. I've tried multiple ways to append, create or add the options but nothing happens.
The PHP/JSON result is :
`
[{"id":"17","title":"Porto+de+Galinhas"},{"id":"18","title":"Serrambi"},{"id":"19","title":"Tamandar%E9"}]
`
It's the result of this PHP script:
`
if($_GET['q'] == 'beaches'){
$praiaSQL = sprintf("SELECT * FROM vp_content AS c LEFT JOIN vp_cck_store_item_content AS v ON c.id = v.id WHERE c.catid = 10 AND v.cck = 'praia' AND v.venue_state = '%s' ORDER BY c.title ASC;", $_GET['s']);
$query = mysqli_query($connection, $praiaSQL);
$praia = array();
while($results = mysqli_fetch_assoc($query)){
array_push($praia, array('id' => $results['id'], 'title' => urlencode($results['title'])));
}
echo json_encode($praia);
}
`
I also need a solution to handle accented characters. I'm trying urlencode here and decode in the JQuery, but may be the problem. When I left it as the original data, when there were accented characters the result item was empty.
This is the relevant JQuery that handles the result (where x = the select and u = the URL to get the AJAX JSON result - I've commented where the problem is in the code):
`
function setBeachList(x,u){
var theDiv = "#cck1r_" + x;
var theSelect = "#" + x;
$j(theSelect).children("option:not(:first)").remove();
$j.ajax({
url: u,
contentType: "application/json;charset=UTF-8",
success: function(data){
if(data.length){
/****
This is where I'm stuck, as I can't find a way to make sure the
data is actually being treated/handled.
I've tried alerts and all sorts of other options to populate the
select.
I know it's being called because the before: and after: functions
are working.
*****/
/*
$j.each(data, function(k, v){
var o = new Option();
var newTitle = urldecode(v.title);
$j(o).html(newTitle).val(v.id);
$j(theSelect).append(o);
});
*/
var htm = '';
for (var i = 0; i '+urldecode(data[i].title)+'';
}
$j(theSelect).html(htm);
}
},
beforeSend: function(){
$j(theDiv).hide();
},
complete: function(){
$j(theDiv).show();
},
dataType: 'json',
});
}
`
Thank you for the time and patience, I'm not an expert at any of this (not exactly a newbie, but close...).
urldecode is not a javascript function,
you can use decodeURIComponent instead of it.
it's working when you change it,
http://jsfiddle.net/MzMPK/1/
UPDATE:
I think your problem is about trying to encode accented chars, It should work without encoding them, if your all encodings are set as UTF-8.
This is a common JSON parsing silent error.
If the JSON is not well formatted, the ajax request will fail silently.
The second most common cause of this problem is the encoding. Make sure you are using UTF-8 in the page you're calling the AJAX and on the script that returns the data.
Your problem with accented data can be resolved by not encoding the data on the server side, thus not needing to unenconde on the client side.
To answer my own question:
Since I'm not and AJAX/JSON expert, I don't know if it's the expected behavior, but the responding page, which generates the AJAX result, cannot have different data than the one expected. Since I had left a regions' output, the requesting page had problems dealing with it somehow. Once I removed the unnecessary data, the select list got updated fine.
That was something I forgot to mention in my post, because I assumed that it was fine to have more than one result in the page. Using Firebug to check the code, the request was being brought fine.
Thank you all for your time, and sorry for the inconvenience...
I had to add htmlentities to the responding page, as accents returned null, although I explicitly have UTF-8 on every file...
I'm building a dynamic pie chart to show election results using the Google Visualization API and jQuery, and I had it (sort of) working on my local machine, and wanted to get some feedback, so uploaded it to an external server, now everything I try to load gives me a "No Data" error.
I've got two files, one which gets data from a database and converts it to JSON, and one which displays the visualization, depending on what areas are checked. You can see it here:
http://www2.lichfielddc.gov.uk/sandbox/pie.php?electionid=14
Any ideas where I'm going wrong?
Cheers
Think I may be on to something.
I downloaded it and tested it locally and as you said it works fine. However, in the datasource i was using (data.php) if I put a delay (sleep(1)) it stopped working. I think it was because you were drawing the chart out of the ajax success callback.
Try this:
function drawVisualization() {
$('.poll').click(function() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Party');
data.addColumn('number', 'Votes');
var polls = [];
$('.poll:checked').each(function(){
polls.push(this.value);
});
polls.join(",");
url = "http://www2.lichfielddc.gov.uk/sandbox/piedata.php?pollid=" + polls;
$.getJSON(url, function(d) {
data.addRows(d.length);
var items = [];
var num = 0;
$.each(d, function(i, o) {
console.log(o);
data.setValue(num, 0, o['party']);
data.setValue(num, 1, o['votes']);
num++;
});
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data);
});
});
Stepping through the code: By the time you call the draw() method, the object 'data' has no data in it. This is likely because the modifications to the data object are not in the same scope.
I agree with Tribal that it's a timing issue, because the live version does work sometimes. There's a couple of other lurking bugs, that aren't behind the presenting issue, but ...
polls.join(",");
url = "http://www2.lichfielddc.gov.uk/sandbox/piedata.php?pollid=" + polls;
polls.join() returns a string, it doesn't do the join in-situ. And url isn't being declared as a local variable