Get current post ID in javascript - WordPress - javascript

I am making a plugin for wordpress. The plugin will add a tinymce on the edit post, and it will send the post_id to the database to do some identification later.
In my case, I am writing a javascript, which directory in wordpress\wp-content\plugins\facebook-api\js\shortcode-tinymce-button.js. And now I have no idea how I can get the post_Id in javascript.
Here is what I am doing:
user click the OK button will send the post_Id and the text box value to the database.
Here is my code:
(function() {
tinymce.PluginManager.add('facebook_api_tinymce', function( editor, url ) {
editor.addButton( 'facebook_api_tinymce',
{
title: 'Set friend condition',
text: 'Condition',
type: 'menubutton',
menu:
[
{
text: 'Friend',
onclick: function() {
editor.windowManager.open( {
body:[
{
type: 'textbox',
name: 'textboxName',
label: 'Set friend',
value: '20'
}
],onsubmit: function( e ) {
var $hi = "php echo get_the_ID();";
alert($hi);
$no_friend_e = parseInt(e.data.textboxName);
//Pass the value the PHP file, which is doing the database update.
jQuery.ajax({
url: 'http://localhost:8080/wordpress/wp-content/plugins/facebook-api/js/databaseConnection.php',
type: 'POST',
data: {functionname: 'updateDatabase', post_id: '1', no_friend: $no_friend_e},
error:function(data){ //When Can't call the PHP function
alert("failed");
console.log(data);
},
success: function(data) { //update data successful
alert("success");
console.log(data); // Inspect this in your console
}
});
}
});
function get_post_content(id){ //Didn't use
return document.getElementById("post-"+id).innerHTML;
}//you should probably use textContent/innerText but I am not going to get into that here
}
}
]
});
});
Thanks,

Related

How to get variable from javascript to php without form?

I'm trying to pass my topic variable from this javascript function to my php file faqs.php. I know you can do this with a form, however this function is called when clicking text on the html page. I've tried AJAX but it didn't work for me and I feel like there must be a simpler way.
getFaqs function:
function getFaqs(topicId, topic) {
$("#topic-container").html("");
//insert javascript to send 'topic' to php file here
$.getJSON("faqs.php", function(data) {
if(data == "") {
$("<div>", {class: "list-group-item", text: "Please add FAQs."}).appendTo($("#topic-container"));
}
$.each(data, function(faqId, faq){
$("<div>", {id: "faq" + faqId, class: "list-group-item", text: faq}).appendTo($("#topic-container"));
});
});
return false;
}
faqs.php:
<?php
header('Content-Type: application/json; charset=utf-8');
//insert some php to get 'topic' here
if(isset($_POST['topic'])){
$topic=$_POST['topic'];
$clean_topic = preg_replace('/\s+/', '', $topic);
}else{
echo json_encode("Please enter a topic!");
}
$musicalinstruments = array("Question1"=>"What is the best musical instrument in the world?", "Answer1"=>"The English concertina", "Question2"=>"How many double bass players does it take to change a light bulb?", "Answer2"=>"None, the piano player can do that with his left hand");
$programminglanguages = array("Question"=>"Why do programmers confuse halloween and christmas?", "Answer"=>"Because Oct 31 = Dec 25");
$varietiesofpizza = array("Question"=>"Should I eat more pizza?", "Answer"=>"Yes. Always.");
echo json_encode ($topic);
?>
Insert topic as GET variable in javascript
$.getJSON("faqs.php?topic=sometopic", function(data) {
And then read that GET variable in PHP
if(isset($_GET['topic'])){
$.getJSON makes a GET request while $.ajax is the main component to send and communicate with the server. Here's a rough code that would do this just fine.
$.ajax({
url: 'faqs.php',
type: 'POST',
dataType: 'json',
data: { topic: topics }, // topics is your topics varaible from the JS scope
success: function(data) {
if (data == "") {
$("<div>", {
class: "list-group-item",
text: "Please add FAQs."
}).appendTo($("#topic-container"));
}
$.each(data, function(faqId, faq) {
$("<div>", {
id: "faq" + faqId,
class: "list-group-item",
text: faq
}).appendTo($("#topic-container"));
});
},
error: function(xhr) {
console.log('error :(');
}
});
you can send it by url here is the code for it xmlhttp.open("GET", "phpFile.php?q=" + str, true);
xmlhttp.send();
where q is he variable which is used to access the value of perticular variable ,str in this case, in php file
If you want use POST:
$.post('test.php', { name: "Anna" }, function(response) {
// Do something with the request, data is JSON object.
}, 'json');
And read in test.php in POST variable.
$_POST['name'] // Anna

Javascript call PHP function

I am editing wordpress post template. And I want to call the PHP function in javascript, but my code doesn't work.
Here is what I want to do. When the user click the OK button, it should be showed a alert box when calling the PHP function success or failed.
Here is my js code:
(function() {
tinymce.PluginManager.add('facebook_api_tinymce', function( editor, url ) {
editor.addButton( 'facebook_api_tinymce',
{
title: 'Set friend condition',
text: 'Condition',
type: 'menubutton',
menu:
[
{
text: 'Friend',
onclick: function() {
editor.windowManager.open( {
body:[
{
type: 'textbox',
name: 'textboxName',
label: 'Set friend',
value: '20'
}
],onsubmit: function( e ) {
$.ajax({
url: 'databaseConnection.php',
type: 'GET',
data: {functionname: 'updateDatabase', post_id: 1, no_friend: 2},
error:function(){
alert("failed");
},
success: function(data) {
alert("success");
console.log(data); // Inspect this in your console
}
});
}
});
}
}
]
});
});
And here is my PHP code:
<?php
$post_id = 0;
$no_friend = 0;
//Check did it pass the functionName
if( !isset($_POST['functionname']))
$error = 'No function name!';
//Check did it pass the Post id
if( !isset($_POST['post_id']) )
$error = 'No function post_id!';
else {
$post_id = $_POST['post_id'];
}
//Check did it pass the no_friend
if( !isset($_POST['no_friend']) )
$error = 'No function no_friend!';
else{
$no_friend = $_POST['no_friend'];
}
//If no data are missed
if( !isset( $error) ) {
switch($_POST['functionname']) {
case 'updateDatabase':
updateDatabase(intval($post_id), intval($no_friend));
break;
default:
$error = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
function updateDatabase($post_id, $no_friend)
{
$ans = $post_id + $no_friend;
echo $ans;
}
echo $error;
It should show an alert box. What I am going wrong?
What do you get back from you Ajax call? So what does this
console.log(data); // Inspect this in your console
actually show? If it's a whole built up Wordpress page, then maybe your PHP functions work, but they are never executed. This might be due to .htaccess rewrites and such.
You are using Type:"GET" in ajax but you are trying to get value in php using POST
Just Change Your Type:"GET" to Type:"POST" in ajax or
Change POST to GET in php code

Jquery display message while php processing

I'm using jQuery ajax call to post process a form.
I want to display a loading message or image while the form is processed and when the action is completed to display a complete message.
How can I do it?
This is my jQuery code.
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
Before ajax function display your loader and inside the success function from your ajax hide it.
As you can see in my example i inserted $('.loader').show(); and $('.loader').hide();
$('.loader').show();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
$('.loader').hide();
}
});
According to the PHP docs:
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
You should take a look at : https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress
I think this will definitely help you out!
Display your message just before launching $.ajax();
And close it in the success (and error) callback functions.
example :
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
var dlg = $s('<div/>').text('your message').dialog();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
error:function() {
dlg.dialog('close');
},
success: function(data) {
dlg.dialog('close');
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
If you go through ajax section of jquery documentation you will notice some more method like success ie error, beforesend, complete etc. Here is the code snippet.
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
beforeSend : function(){
// load message or image
},
success: function(data) {
// write code as per requirement
},
complete : function(){
// load complete message where you previously added the message or image, as a result previous one will be overwritten
}
});

Another way to load remote data in Select2

I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.

Loading remote data only once with Select2

As the title suggests I would like to load remote data once only.
I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...
a solution can be found here:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Edit:
I might have misinterpreted your question. if you wish to load all data once, then use that is Select2, there is no built in functionality to do that.
Your suggestion to do a single query, and then use that stored data in Select2 would be the way to go.
This is for Select2 v4.0.3:
I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
This worked well for what I had in mind. Hope this helps people searching with the same question.
To load data once:
Assumptions:
You have a REST API endpoint at /services that serves a JSON array of objects
The array contains objects which have at least a "name" and "id" attribute. Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to store that array as the global 'services_raw'
First, our function to load the data and create the global 'services_raw' (AKA 'window.services_raw'):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
Second, our Select2 instantiation code which transforms our data into a format that Select2 can work with:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
Here's what the Select2 element in HTML should look like before your call the above functions:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI();
window.refreshServicesSelect();
Lastly, here's a JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we're just using ajax to populate the equivalent of window.pills in the Fiddle.
Hope this helps :)
Please reply if you know how to do this via the Select2 .ajax function, as that would be a bit shorter.
In my condition, it is working perfectly with the given code
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
And my data return from the ajax is in this form
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>

Categories