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
Related
I try to do an ajax request with wordpress. So I've created a simple js request:
$.ajax({
url: '?',
type: 'POST',
data: {
'pr_post': post,
'pr_rating': rating
},
success: function (response) {
console.log(response);
}
});
Here is my function to handle the request.
function pr_request()
{
if (isset($_REQUEST['pr_post']) && isset($_REQUEST['pr_rating']) && isset($_REQUEST['pr_user'])) {
$post = $_REQUEST['pr_post'];
$rating = ($_REQUEST['pr_rating'] > 5 ? 5 : $_REQUEST['pr_rating']);
$user = get_current_user_id();
if (!pr_has_user_already_voted($user, $post)) {
global $wpdb;
$table = $wpdb->prefix . 'mitmach_ratings';
$wpdb->query($wpdb->prepare("insert into $table values (null, $post, $rating, '$user');"));
wp_send_json(['message' => 'success']);
} else {
wp_send_json(['message' => 'duplicate'], 403);
}
}
}
As you see I call the get_current_user_id() function. This function always returns true even if the user logged in. How can I get the user id in my handler without sending it via ajax?
For a start check docs - WP Ajax.
You need to send action key
Notice how the 'action' key's value 'my_action', defined in our JavaScript above, matches the latter half of the action 'wp_ajax_my_action' in our AJAX handler below. This is because it is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process.
$.ajax({
url: '?',
type: 'POST',
data: {
action : 'pr_post',
pr_rating : rating
},
success: function (response) {
console.log(response);
}
});
and call like this:
add_action( 'wp_ajax_pr_request', 'pr_request' );
add_action( 'wp_ajax_nopriv_pr_request', 'pr_request' );
function pr_request() {
// Code
}
This question already has answers here:
Get response from PHP file using AJAX
(5 answers)
Closed 5 years ago.
I'm new to programming and i'm not good at all with Ajax.
I want to get a value back from a php script in Ajax.
I send a javascript variable to a php script like that :
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
});
return false;
}
});
This is sent to the following php script which is deleting messages according to the id contained in the checkboxIdArray:
if (isset($_POST['checkboxIdArray'])) {
$checkboxIdArray = $_POST['checkboxIdArray'];
$str = json_encode($checkboxIdArray);
$tab = explode(",", $str);
$deleteSuccess = true;
foreach($tab as $id)
{
$id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
if (!$messageModelDb->delete($id)) {
$deleteSuccess = false;
die();
}
}
if ($deleteSuccess === true) {
$message = 'Success';;
} else {
$message= "Error";
}
}
I want to get the $message variable back to my javascript in order to display a message according to the result of the script.
I would really appreciate some help ...
Thank you.
You have to use success function and actually include the message in the response
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
},
success : function(response){
// your code or logic
alert(response);
}
});
PHP
if ($deleteSuccess === true) {
$message = 'Success';
} else {
$message= "Error";
}
echo $message;
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
},
success: function(response){
alert(response);
}
});
return false;
}
});
There is nothing special about an HTTP request made with JavaScript.
You output data in the response to it in from PHP in the same way as any other HTTP response.
echo $message;
In JavaScript, you process it as described in the documentation for jQuery.ajax.
Write a function that accepts a the response content as the first argument.
Then call done on the jqXHR object that .ajax returns and pass it that function.
function handleResponse(data) {
alert(data);
}
var jqXHR = $.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
});
jqXHR.done(handleResponse);
Try out the code to get the value in ajax
<script>
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
}).done(function(result)
{
alert(result);
});
return false;
}
});
</script>
Here is the php code
<?php
if (isset($_POST['checkboxIdArray'])) {
$checkboxIdArray = $_POST['checkboxIdArray'];
$str = json_encode($checkboxIdArray);
$tab = explode(",", $str);
$deleteSuccess = true;
foreach($tab as $id)
{
$id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
if (!$messageModelDb->delete($id)) {
$deleteSuccess = false;
die();
}
}
if ($deleteSuccess === true) {
$message = 'Success';;
} else {
$message= "Error";
}
echo $message;
}
?>
Since jQuery implemented deferreds, .done is the preferred way to implement a success callback. You should also implement a .fail method with a failure response code.
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,
I have implemented jQuery autocomplete function for my web, which is working fine. But I want the result of the autocomplete to retrieve only the data of a particular person and not the complete database result.
Below is the jQuery for the autocomplete
jQuery(document).ready(function($){
$('.product_desc').autocomplete({source:'functions/products.php?', minLength:2});
products.php
//Path for the databsae
<?php
include '../include/configuration.php';
if ( !isset($_REQUEST['term']) )
exit;
$rs = mysql_query('select id,item_name,fk_vendor_id from item where item_name like "%'. mysql_real_escape_string($_REQUEST['term']).'%" order by item_name asc ', $con);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['item_name'],
'value' => $row['item_name']
);
}
}
else
{
$data[] = array(
'label' => 'not found',
'value' =>''
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
Any solution will be appreciated.
Try this:
$(".product_desc").autocomplete({
source: "functions/products.php",
minLength: 2,
select: function(event,ui){
//do something
}
});
Try this code, Any text field having class .search the auto complete suggestion will works on server side in ajax.php file you need to return array as below:
$response = ['Computer', 'Mouse', 'Keyboard', 'Monitor'];
echo json_encode($response);
Here is sample code for auto suggest.
$(document).on('keyups','.search',function() {
$(this).autocomplete({
source: function( request, response ) {
if (request.term != "") {
$.ajax({
url: "ajax.php",
dataType: "json",
method: "post",
data: {
name: request.term
},
success: function (data) {
if (data != "") {
response($.map(data, function (item) {
var name = item.name;
return {
label: name,
value: name,
data: item
}
}));
}
}
});
}
},
autoFocus: true,
minLength: 2,
select: function( event, ui ) {
var name = ui.item.data;
$(this).val(name);
}
});
});
I'm trying to send a message from php to ajax. I'm using echo json_encode to do it. When I do that, the website displays the arrays message. ({"foo":"content of foo"}). How can I get it to not display the message?
Also, the alerts from ajax don't get called.
Here's the code:
<?php
$myString = $_POST['data'];
if ($myString == "") {
echo json_encode(
array()
);
} else if ($myString == "foo" {
echo json_encode(
array(
'foo2' => 'this is the contents of foo'
)
);
} else if ($myString == "foo2") {
echo json_encode(
array(
'foo2' => 'this is the contents of foo2'
)
);
}
?>
<script>
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response) {
if (response.length == 0) {
alert("empty");
} else if (response.foo) {
alert("foo");
} else if (respons.foo2) {
alert("foo2");
}
}
});
</script>
How can I get the array to not display on the website? And why are the ajax if statements not getting called?
You need to set the HTTP header at the top of the script so you can return son:
header('Content-type: application/json');
Your script is a little confusing. You can't return json AND html/javascript.
It's one or the other.