简体   繁体   中英

Is it possible to send the JS variable to parameter of the php function

Is it possible the Javascript variable value to the php url parameter? please see following code and give a suggestion how to do this? Html code:

foreach($rd as $data){
            echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td><a href=".$this->action('edit', $data['role_id']).">Edit</a></td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
        }

in this code i call JS function deleteRole?(): script:

function deleteRole(myvar) {
    if (confirm('<?php echo $delConfirmJS ?>')) {
       location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
    }
}

In my controller page i receive the myvar as string not the value? controller.php

public function delete($id){
    echo $id;
    exit;
    $delete = roleinfo::delete($id);
    $this->redirect('/role/add_role'); }

this echo print "myvar" only not a value? Please suggest me its write way or not ? else how to do this?

thanks Kumar

You can't send or assign a JS variable directly to PHP function or variable, because of JS is a client side language and PHP is a server side language.

If you want to send you JS variable, one way is - you can send a ajax request to server, and then your variable will be available in php, and can use it.

Here is sample ajax format:

$.ajax({
    cache: false,
    url: base_path + '{file_name_where_you_want_to_receive_that_value}',
    type: 'post',
    data: {
        myvar: myvar
    },
    success: function(data) {
        // when you provided url procedd the req. then success will call.

    }
})

And in [file_name_where_you_want_to_receive_that_value] assing that value to some variable and use it.

Do you have a form or smthg? I suppose the easiest way would be with a hidden field where you just modify the value via JS and send it to PHP with POST. Its not a clean or professional way, but easy to implement and does its job.

The most simple AJAX request you can make is the following (using jQuery for simplicity, you can search for how to do an AJAX request without jQuery):

function deleteRole(myvar) {
    $.ajax({
        url: "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>",
    }).done(function(data) {
        console.log(data);
        $( this ).addClass( "done" );
    });
}

This will create a new request to the specified URL, and basically run the controller action. You will have the request response in the javascript variable data.

More info here .

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