简体   繁体   中英

Call PHP function with javascript with a javascript parameter

I have this simple javascript which calls a PHP function flawlessly:

var showFeedPHP = "<?php showFeed($link, $category, $siteVersion, $cookie_index, $myuserlevel, $perPage, $showFrom); ?>";
$( "#sectionPosts" ).append( ""+showFeedPHP+"" );

I would like the last paramter, $showFrom, to be a javascript variable.

However, this version doesn't work and will just set the last parameter to the text string "+showFromJS+":

var showFromJS = 10;
var showFeedPHP = "<?php showFeed($link, $category, $siteVersion, $cookie_index, $myuserlevel, $perPage, "+showFromJS+"); ?>";
$( "#sectionPosts" ).append( ""+showFeedPHP+"" );

I would like to use a javascript variable for declaring one of the php function parameters, but how?

You have to use Ajax in this case here is a sample

    var showdeed= function(id) {
        $.ajax({
            url: 'path/to/php/file/showFeed',
            type: 'GET',
            data: {link:link,
          category:category,...},
            success: function(data) {
                $( "#sectionPosts" ).append( ""+data+"" );

            }
        });

};

You must use AJAX to achieve your objective

function loadData() {
    $.ajax({
    url: "path_to_showfeed.php?var1="+<?php echo json_encode($link);?>+"&var2="+<?php echo json_encode($category);?>+"&var3="....
    }).done(function(data) { 
    $( "#sectionPosts" ).append( ""+data+"" );
   });

 }

Also add this line to your head section

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

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