简体   繁体   中英

Passing specific Javascript variable to PHP

I have a multi dimensional session array in PHP( $_SESSION['playlist']['ID1'] , $_SESSION['playlist']['ID2'] ETC) with IDs stored as values. In javascript these can be deleted with the press of a button which will relay the value to a function in PHP to tell it to remove that value from the session array by matching the given ID and the one stored in the array. I can't get this to work. My JS is sending this $(wrapper).append("<?php delVid('"+vidID+"');?> "); but PHP acts like JS is sending a string, which I thought the quotes would make it do anyway but it was the only way I could get the variable to even properly transfer to PHP. here's my PHP function

function delVid($id){
    foreach( $_SESSION['playlist'] as $key => $value ) {
            if($id == $value){
                unset( $_SESSION['playlist'][ $key ] );
            }
        sort($_SESSION['playlist'], SORT_NUMERIC);
    }
}

It doesn't work the way you suppose. Appending HTML with JQuery doesn't run your server-side PHP script. So it is just a string appended to the wrapper which has no sense from code execution's point of view.

To make what you want to do, you need to use Ajax technology which consists in passing data to server without page reload. So you need to create a server side page which will accept your $id parameter and invoke your delVid function.

// ajaxScript.php (pseudo code)
// I don't know what framework and routing scheme are you using,
// so just a raw code to show an idea

<?php       

function delVid($id) {
    foreach($_SESSION['playlist'] as $key => $value) {
        if($id == $value) {
            unset($_SESSION['playlist'][$key]);
        }
        sort($_SESSION['playlist'], SORT_NUMERIC);
    }
}

delVid($_POST['id']);

Then you need to write JS code which will be perform Ajax request to that page on some event. JQuery has such useful methods as $.ajax , $.get and $.post to implement it.

jQuery(document).ready(function($){ 
  $(document).on("click",".remove", function(){ 
    var vidID = $(this).parent('div').parent('div').attr('id');             
    $(this).parent('div').parent('div').fadeOut();
    $.post('/ajaxScript.php', {id:vidId});
  }); 
});

You are trying to append to HTML a PHP function, which shows that you havem't understood how the client-server model works. PHP is a server side script, while JS and HTML are client side: so what you have to do is to use AJAX to send a request to your server with the proper parameters. But first of all you have to understand how PHP and JS work.

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