I am editing wordpress post template. And I want to call the PHP function in javascript, but my code doesn't work.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.