简体   繁体   中英

Passing a PHP variable to JavaScript For AJAX Request

So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).

With attempt 2), I get a null when viewing its value in the web inspector.

The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):

$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
        function( data ) {
            console.log(topic_id);
            data = data.trim();
            if ( data !== "" ) {
                //get the participants data for avatars
                $.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {

The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.

    }


    //One attempt:     echo $content; //
    //Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}

?>

<script>

var topic_id = "<?php echo $row['topicid'] ?>";

</script>

Try this:

In php

$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array

In javascript

    var $url = '/wp-content/mu-plugins/topic-search.php';
    var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});

    $.ajax({
        url: $url,
        type: "POST",
        data: $json,
        dataType: "json",
        success: function(data){//you will have the body of the response in data
          //do something
        },
        error: function(data){
          //do something else
        }
    });

EDIT:

This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.

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