简体   繁体   中英

Call PHP function and return value to Javascript

I am working with Wordpress and the Javascript will insert text in to the editor on the edit post.

I have two files, one is the js and another one is the PHP file. I want to call the PHP function to return the database value to the Javascript .

What I am doing:

I have [value - X] points. //The Javascript will insert this into the editor. [value - x] is the value which return from the PHP function

Here is my JavaScript :

   onsubmit: function( e ) 
{
var str = '';                                                                    
if(e.data.friend_cb ) 
{                                                                            
    str += 'I have [value - X] points. <br><br/>';
}

editor.insertContent(str);



jQuery.ajax({
    url: 'http://localhost:8080/wordpress/wp-content/plugins/databaseConnection.php',
    type: 'POST',
    data: {functionname: 'getX', condition_code: condition_code},
        error:function(data)
        {
            alert("failed");
            console.log(data);
        },
        success: function(data) 
        {
            alert("success");                                                                                
            console.log(data); // Inspect this in your console
        }
});

And here is the PHP function:

if( !isset($_POST['condition_code']) ) 
 {
      $error .= 'No function no_friend!';          
      $condition_code = $_POST['condition_code'];
 }

    $functionName  = $_POST['functionname'];
          // $functionName = 'add_bonus_point';
    switch($functionName) {
        case 'set_no_friend':  


             //Check did it pass the functionName
            if( !isset($_POST['functionname']))
                  $error .= 'No function name!'; 
            else
                 $errorBool = false;
            break;
        case 'try_insert':
            getX();
            break;
        }


 function getX()
 {
     $x = 0;
     //Connect to database, get X value.
     return $x;

 }

How can I get the value X?

Thx a lot.

First thing first. If you are working on wordpress , you should call ajax in wordpress way

See : https://codex.wordpress.org/AJAX_in_Plugins

Your javascript should be

onsubmit: function( e ) {
    var str = '';                                                                    
    if(e.data.friend_cb ) {                                                                            
        str += 'I have [value - X] points. <br><br/>';
    }

    editor.insertContent(str);

    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action:'my_ajax_function',
            functionname: 'getX', 
            condition_code: condition_code
        },
        error:function(data){
            alert("failed");
            console.log(data);
        },
        success: function(data) {
            alert("success");                                                                                
            console.log(data); // Inspect this in your console
        }
    });
}

Your PHP code should be

add_action( 'wp_ajax_my_ajax_function', 'my_ajax_function' );
add_action( 'wp_ajax_nopriv_my_ajax_function', 'my_ajax_function' );

function my_ajax_function(){
    if( !isset($_POST['condition_code']) ) {
          $error .= 'No function no_friend!';          
          $condition_code = $_POST['condition_code'];
    }

    $functionName  = $_POST['functionname'];
          // $functionName = 'add_bonus_point';
    switch($functionName) {
        case 'set_no_friend':  


             //Check did it pass the functionName
            if( !isset($_POST['functionname']))
                  $error .= 'No function name!'; 
            else
                 $errorBool = false;
            break;
        case 'try_insert':
            getX();
            break;
    }
}

function getX(){
     // access global variable $wpdb database connection object
     global $wpdb; 
     $x = 0;
     //Connect to database, get X value.
     return $x;
}

You can put json array for get data. Please write below code.

function getX()
 {
     $x = 0;
     //Connect to database, get X value.
     $data = array(
            "x"     => 0
          );
      echo json_encode($data);

 }

And Javascript code like below.

jQuery.ajax({
    url: 'http://localhost:8080/wordpress/wp-content/plugins/databaseConnection.php',
    type: 'POST',
    data: {functionname: 'getX', condition_code: condition_code},
        error:function(data)
        {
            alert("failed");
            console.log(data);
        },
        success: function(data) 
        {
            var obj = jQuery.parseJSON(data);
            alert( obj.x );

            console.log(obj); // Inspect this in your console
        }
});

for example

<script type="text/javascript">
  var phpVariable = "<?php
  $x = getX();
  echo $x;
  ?>";
</script>

store the php value into a javascript variable 1st, then use it in your javascript. Just make sure that this variable is declared and assigned value to before the script that uses it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM