简体   繁体   中英

How to use jQuery to get variable from PHP

I am trying to get data from MySQL using ajax and jQuery. Right now, the only thing being returned is "0". Here is my PHP function:

function dallas_db_facebook_make_post () {
    global $wpdb;
    $query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
    $results = $wpdb->get_results($query, ARRAY_A);

    foreach($results as $result) {
        $fbpost =  $result['text'];
    }   

}

Here is my jQuery function:

function send_fb_post() {
    jQuery.ajax({
        type: "GET",
        url: my_ajax.ajaxurl,
        data: {
            'action': 'dallas_db_facebook_make_post'
        },
        beforeSend: function() {
        },
        success: function(data){

            console.log(data);

        },
        error: function(){
        },
    });
};

You are not getting anything, because you are not printing/echoing anything.

What happens if you try

foreach($results as $result) {
    echo $fbpost =  $result['text'];
}   

You code is not working because you are not print anything on server side. so you can small change in your code like below. jsonencode is use to return an array of data.

function dallas_db_facebook_make_post () {
    global $wpdb;
    $query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
    $results = $wpdb->get_results($query, ARRAY_A);

    $fbpost = array();

    foreach($results as $result) {
        $fbpost =  $result['text'];
    }   
    echo json_encode($fbpost);
    exit;
}

in response you json_encodeed data. You can decode and use this data using below function in response callback.

function send_fb_post() {
    jQuery.ajax({
        type: "GET",
        url: my_ajax.ajaxurl,
        data: {
            'action': 'dallas_db_facebook_make_post'
        },
        beforeSend: function() {
        },
        success: function(data){

            console.log(jQuery.parseJSON( data ));

        },
        error: function(){
        },
    });
};

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