Capslock10 Capslock10 - 4 months ago 32
jQuery Question

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.


  1. 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.
    enter image description here



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?

Answer

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.