JM4
JM4

Reputation: 6798

Pass ID variable into a javascript function

I have the following link which opens a jquery modal window:

<div id='confirm-dialog'><a href='#' class='confirm'><img src='1.png' /></a></div>

and the following JS code which processes it:

jQuery(function ($) {
    $('#confirm-dialog input.confirm, #confirm-dialog a.confirm').click(function (e) {
        e.preventDefault();

        confirm("Are you sure you want to delete item id='IDNUMBER'.", function () {
            window.location.href = 'path to php process script';
        });
    });
});

function confirm(message, callback) {
    $('#confirm').modal({
        closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
        position: ["30%",],
        overlayId: 'confirm-overlay',
        containerId: 'confirm-container', 
        onShow: function (dialog) {
            var modal = this;

            $('.message', dialog.data[0]).append(message);

            // if the user clicks "yes"
            $('.yes', dialog.data[0]).click(function () {
                // call the callback
                if ($.isFunction(callback)) {
                    callback.apply();
                }
                // close the dialog
                modal.close(); // or $.modal.close();
            });
        }
    });
}

I am unable to solve two issues:

  1. How do I pass the ID variable (perhaps other variables) into the javascript function so that when I submit 'yes' on the confirmation window, the php path will include something like : http://www.pathtophp.com?ID=12345

  2. How do I display the ID variable within the popup text (shown as: ...delete item id="IDNUMBER"...)

Upvotes: 1

Views: 2783

Answers (2)

Daniel
Daniel

Reputation: 890

You could simply in the head of the page the PHP generates (before including the other JS files) add

<script type="text/javascript">
//Assumes id is passed in the URL
var id = <?php print $_GET['id'];?>;
</script>

Then the variable "id" is available to all JavaScript functions on the page.

Alternatively, if there are multiple links on the page you are wanting to apply this functionality to, you could add the id to the rel attribute of the anchor tag:

<a href="javascript:void(0)" class="confirm" rel="<?php print $id;?>">

Then you'll modify your jQuery function to

jQuery(function ($) {
    $('#confirm-dialog input.confirm, #confirm-dialog a.confirm').click(function (e) {
        e.preventDefault();

        confirm("Are you sure you want to delete item id='"+ e.currentTarget.rel +"'.", function () {
            window.location.href = 'http://www.pathtophp.com?ID=' + e.currentTarget.rel;
        });
    });
});

Upvotes: 2

kobe
kobe

Reputation: 15835

for 1 you can use like below

var value= "<%=value from server side%>"

Upvotes: 0

Related Questions